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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3af1e2e8045b1b961ede0a5b013625fc7f0bf21f
| 1,437
|
hpp
|
C++
|
src/rewofs/messages.hpp
|
dsiroky/rewofs
|
4fac193bfcb0aecde46eed9d689dce76f037d4c2
|
[
"MIT"
] | 3
|
2020-04-21T10:06:42.000Z
|
2021-04-15T09:41:08.000Z
|
src/rewofs/messages.hpp
|
dsiroky/rewofs
|
4fac193bfcb0aecde46eed9d689dce76f037d4c2
|
[
"MIT"
] | null | null | null |
src/rewofs/messages.hpp
|
dsiroky/rewofs
|
4fac193bfcb0aecde46eed9d689dce76f037d4c2
|
[
"MIT"
] | null | null | null |
/// Messages support.
///
/// @file
#pragma once
#ifndef MESSAGES_HPP__78PIAARG
#define MESSAGES_HPP__78PIAARG
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "rewofs/messages/all.hpp"
//==========================================================================
namespace rewofs {
//==========================================================================
inline void copy(const timespec& src, messages::Time& dst)
{
dst.mutate_nsec(src.tv_nsec);
dst.mutate_sec(src.tv_sec);
}
//--------------------------------------------------------------------------
inline void copy(const messages::Time& src, timespec& dst)
{
dst.tv_nsec = src.nsec();
dst.tv_sec = src.sec();
}
//--------------------------------------------------------------------------
inline void copy(struct stat& src, messages::Stat& dst)
{
dst.mutate_st_mode(src.st_mode);
dst.mutate_st_size(src.st_size);
copy(src.st_ctim, dst.mutable_st_ctim());
copy(src.st_mtim, dst.mutable_st_mtim());
}
//--------------------------------------------------------------------------
inline void copy(const messages::Stat& src, struct stat& dst)
{
dst.st_mode = src.st_mode();
dst.st_size = src.st_size();
copy(src.st_ctim(), dst.st_ctim);
copy(src.st_mtim(), dst.st_mtim);
}
//==========================================================================
} // namespace rewofs
#endif /* include guard */
| 25.210526
| 76
| 0.463466
|
dsiroky
|
3afb034fa247a84a67c7cb0e73e7ce363f5115c2
| 15,765
|
hpp
|
C++
|
include/boost/wintls/stream.hpp
|
xiaoxiaozhu5/boost-wintls
|
93cb896500fbbad581e0362a133593f0e1b14d56
|
[
"BSL-1.0"
] | 6
|
2020-08-12T21:06:50.000Z
|
2020-08-30T17:23:27.000Z
|
include/boost/wintls/stream.hpp
|
xiaoxiaozhu5/boost-wintls
|
93cb896500fbbad581e0362a133593f0e1b14d56
|
[
"BSL-1.0"
] | 9
|
2020-09-22T08:55:25.000Z
|
2020-12-12T14:24:57.000Z
|
include/boost/wintls/stream.hpp
|
xiaoxiaozhu5/boost-wintls
|
93cb896500fbbad581e0362a133593f0e1b14d56
|
[
"BSL-1.0"
] | 1
|
2020-08-12T20:53:10.000Z
|
2020-08-12T20:53:10.000Z
|
//
// Copyright (c) 2020 Kasper Laudrup (laudrup at stacktrace dot dk)
//
// 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_WINTLS_STREAM_HPP
#define BOOST_WINTLS_STREAM_HPP
#include <boost/wintls/error.hpp>
#include <boost/wintls/handshake_type.hpp>
#include <boost/wintls/detail/async_handshake.hpp>
#include <boost/wintls/detail/async_read.hpp>
#include <boost/wintls/detail/async_shutdown.hpp>
#include <boost/wintls/detail/async_write.hpp>
#include <boost/wintls/detail/sspi_stream.hpp>
#include <boost/asio/compose.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/system/error_code.hpp>
#include <memory>
namespace boost {
namespace wintls {
/** Provides stream-oriented functionality using Windows SSPI/Schannel.
*
* The stream class template provides asynchronous and blocking
* stream-oriented functionality using Windows SSPI/Schannel.
*
* @tparam NextLayer The type representing the next layer, to which
* data will be read and written during operations. For synchronous
* operations, the type must support the <em>SyncStream</em> concept.
* For asynchronous operations, the type must support the
* <em>AsyncStream</em> concept.
*/
template<class NextLayer>
class stream {
public:
/// The type of the next layer.
using next_layer_type = typename std::remove_reference<NextLayer>::type;
/// The type of the executor associated with the object.
using executor_type = typename std::remove_reference<next_layer_type>::type::executor_type;
/** Construct a stream.
*
* This constructor creates a stream and initialises the underlying
* stream object.
*
* @param arg The argument to be passed to initialise the
* underlying stream.
* @param ctx The wintls @ref context to be used for the stream.
*/
template <class Arg>
stream(Arg&& arg, context& ctx)
: next_layer_(std::forward<Arg>(arg))
, sspi_stream_(std::make_unique<detail::sspi_stream>(ctx)) {
}
stream(stream&& other) = default;
stream& operator=(stream&& other) = delete;
/** Get the executor associated with the object.
*
* This function may be used to obtain the executor object that the
* stream uses to dispatch handlers for asynchronous operations.
*
* @return A copy of the executor that stream will use to dispatch
* handlers.
*/
executor_type get_executor() {
return next_layer().get_executor();
}
/** Get a reference to the next layer.
*
* This function returns a reference to the next layer in a stack of
* stream layers.
*
* @return A reference to the next layer in the stack of stream
* layers. Ownership is not transferred to the caller.
*/
const next_layer_type& next_layer() const {
return next_layer_;
}
/** Get a reference to the next layer.
*
* This function returns a reference to the next layer in a stack of
* stream layers.
*
* @return A reference to the next layer in the stack of stream
* layers. Ownership is not transferred to the caller.
*/
next_layer_type& next_layer() {
return next_layer_;
}
/** Set SNI hostname
*
* Sets the SNI hostname the client will use for requesting and
* validating the server certificate.
*
* Only used when handshake is performed as @ref
* handshake_type::client
*
* @param hostname The hostname to use in certificate validation
*/
void set_server_hostname(const std::string& hostname) {
sspi_stream_->handshake.set_server_hostname(hostname);
}
/** Perform TLS handshaking.
*
* This function is used to perform TLS handshaking on the
* stream. The function call will block until handshaking is
* complete or an error occurs.
*
* @param type The @ref handshake_type to be performed, i.e. client
* or server.
* @param ec Set to indicate what error occurred, if any.
*/
void handshake(handshake_type type, boost::system::error_code& ec) {
sspi_stream_->handshake(type);
detail::sspi_handshake::state state;
while((state = sspi_stream_->handshake()) != detail::sspi_handshake::state::done) {
switch (state) {
case detail::sspi_handshake::state::data_needed: {
std::size_t size_read = next_layer_.read_some(sspi_stream_->handshake.in_buffer(), ec);
if (ec) {
return;
}
sspi_stream_->handshake.size_read(size_read);
continue;
}
case detail::sspi_handshake::state::data_available: {
std::size_t size_written = net::write(next_layer_, sspi_stream_->handshake.out_buffer(), ec);
if (ec) {
return;
}
sspi_stream_->handshake.size_written(size_written);
continue;
}
case detail::sspi_handshake::state::error:
ec = sspi_stream_->handshake.last_error();
return;
case detail::sspi_handshake::state::done:
BOOST_UNREACHABLE_RETURN(0);
}
}
}
/** Perform TLS handshaking.
*
* This function is used to perform TLS handshaking on the
* stream. The function call will block until handshaking is
* complete or an error occurs.
*
* @param type The @ref handshake_type to be performed, i.e. client
* or server.
*
* @throws boost::system::system_error Thrown on failure.
*/
void handshake(handshake_type type) {
boost::system::error_code ec{};
handshake(type, ec);
if (ec) {
detail::throw_error(ec);
}
}
/** Start an asynchronous TLS handshake.
*
* This function is used to asynchronously perform an TLS
* handshake on the stream. This function call always returns
* immediately.
*
* @param type The @ref handshake_type to be performed, i.e. client
* or server.
* @param handler The handler to be called when the operation
* completes. The implementation takes ownership of the handler by
* performing a decay-copy. The handler must be invocable with this
* signature:
* @code
* void handler(
* boost::system::error_code // Result of operation.
* );
* @endcode
*
* @note Regardless of whether the asynchronous operation completes
* immediately or not, the handler will not be invoked from within
* this function. Invocation of the handler will be performed in a
* manner equivalent to using `net::post`.
*/
template <class CompletionToken>
auto async_handshake(handshake_type type, CompletionToken&& handler) {
return boost::asio::async_compose<CompletionToken, void(boost::system::error_code)>(
detail::async_handshake<next_layer_type>{next_layer_, sspi_stream_->handshake, type}, handler);
}
/** Read some data from the stream.
*
* This function is used to read data from the stream. The function
* call will block until one or more bytes of data has been read
* successfully, or until an error occurs.
*
* @param ec Set to indicate what error occurred, if any.
* @param buffers The buffers into which the data will be read.
*
* @returns The number of bytes read.
*
* @note The `read_some` operation may not read all of the requested
* number of bytes. Consider using the `net::read` function if you
* need to ensure that the requested amount of data is read before
* the blocking operation completes.
*/
template <class MutableBufferSequence>
size_t read_some(const MutableBufferSequence& buffers, boost::system::error_code& ec) {
detail::sspi_decrypt::state state;
while((state = sspi_stream_->decrypt(buffers)) == detail::sspi_decrypt::state::data_needed) {
std::size_t size_read = next_layer_.read_some(sspi_stream_->decrypt.input_buffer, ec);
if (ec) {
return 0;
}
sspi_stream_->decrypt.size_read(size_read);
continue;
}
if (state == detail::sspi_decrypt::state::error) {
ec = sspi_stream_->decrypt.last_error();
return 0;
}
return sspi_stream_->decrypt.size_decrypted;
}
/** Read some data from the stream.
*
* This function is used to read data from the stream. The function
* call will block until one or more bytes of data has been read
* successfully, or until an error occurs.
*
* @param buffers The buffers into which the data will be read.
*
* @returns The number of bytes read.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note The `read_some` operation may not read all of the requested
* number of bytes. Consider using the `net::read` function if you
* need to ensure that the requested amount of data is read before
* the blocking operation completes.
*/
template <class MutableBufferSequence>
size_t read_some(const MutableBufferSequence& buffers) {
boost::system::error_code ec{};
auto read = read_some(buffers, ec);
if (ec) {
detail::throw_error(ec);
}
return read;
}
/** Start an asynchronous read.
*
* This function is used to asynchronously read one or more bytes of
* data from the stream. The function call always returns
* immediately.
*
* @param buffers The buffers into which the data will be
* read. Although the buffers object may be copied as necessary,
* ownership of the underlying buffers is retained by the caller,
* which must guarantee that they remain valid until the handler is
* called.
* @param handler The handler to be called when the read operation
* completes. Copies will be made of the handler as required. The
* equivalent function signature of the handler must be:
* @code
* void handler(
* const boost::system::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes read.
* ); @endcode
*
* @note The `async_read_some` operation may not read all of the
* requested number of bytes. Consider using the `net::async_read`
* function if you need to ensure that the requested amount of data
* is read before the asynchronous operation completes.
*/
template <class MutableBufferSequence, class CompletionToken>
auto async_read_some(const MutableBufferSequence& buffers, CompletionToken&& handler) {
return boost::asio::async_compose<CompletionToken, void(boost::system::error_code, std::size_t)>(
detail::async_read<next_layer_type, MutableBufferSequence>{next_layer_, buffers, sspi_stream_->decrypt}, handler);
}
/** Write some data to the stream.
*
* This function is used to write data on the stream. The function
* call will block until one or more bytes of data has been written
* successfully, or until an error occurs.
*
* @param buffers The data to be written.
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes written.
*
* @note The `write_some` operation may not transmit all of the data
* to the peer. Consider using the `net::write` function if you need
* to ensure that all data is written before the blocking operation
* completes.
*/
template <class ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers, boost::system::error_code& ec) {
std::size_t bytes_consumed = sspi_stream_->encrypt(buffers, ec);
if (ec) {
return 0;
}
net::write(next_layer_, sspi_stream_->encrypt.buffers, ec);
if (ec) {
return 0;
}
return bytes_consumed;
}
/** Write some data to the stream.
*
* This function is used to write data on the stream. The function
* call will block until one or more bytes of data has been written
* successfully, or until an error occurs.
*
* @param buffers The data to be written.
*
* @returns The number of bytes written.
*
* @throws boost::system::system_error Thrown on failure.
*
* @note The `write_some` operation may not transmit all of the data
* to the peer. Consider using the `net::write` function if you need
* to ensure that all data is written before the blocking operation
* completes.
*/
template <class ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers) {
boost::system::error_code ec{};
auto wrote = write_some(buffers, ec);
if (ec) {
detail::throw_error(ec);
}
return wrote;
}
/** Start an asynchronous write.
*
* This function is used to asynchronously write one or more bytes
* of data to the stream. The function call always returns
* immediately.
*
* @param buffers The data to be written to the stream. Although the
* buffers object may be copied as necessary, ownership of the
* underlying buffers is retained by the caller, which must
* guarantee that they remain valid until the handler is called.
* @param handler The handler to be called when the write operation
* completes. Copies will be made of the handler as required. The
* equivalent function signature of the handler must be:
* @code
* void handler(
* const boost::system::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes written.
* );
* @endcode
*
* @note The `async_write_some` operation may not transmit all of
* the data to the peer. Consider using the `net::async_write`
* function if you need to ensure that all data is written before
* the asynchronous operation completes.
*/
template <class ConstBufferSequence, class CompletionToken>
auto async_write_some(const ConstBufferSequence& buffers, CompletionToken&& handler) {
return boost::asio::async_compose<CompletionToken, void(boost::system::error_code, std::size_t)>(
detail::async_write<next_layer_type, ConstBufferSequence>{next_layer_, buffers, sspi_stream_->encrypt}, handler);
}
/** Shut down TLS on the stream.
*
* This function is used to shut down TLS on the stream. The
* function call will block until TLS has been shut down or an
* error occurs.
*
* @param ec Set to indicate what error occurred, if any.
*/
void shutdown(boost::system::error_code& ec) {
ec = sspi_stream_->shutdown();
if (ec) {
return;
}
std::size_t size_written = net::write(next_layer_, sspi_stream_->shutdown.buffer(), ec);
if (!ec) {
sspi_stream_->shutdown.size_written(size_written);
}
}
/** Shut down TLS on the stream.
*
* This function is used to shut down TLS on the stream. The
* function call will block until TLS has been shut down or an error
* occurs.
*
* @throws boost::system::system_error Thrown on failure.
*/
void shutdown() {
boost::system::error_code ec{};
shutdown(ec);
if (ec) {
detail::throw_error(ec);
}
}
/** Asynchronously shut down TLS on the stream.
*
* This function is used to asynchronously shut down TLS on the
* stream. This function call always returns immediately.
*
* @param handler The handler to be called when the handshake
* operation completes. Copies will be made of the handler as
* required. The equivalent function signature of the handler must
* be:
* @code void handler(
* const boost::system::error_code& error // Result of operation.
*);
* @endcode
*/
template <class CompletionToken>
auto async_shutdown(CompletionToken&& handler) {
return boost::asio::async_compose<CompletionToken, void(boost::system::error_code)>(
detail::async_shutdown<next_layer_type>{next_layer_, sspi_stream_->shutdown}, handler);
}
private:
NextLayer next_layer_;
std::unique_ptr<detail::sspi_stream> sspi_stream_;
};
} // namespace wintls
} // namespace boost
#endif // BOOST_WINTLS_STREAM_HPP
| 34.72467
| 122
| 0.69242
|
xiaoxiaozhu5
|
3afcda5826f1abdbdc760346f6fd7073e043c3fa
| 1,400
|
cpp
|
C++
|
source/Test.cpp
|
MultiSight/multisight-buildy
|
516aaf31a448a6e64a22b3dd4fee462d0005ff25
|
[
"BSL-1.0"
] | null | null | null |
source/Test.cpp
|
MultiSight/multisight-buildy
|
516aaf31a448a6e64a22b3dd4fee462d0005ff25
|
[
"BSL-1.0"
] | null | null | null |
source/Test.cpp
|
MultiSight/multisight-buildy
|
516aaf31a448a6e64a22b3dd4fee462d0005ff25
|
[
"BSL-1.0"
] | null | null | null |
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// XSDK
// Copyright (c) 2015 Schneider Electric
//
// Use, modification, and distribution is subject to the Boost Software License,
// Version 1.0 (See accompanying file LICENSE).
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "Test.h"
#include "XSDK/XPath.h"
using namespace XSDK;
using namespace std;
void Test( XRef<Config> cfg, const XSDK::XString& tag )
{
XString configDir = cfg->GetConfigDir();
list<struct Component> components=(tag.length()>0) ? cfg->GetMatchingComponents(tag) : cfg->GetAllComponents();
int err = 0;
list<struct Component>::iterator i;
for( i = components.begin(); i != components.end(); i++ )
{
if( i->cleantest.length() > 0 )
{
err = system( XString::Format( "\"%s%s%s\" %s %s %s",
configDir.c_str(),
PATH_SLASH,
i->cleantest.c_str(),
i->name.c_str(),
(i->src.length() > 0) ? i->src.c_str() : "NO_SOURCE",
i->path.c_str() ).c_str() );
if( err != 0 )
X_THROW(("Test failure."));
}
}
}
| 33.333333
| 115
| 0.419286
|
MultiSight
|
3afdc74e2722fe07e0dc18fd3aad7fa7b40cc535
| 2,861
|
cpp
|
C++
|
app/GUI/immediate/BloodSplat.cpp
|
isonil/survival
|
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
|
[
"MIT"
] | 1
|
2017-05-12T10:12:41.000Z
|
2017-05-12T10:12:41.000Z
|
app/GUI/immediate/BloodSplat.cpp
|
isonil/Survival
|
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
|
[
"MIT"
] | null | null | null |
app/GUI/immediate/BloodSplat.cpp
|
isonil/Survival
|
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
|
[
"MIT"
] | 1
|
2019-01-09T04:05:36.000Z
|
2019-01-09T04:05:36.000Z
|
#include "BloodSplat.hpp"
#include "../../Global.hpp"
#include "../../Core.hpp"
#include "engine/util/Math.hpp"
#include "engine/app3D/Device.hpp"
#include "engine/GUI/GUIManager.hpp"
#include "engine/GUI/IGUIRenderer.hpp"
#include "engine/GUI/IGUITexture.hpp"
namespace app
{
BloodSplat::BloodSplat()
: m_reachedFullAlpha{},
m_lifeSpanTimer{k_lifeSpan},
m_alphaIncrease{0.f, InterpolationType::FixedStepLinear, k_alphaIncreaseStep},
m_alphaDecrease{1.f, InterpolationType::FixedStepLinear, k_alphaDecreaseStep},
m_stretchFactor{0.f, InterpolationType::FixedStepLinear, k_stretchFactorStep}
{
m_alphaIncrease.setTargetValue(1.f);
m_stretchFactor.setTargetValue(0.3f);
auto &device = Global::getCore().getDevice();
const auto &screenSize = device.getScreenSize();
engine::IntVec2 center{screenSize.x / 4 + engine::Random::rangeInclusive(0, screenSize.x / 2),
screenSize.y / 4 + engine::Random::rangeInclusive(0, screenSize.y / 2)};
E_DASSERT(!k_texturePaths.empty(), "There are no textures.");
int index{engine::Random::rangeExclusive(0, k_texturePaths.size())};
m_texture = device.getGUIManager().getRenderer().getTexture(k_texturePaths[index]);
float scaleFactor{static_cast <float> (screenSize.x) / m_texture->getSize().x * 0.7f};
const auto &textureSize = m_texture->getSize();
engine::IntVec2 size{static_cast <int> (textureSize.x * scaleFactor),
static_cast <int> (textureSize.y * scaleFactor)};
m_rect = {center - size / 2, size};
}
void BloodSplat::update()
{
m_alphaIncrease.update();
m_alphaDecrease.update();
m_stretchFactor.update();
if(engine::Math::fuzzyCompare(m_alphaIncrease.getCurrentValue(), 1.f))
m_reachedFullAlpha = true;
if(m_reachedFullAlpha && m_lifeSpanTimer.passed())
m_alphaDecrease.setTargetValue(0.f);
}
void BloodSplat::draw() const
{
E_DASSERT(m_texture, "Texture is nullptr.");
float alpha{};
if(m_reachedFullAlpha)
alpha = m_alphaDecrease.getCurrentValue();
else
alpha = m_alphaIncrease.getCurrentValue();
auto sizeY = static_cast <int> (m_rect.size.y + m_rect.size.y * m_stretchFactor.getCurrentValue());
m_texture->draw({m_rect.pos, {m_rect.size.x, sizeY}}, {1.f, 1.f, 1.f, alpha});
}
bool BloodSplat::wantsToBeRemoved() const
{
return m_lifeSpanTimer.passed() && engine::Math::fuzzyCompare(m_alphaDecrease.getCurrentValue(), 0.f);
}
const float BloodSplat::k_lifeSpan{3000.f};
const float BloodSplat::k_alphaIncreaseStep{7.f};
const float BloodSplat::k_alphaDecreaseStep{0.3f};
const float BloodSplat::k_stretchFactorStep{0.03f};
const std::vector <std::string> BloodSplat::k_texturePaths = {
"GUI/bloodSplat1.png",
"GUI/bloodSplat2.png",
"GUI/bloodSplat3.png"
};
} // namespace app
| 31.788889
| 106
| 0.701503
|
isonil
|
d7013ba1caf402de08b963abc04f796cef0d5360
| 104,252
|
cpp
|
C++
|
webkit/WebCore/rendering/RenderBlockLineLayout.cpp
|
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
|
3dd05f035e0a5fc9723300623e9b9b359be64e11
|
[
"Unlicense"
] | 15
|
2016-01-05T12:43:41.000Z
|
2022-03-15T10:34:47.000Z
|
webkit/WebCore/rendering/RenderBlockLineLayout.cpp
|
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
|
3dd05f035e0a5fc9723300623e9b9b359be64e11
|
[
"Unlicense"
] | null | null | null |
webkit/WebCore/rendering/RenderBlockLineLayout.cpp
|
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
|
3dd05f035e0a5fc9723300623e9b9b359be64e11
|
[
"Unlicense"
] | 2
|
2020-11-30T18:36:01.000Z
|
2021-02-05T23:20:24.000Z
|
/*
* Copyright (C) 2000 Lars Knoll (knoll@kde.org)
* Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009 Apple Inc. All right reserved.
* Copyright (c) 2010,2011 ACCESS CO., LTD. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "BidiResolver.h"
#include "CharacterNames.h"
#include "InlineTextBox.h"
#include "Logging.h"
#include "RenderArena.h"
#include "RenderInline.h"
#include "RenderListMarker.h"
#include "RenderView.h"
#include "break_lines.h"
#include <wtf/AlwaysInline.h>
#include <wtf/RefCountedLeakCounter.h>
#include <wtf/StdLibExtras.h>
#include <wtf/Vector.h>
#if ENABLE(WKC_ANDROID_LAYOUT)
#include "Frame.h"
#include "FrameTree.h"
#include "Settings.h"
#include "Text.h"
#include "HTMLNames.h"
#endif
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
// We don't let our line box tree for a single line get any deeper than this.
const unsigned cMaxLineDepth = 200;
class InlineIterator {
public:
InlineIterator()
: block(0)
, obj(0)
, pos(0)
, nextBreakablePosition(-1)
{
}
InlineIterator(RenderBlock* b, RenderObject* o, unsigned p)
: block(b)
, obj(o)
, pos(p)
, nextBreakablePosition(-1)
{
}
void increment(InlineBidiResolver* resolver = 0);
bool atEnd() const;
UChar current() const;
Direction direction() const;
RenderBlock* block;
RenderObject* obj;
unsigned pos;
int nextBreakablePosition;
};
static int getBorderPaddingMargin(RenderBoxModelObject* child, bool endOfInline)
{
bool leftSide = (child->style()->direction() == LTR) ? !endOfInline : endOfInline;
if (leftSide)
return child->marginLeft() + child->paddingLeft() + child->borderLeft();
return child->marginRight() + child->paddingRight() + child->borderRight();
}
static int inlineWidth(RenderObject* child, bool start = true, bool end = true)
{
unsigned lineDepth = 1;
int extraWidth = 0;
RenderObject* parent = child->parent();
while (parent->isInline() && !parent->isInlineBlockOrInlineTable() && lineDepth++ < cMaxLineDepth) {
if (start && !child->previousSibling())
extraWidth += getBorderPaddingMargin(toRenderBoxModelObject(parent), false);
if (end && !child->nextSibling())
extraWidth += getBorderPaddingMargin(toRenderBoxModelObject(parent), true);
child = parent;
parent = child->parent();
}
return extraWidth;
}
struct BidiRun : BidiCharacterRun {
BidiRun(int start, int stop, RenderObject* object, BidiContext* context, Direction dir)
: BidiCharacterRun(start, stop, context, dir)
, m_object(object)
, m_box(0)
{
}
void destroy();
// Overloaded new operator.
#if PLATFORM(WKC) && COMPILER(RVCT)
void* operator new(size_t, RenderArena*);
#else
void* operator new(size_t, RenderArena*) throw();
#endif
// Overridden to prevent the normal delete from being called.
void operator delete(void*, size_t);
BidiRun* next() { return static_cast<BidiRun*>(m_next); }
private:
// The normal operator new is disallowed.
#if PLATFORM(WKC) && COMPILER(RVCT)
void* operator new(size_t);
#else
void* operator new(size_t) throw();
#endif
public:
RenderObject* m_object;
InlineBox* m_box;
};
#ifndef NDEBUG
#if PLATFORM(WKC)
static RefCountedLeakCounter* bidiRunCounter;
#else
static RefCountedLeakCounter bidiRunCounter("BidiRun");
#endif
static bool inBidiRunDestroy;
#endif
void BidiRun::destroy()
{
#ifndef NDEBUG
inBidiRunDestroy = true;
#endif
RenderArena* renderArena = m_object->renderArena();
delete this;
#ifndef NDEBUG
inBidiRunDestroy = false;
#endif
// Recover the size left there for us by operator delete and free the memory.
#if defined(ENABLE_REPLACEMENT_FASTMALLOC) || defined(_CRTDBG_MAP_ALLOC)
renderArena->renderarena_free(*reinterpret_cast<size_t*>(this), this);
#else
renderArena->free(*reinterpret_cast<size_t*>(this), this);
#endif
}
#if PLATFORM(WKC) && COMPILER(RVCT)
void* BidiRun::operator new(size_t sz, RenderArena* renderArena)
#else
void* BidiRun::operator new(size_t sz, RenderArena* renderArena) throw()
#endif
{
#ifndef NDEBUG
#if PLATFORM(WKC)
if (!bidiRunCounter) {
bidiRunCounter = new RefCountedLeakCounter("BidiRun");
}
bidiRunCounter->increment();
#else
bidiRunCounter.increment();
#endif
#endif
return renderArena->allocate(sz);
}
void BidiRun::operator delete(void* ptr, size_t sz)
{
#ifndef NDEBUG
#if PLATFORM(WKC)
bidiRunCounter->decrement();
#else
bidiRunCounter.decrement();
#endif
#endif
ASSERT(inBidiRunDestroy);
// Stash size where destroy() can find it.
*(size_t*)ptr = sz;
}
// ---------------------------------------------------------------------
inline bool operator==(const InlineIterator& it1, const InlineIterator& it2)
{
return it1.pos == it2.pos && it1.obj == it2.obj;
}
inline bool operator!=(const InlineIterator& it1, const InlineIterator& it2)
{
return it1.pos != it2.pos || it1.obj != it2.obj;
}
static inline RenderObject* bidiNext(RenderBlock* block, RenderObject* current, InlineBidiResolver* resolver = 0, bool skipInlines = true, bool* endOfInlinePtr = 0)
{
RenderObject* next = 0;
bool oldEndOfInline = endOfInlinePtr ? *endOfInlinePtr : false;
bool endOfInline = false;
while (current) {
next = 0;
if (!oldEndOfInline && !current->isFloating() && !current->isReplaced() && !current->isPositioned() && !current->isText()) {
next = current->firstChild();
if (next && resolver && next->isRenderInline()) {
EUnicodeBidi ub = next->style()->unicodeBidi();
if (ub != UBNormal) {
TextDirection dir = next->style()->direction();
Direction d = (ub == Embed
? (dir == RTL ? RightToLeftEmbedding : LeftToRightEmbedding)
: (dir == RTL ? RightToLeftOverride : LeftToRightOverride));
resolver->embed(d);
}
}
}
if (!next) {
if (!skipInlines && !oldEndOfInline && current->isRenderInline()) {
next = current;
endOfInline = true;
break;
}
while (current && current != block) {
if (resolver && current->isRenderInline() && current->style()->unicodeBidi() != UBNormal)
resolver->embed(PopDirectionalFormat);
next = current->nextSibling();
if (next) {
if (resolver && next->isRenderInline()) {
EUnicodeBidi ub = next->style()->unicodeBidi();
if (ub != UBNormal) {
TextDirection dir = next->style()->direction();
Direction d = (ub == Embed
? (dir == RTL ? RightToLeftEmbedding: LeftToRightEmbedding)
: (dir == RTL ? RightToLeftOverride : LeftToRightOverride));
resolver->embed(d);
}
}
break;
}
current = current->parent();
if (!skipInlines && current && current != block && current->isRenderInline()) {
next = current;
endOfInline = true;
break;
}
}
}
if (!next)
break;
if (next->isText() || next->isFloating() || next->isReplaced() || next->isPositioned()
|| ((!skipInlines || !next->firstChild()) // Always return EMPTY inlines.
&& next->isRenderInline()))
break;
current = next;
}
if (endOfInlinePtr)
*endOfInlinePtr = endOfInline;
return next;
}
static RenderObject* bidiFirst(RenderBlock* block, InlineBidiResolver* resolver, bool skipInlines = true)
{
if (!block->firstChild())
return 0;
RenderObject* o = block->firstChild();
if (o->isRenderInline()) {
if (resolver) {
EUnicodeBidi ub = o->style()->unicodeBidi();
if (ub != UBNormal) {
TextDirection dir = o->style()->direction();
Direction d = (ub == Embed
? (dir == RTL ? RightToLeftEmbedding : LeftToRightEmbedding)
: (dir == RTL ? RightToLeftOverride : LeftToRightOverride));
resolver->embed(d);
}
}
if (skipInlines && o->firstChild())
o = bidiNext(block, o, resolver, skipInlines);
else {
// Never skip empty inlines.
if (resolver)
resolver->commitExplicitEmbedding();
return o;
}
}
if (o && !o->isText() && !o->isReplaced() && !o->isFloating() && !o->isPositioned())
o = bidiNext(block, o, resolver, skipInlines);
if (resolver)
resolver->commitExplicitEmbedding();
return o;
}
inline void InlineIterator::increment(InlineBidiResolver* resolver)
{
if (!obj)
return;
if (obj->isText()) {
pos++;
if (pos >= toRenderText(obj)->textLength()) {
obj = bidiNext(block, obj, resolver);
pos = 0;
nextBreakablePosition = -1;
}
} else {
obj = bidiNext(block, obj, resolver);
pos = 0;
nextBreakablePosition = -1;
}
}
template<>
inline void InlineBidiResolver::increment()
{
current.increment(this);
}
inline bool InlineIterator::atEnd() const
{
return !obj;
}
inline UChar InlineIterator::current() const
{
if (!obj || !obj->isText())
return 0;
RenderText* text = toRenderText(obj);
if (pos >= text->textLength())
return 0;
return text->characters()[pos];
}
ALWAYS_INLINE Direction InlineIterator::direction() const
{
if (UChar c = current())
return Unicode::direction(c);
if (obj && obj->isListMarker())
return obj->style()->direction() == LTR ? LeftToRight : RightToLeft;
return OtherNeutral;
}
// -------------------------------------------------------------------------------------------------
static void chopMidpointsAt(LineMidpointState& lineMidpointState, RenderObject* obj, unsigned pos)
{
if (!lineMidpointState.numMidpoints)
return;
InlineIterator* midpoints = lineMidpointState.midpoints.data();
for (int i = lineMidpointState.numMidpoints - 1; i >= 0; i--) {
const InlineIterator& point = midpoints[i];
if (point.obj == obj && point.pos == pos) {
lineMidpointState.numMidpoints = i;
break;
}
}
}
static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
{
// Check to see if our last midpoint is a start point beyond the line break. If so,
// shave it off the list, and shave off a trailing space if the previous end point doesn't
// preserve whitespace.
if (lBreak.obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
InlineIterator* midpoints = lineMidpointState.midpoints.data();
InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
InlineIterator currpoint = endpoint;
while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
currpoint.increment();
if (currpoint == lBreak) {
// We hit the line break before the start point. Shave off the start point.
lineMidpointState.numMidpoints--;
if (endpoint.obj->style()->collapseWhiteSpace()) {
if (endpoint.obj->isText()) {
// Don't shave a character off the endpoint if it was from a soft hyphen.
RenderText* textObj = toRenderText(endpoint.obj);
if (endpoint.pos + 1 < textObj->textLength()) {
if (textObj->characters()[endpoint.pos+1] == softHyphen)
return;
} else if (startpoint.obj->isText()) {
RenderText *startText = toRenderText(startpoint.obj);
if (startText->textLength() && startText->characters()[0] == softHyphen)
return;
}
}
endpoint.pos--;
}
}
}
}
static void addMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
{
if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
InlineIterator* midpoints = lineMidpointState.midpoints.data();
midpoints[lineMidpointState.numMidpoints++] = midpoint;
}
static void appendRunsForObject(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
{
if (start > end || obj->isFloating() ||
(obj->isPositioned() && !obj->style()->hasStaticX() && !obj->style()->hasStaticY() && !obj->container()->isRenderInline()))
return;
LineMidpointState& lineMidpointState = resolver.midpointState();
bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
InlineIterator nextMidpoint;
if (haveNextMidpoint)
nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
if (lineMidpointState.betweenMidpoints) {
if (!(haveNextMidpoint && nextMidpoint.obj == obj))
return;
// This is a new start point. Stop ignoring objects and
// adjust our start.
lineMidpointState.betweenMidpoints = false;
start = nextMidpoint.pos;
lineMidpointState.currentMidpoint++;
if (start < end)
return appendRunsForObject(start, end, obj, resolver);
} else {
if (!haveNextMidpoint || (obj != nextMidpoint.obj)) {
resolver.addRun(new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir()));
return;
}
// An end midpoint has been encountered within our object. We
// need to go ahead and append a run with our endpoint.
if (static_cast<int>(nextMidpoint.pos + 1) <= end) {
lineMidpointState.betweenMidpoints = true;
lineMidpointState.currentMidpoint++;
if (nextMidpoint.pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
if (static_cast<int>(nextMidpoint.pos + 1) > start)
resolver.addRun(new (obj->renderArena())
BidiRun(start, nextMidpoint.pos + 1, obj, resolver.context(), resolver.dir()));
return appendRunsForObject(nextMidpoint.pos + 1, end, obj, resolver);
}
} else
resolver.addRun(new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir()));
}
}
template <>
void InlineBidiResolver::appendRun()
{
if (!emptyRun && !eor.atEnd()) {
int start = sor.pos;
RenderObject *obj = sor.obj;
while (obj && obj != eor.obj && obj != endOfLine.obj) {
appendRunsForObject(start, obj->length(), obj, *this);
start = 0;
obj = bidiNext(sor.block, obj);
}
if (obj) {
unsigned pos = obj == eor.obj ? eor.pos : UINT_MAX;
if (obj == endOfLine.obj && endOfLine.pos <= pos) {
reachedEndOfLine = true;
pos = endOfLine.pos;
}
// It's OK to add runs for zero-length RenderObjects, just don't make the run larger than it should be
int end = obj->length() ? pos+1 : 0;
appendRunsForObject(start, end, obj, *this);
}
eor.increment();
sor = eor;
}
m_direction = OtherNeutral;
m_status.eor = OtherNeutral;
}
static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
{
if (isRootLineBox)
return toRenderBlock(obj)->createAndAppendRootInlineBox();
if (obj->isText()) {
InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
// We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
// (Note the use of strict mode. In "almost strict" mode, we don't treat the box for <br> as text.)
if (obj->isBR())
textBox->setIsText(isOnlyRun || obj->document()->inStrictMode());
return textBox;
}
if (obj->isBox())
return toRenderBox(obj)->createInlineBox();
return toRenderInline(obj)->createAndAppendInlineFlowBox();
}
static inline void dirtyLineBoxesForRenderer(RenderObject* o, bool fullLayout)
{
if (o->isText()) {
if (o->prefWidthsDirty() && o->isCounter())
toRenderText(o)->calcPrefWidths(0); // FIXME: Counters depend on this hack. No clue why. Should be investigated and removed.
toRenderText(o)->dirtyLineBoxes(fullLayout);
} else
toRenderInline(o)->dirtyLineBoxes(fullLayout);
}
InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, bool firstLine)
{
// See if we have an unconstructed line box for this object that is also
// the last item on the line.
unsigned lineDepth = 1;
InlineFlowBox* childBox = 0;
InlineFlowBox* parentBox = 0;
InlineFlowBox* result = 0;
do {
ASSERT(obj->isRenderInline() || obj == this);
// Get the last box we made for this render object.
parentBox = obj->isRenderInline() ? toRenderInline(obj)->lastLineBox() : toRenderBlock(obj)->lastLineBox();
// If this box is constructed then it is from a previous line, and we need
// to make a new box for our line. If this box is unconstructed but it has
// something following it on the line, then we know we have to make a new box
// as well. In this situation our inline has actually been split in two on
// the same line (this can happen with very fancy language mixtures).
bool constructedNewBox = false;
if (!parentBox || parentBox->isConstructed() || parentBox->nextOnLine()) {
// We need to make a new box for this render object. Once
// made, we need to place it at the end of the current line.
InlineBox* newBox = createInlineBoxForRenderer(obj, obj == this);
ASSERT(newBox->isInlineFlowBox());
parentBox = static_cast<InlineFlowBox*>(newBox);
parentBox->setFirstLineStyleBit(firstLine);
constructedNewBox = true;
}
if (!result)
result = parentBox;
// If we have hit the block itself, then |box| represents the root
// inline box for the line, and it doesn't have to be appended to any parent
// inline.
if (childBox)
parentBox->addToLine(childBox);
if (!constructedNewBox || obj == this)
break;
childBox = parentBox;
// If we've exceeded our line depth, then jump straight to the root and skip all the remaining
// intermediate inline flows.
obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
} while (true);
return result;
}
RootInlineBox* RenderBlock::constructLine(unsigned runCount, BidiRun* firstRun, BidiRun* lastRun, bool firstLine, bool lastLine, RenderObject* endObject)
{
ASSERT(firstRun);
InlineFlowBox* parentBox = 0;
for (BidiRun* r = firstRun; r; r = r->next()) {
// Create a box for our object.
bool isOnlyRun = (runCount == 1);
if (runCount == 2 && !r->m_object->isListMarker())
isOnlyRun = ((style()->direction() == RTL) ? lastRun : firstRun)->m_object->isListMarker();
InlineBox* box = createInlineBoxForRenderer(r->m_object, false, isOnlyRun);
r->m_box = box;
ASSERT(box);
if (!box)
continue;
// If we have no parent box yet, or if the run is not simply a sibling,
// then we need to construct inline boxes as necessary to properly enclose the
// run's inline box.
if (!parentBox || parentBox->renderer() != r->m_object->parent())
// Create new inline boxes all the way back to the appropriate insertion point.
parentBox = createLineBoxes(r->m_object->parent(), firstLine);
// Append the inline box to this line.
parentBox->addToLine(box);
bool visuallyOrdered = r->m_object->style()->visuallyOrdered();
box->setBidiLevel(visuallyOrdered ? 0 : r->level());
if (box->isInlineTextBox()) {
InlineTextBox* text = static_cast<InlineTextBox*>(box);
text->setStart(r->m_start);
text->setLen(r->m_stop - r->m_start);
text->m_dirOverride = r->dirOverride(visuallyOrdered);
}
}
// We should have a root inline box. It should be unconstructed and
// be the last continuation of our line list.
ASSERT(lastLineBox() && !lastLineBox()->isConstructed());
// Set bits on our inline flow boxes that indicate which sides should
// paint borders/margins/padding. This knowledge will ultimately be used when
// we determine the horizontal positions and widths of all the inline boxes on
// the line.
lastLineBox()->determineSpacingForFlowBoxes(lastLine, endObject);
// Now mark the line boxes as being constructed.
lastLineBox()->setConstructed();
// Return the last line.
return lastRootBox();
}
void RenderBlock::computeHorizontalPositionsForLine(RootInlineBox* lineBox, bool firstLine, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd)
{
// First determine our total width.
int availableWidth = lineWidth(height(), firstLine);
int totWidth = lineBox->getFlowSpacingWidth();
bool needsWordSpacing = false;
unsigned numSpaces = 0;
ETextAlign textAlign = style()->textAlign();
for (BidiRun* r = firstRun; r; r = r->next()) {
if (!r->m_box || r->m_object->isPositioned() || r->m_box->isLineBreak())
continue; // Positioned objects are only participating to figure out their
// correct static x position. They have no effect on the width.
// Similarly, line break boxes have no effect on the width.
if (r->m_object->isText()) {
RenderText* rt = toRenderText(r->m_object);
if (textAlign == JUSTIFY && r != trailingSpaceRun) {
const UChar* characters = rt->characters();
for (int i = r->m_start; i < r->m_stop; i++) {
UChar c = characters[i];
if (c == ' ' || c == '\n' || c == '\t')
numSpaces++;
}
}
if (int length = rt->textLength()) {
if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
totWidth += rt->style(firstLine)->font().wordSpacing();
needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;
}
HashSet<const SimpleFontData*> fallbackFonts;
r->m_box->setWidth(rt->width(r->m_start, r->m_stop - r->m_start, totWidth, firstLine, &fallbackFonts));
if (!fallbackFonts.isEmpty()
#if ENABLE(SVG)
&& !isSVGText()
#endif
) {
ASSERT(r->m_box->isText());
static_cast<InlineTextBox*>(r->m_box)->setFallbackFonts(fallbackFonts);
}
} else if (!r->m_object->isRenderInline()) {
RenderBox* renderBox = toRenderBox(r->m_object);
renderBox->calcWidth();
r->m_box->setWidth(renderBox->width());
totWidth += renderBox->marginLeft() + renderBox->marginRight();
}
totWidth += r->m_box->width();
}
// Armed with the total width of the line (without justification),
// we now examine our text-align property in order to determine where to position the
// objects horizontally. The total width of the line can be increased if we end up
// justifying text.
int x = leftOffset(height(), firstLine);
switch (textAlign) {
case LEFT:
case WEBKIT_LEFT:
// The direction of the block should determine what happens with wide lines. In
// particular with RTL blocks, wide lines should still spill out to the left.
if (style()->direction() == LTR) {
if (totWidth > availableWidth && trailingSpaceRun)
trailingSpaceRun->m_box->setWidth(max(0, trailingSpaceRun->m_box->width() - totWidth + availableWidth));
} else {
if (trailingSpaceRun)
trailingSpaceRun->m_box->setWidth(0);
else if (totWidth > availableWidth)
x -= (totWidth - availableWidth);
}
break;
case JUSTIFY:
if (numSpaces && !reachedEnd && !lineBox->endsWithBreak()) {
if (trailingSpaceRun) {
totWidth -= trailingSpaceRun->m_box->width();
trailingSpaceRun->m_box->setWidth(0);
}
break;
}
// fall through
case TAAUTO:
numSpaces = 0;
// for right to left fall through to right aligned
if (style()->direction() == LTR) {
if (totWidth > availableWidth && trailingSpaceRun)
trailingSpaceRun->m_box->setWidth(max(0, trailingSpaceRun->m_box->width() - totWidth + availableWidth));
break;
}
case RIGHT:
case WEBKIT_RIGHT:
// Wide lines spill out of the block based off direction.
// So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
// side of the block.
if (style()->direction() == LTR) {
if (trailingSpaceRun) {
totWidth -= trailingSpaceRun->m_box->width();
trailingSpaceRun->m_box->setWidth(0);
}
if (totWidth < availableWidth)
x += availableWidth - totWidth;
} else {
if (totWidth > availableWidth && trailingSpaceRun) {
trailingSpaceRun->m_box->setWidth(max(0, trailingSpaceRun->m_box->width() - totWidth + availableWidth));
totWidth -= trailingSpaceRun->m_box->width();
} else
x += availableWidth - totWidth;
}
break;
case CENTER:
case WEBKIT_CENTER:
int trailingSpaceWidth = 0;
if (trailingSpaceRun) {
totWidth -= trailingSpaceRun->m_box->width();
trailingSpaceWidth = min(trailingSpaceRun->m_box->width(), (availableWidth - totWidth + 1) / 2);
trailingSpaceRun->m_box->setWidth(max(0, trailingSpaceWidth));
}
if (style()->direction() == LTR)
x += max((availableWidth - totWidth) / 2, 0);
else
x += totWidth > availableWidth ? (availableWidth - totWidth) : (availableWidth - totWidth) / 2 - trailingSpaceWidth;
break;
}
if (numSpaces) {
for (BidiRun* r = firstRun; r; r = r->next()) {
if (!r->m_box || r == trailingSpaceRun)
continue;
int spaceAdd = 0;
if (r->m_object->isText()) {
unsigned spaces = 0;
const UChar* characters = toRenderText(r->m_object)->characters();
for (int i = r->m_start; i < r->m_stop; i++) {
UChar c = characters[i];
if (c == ' ' || c == '\n' || c == '\t')
spaces++;
}
ASSERT(spaces <= numSpaces);
// Only justify text if whitespace is collapsed.
if (r->m_object->style()->collapseWhiteSpace()) {
spaceAdd = (availableWidth - totWidth) * spaces / numSpaces;
static_cast<InlineTextBox*>(r->m_box)->setSpaceAdd(spaceAdd);
totWidth += spaceAdd;
}
numSpaces -= spaces;
if (!numSpaces)
break;
}
}
}
// The widths of all runs are now known. We can now place every inline box (and
// compute accurate widths for the inline flow boxes).
needsWordSpacing = false;
lineBox->placeBoxesHorizontally(x, needsWordSpacing);
}
void RenderBlock::computeVerticalPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun)
{
setHeight(lineBox->verticallyAlignBoxes(height()));
lineBox->setBlockHeight(height());
// Now make sure we place replaced render objects correctly.
for (BidiRun* r = firstRun; r; r = r->next()) {
ASSERT(r->m_box);
if (!r->m_box)
continue; // Skip runs with no line boxes.
// Align positioned boxes with the top of the line box. This is
// a reasonable approximation of an appropriate y position.
if (r->m_object->isPositioned())
r->m_box->setY(height());
// Position is used to properly position both replaced elements and
// to update the static normal flow x/y of positioned elements.
if (r->m_object->isText())
toRenderText(r->m_object)->positionLineBox(r->m_box);
else if (r->m_object->isBox())
toRenderBox(r->m_object)->positionLineBox(r->m_box);
}
// Positioned objects and zero-length text nodes destroy their boxes in
// position(), which unnecessarily dirties the line.
lineBox->markDirty(false);
}
// collects one line of the paragraph and transforms it to visual order
void RenderBlock::bidiReorderLine(InlineBidiResolver& resolver, const InlineIterator& end, bool previousLineBrokeCleanly)
{
#if PLATFORM(WKC)
// This will give an application a chance to break heavy loop. 0 is dummy.
wkcMemoryCheckAvailabilityPeer(0);
#endif
resolver.createBidiRunsForLine(end, style()->visuallyOrdered(), previousLineBrokeCleanly);
}
static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
{
if (character == ' ' || character == '\t' || character == softHyphen)
return true;
if (character == '\n')
return !renderer->style()->preserveNewline();
if (character == noBreakSpace)
return renderer->style()->nbspMode() == SPACE;
return false;
}
void RenderBlock::layoutInlineChildren(bool relayoutChildren, int& repaintTop, int& repaintBottom)
{
bool useRepaintBounds = false;
m_overflow.clear();
setHeight(borderTop() + paddingTop());
int toAdd = borderBottom() + paddingBottom() + horizontalScrollbarHeight();
// Figure out if we should clear out our line boxes.
// FIXME: Handle resize eventually!
bool fullLayout = !firstLineBox() || !firstChild() || selfNeedsLayout() || relayoutChildren;
if (fullLayout)
lineBoxes()->deleteLineBoxes(renderArena());
// Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
// clip.
// FIXME: CSS3 says that descendants that are clipped must also know how to truncate. This is insanely
// difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
// anyway, so we won't worry about following the draft here.
bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
// Walk all the lines and delete our ellipsis line boxes if they exist.
if (hasTextOverflow)
deleteEllipsisLineBoxes();
if (firstChild()) {
#if ENABLE(WKC_ANDROID_LAYOUT)
// if we are in fitColumnToScreen mode and viewport width is not device-width,
// and the current object is not float:right in LTR or not float:left in RTL,
// and text align is auto, or justify or left in LTR, or right in RTL, we
// will wrap text around screen width so that it doesn't need to scroll
// horizontally when reading a paragraph.
const Settings* settings = document()->settings();
bool doTextWrap = settings && settings->viewportWidth() != 0 &&
settings->layoutAlgorithm() == Settings::kLayoutFitColumnToScreen;
if (doTextWrap) {
int ta = style()->textAlign();
int dir = style()->direction();
bool autowrap = style()->autoWrap();
// if the RenderBlock is positioned, don't wrap text around screen
// width as it may cause text to overlap.
bool positioned = isPositioned();
EFloat cssfloat = style()->floating();
doTextWrap = autowrap && !positioned &&
(((dir == LTR && cssfloat != FRIGHT) ||
(dir == RTL && cssfloat != FLEFT)) &&
((ta == TAAUTO) || (ta == JUSTIFY) ||
((ta == LEFT || ta == WEBKIT_LEFT) && (dir == LTR)) ||
((ta == RIGHT || ta == WEBKIT_RIGHT) && (dir == RTL))));
}
bool hasTextToWrap = false;
#endif
// layout replaced elements
bool endOfInline = false;
RenderObject* o = bidiFirst(this, 0, false);
Vector<FloatWithRect> floats;
while (o) {
if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
RenderBox* box = toRenderBox(o);
if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
o->setChildNeedsLayout(true, false);
// If relayoutChildren is set and we have percentage padding, we also need to invalidate the child's pref widths.
if (relayoutChildren && (o->style()->paddingLeft().isPercent() || o->style()->paddingRight().isPercent()))
o->setPrefWidthsDirty(true, false);
if (o->isPositioned())
o->containingBlock()->insertPositionedObject(box);
else {
#if ENABLE(WKC_ANDROID_LAYOUT)
// ignore text wrap for textField or menuList
if (doTextWrap && (o->isTextField() || o->isMenuList()))
doTextWrap = false;
#endif
if (o->isFloating())
floats.append(FloatWithRect(box));
else if (fullLayout || o->needsLayout()) // Replaced elements
toRenderBox(o)->dirtyLineBoxes(fullLayout);
o->layoutIfNeeded();
}
} else if (o->isText() || (o->isRenderInline() && !endOfInline)) {
if (fullLayout || o->selfNeedsLayout())
dirtyLineBoxesForRenderer(o, fullLayout);
o->setNeedsLayout(false);
#if ENABLE(WKC_ANDROID_LAYOUT)
if (doTextWrap && !hasTextToWrap && o->isText()) {
Node* node = o->node();
// as it is very common for sites to use a serial of <a> or
// <li> as tabs, we don't force text to wrap if all the text
// are short and within an <a> or <li> tag, and only separated
// by short word like "|" or ";".
if (node && node->isTextNode() &&
!static_cast<Text*>(node)->containsOnlyWhitespace()) {
int length = static_cast<Text*>(node)->length();
// FIXME, need a magic number to decide it is too long to
// be a tab. Pick 25 for now as it covers around 160px
// (half of 320px) with the default font.
if (length > 25 || (length > 3 &&
(!node->parent()->hasTagName(HTMLNames::aTag) &&
!node->parent()->hasTagName(HTMLNames::liTag))))
hasTextToWrap = true;
}
}
#endif
if (!o->isText())
toRenderInline(o)->invalidateVerticalPosition(); // FIXME: Should do better here and not always invalidate everything.
}
o = bidiNext(this, o, 0, false, &endOfInline);
}
#if ENABLE(WKC_ANDROID_LAYOUT)
// try to make sure that inline text will not span wider than the
// screen size unless the container has a fixed height,
if (doTextWrap && hasTextToWrap) {
// check all the nested containing blocks, unless it is table or
// table-cell, to make sure there is no fixed height as it implies
// fixed layout. If we constrain the text to fit screen, we may
// cause text overlap with the block after.
bool isConstrained = false;
RenderObject* obj = this;
while (obj) {
if (obj->style()->height().isFixed() && (!obj->isTable() && !obj->isTableCell())) {
isConstrained = true;
break;
}
if (obj->isFloating() || obj->isPositioned()) {
// floating and absolute or fixed positioning are done out
// of normal flow. Don't need to worry about height any more.
break;
}
obj = obj->container();
}
if (!isConstrained) {
int screenWidth = view()->frameView()->screenWidth();
int padding = paddingLeft() + paddingRight();
if (screenWidth > 0 && width() > (screenWidth + padding)) {
// limit the content width (width excluding padding) to be
// (screenWidth - 2 * ANDROID_FCTS_MARGIN_PADDING)
int maxWidth = screenWidth - 2 * ANDROID_FCTS_MARGIN_PADDING + padding;
setWidth(min(width(), maxWidth));
m_minPrefWidth = min(m_minPrefWidth, maxWidth);
m_maxPrefWidth = min(m_maxPrefWidth, maxWidth);
// m_overflowWidth = min(m_overflowWidth, maxWidth);
}
}
}
#endif
// We want to skip ahead to the first dirty line
InlineBidiResolver resolver;
unsigned floatIndex;
bool firstLine = true;
bool previousLineBrokeCleanly = true;
RootInlineBox* startLine = determineStartPosition(firstLine, fullLayout, previousLineBrokeCleanly, resolver, floats, floatIndex);
if (fullLayout && !selfNeedsLayout()) {
setNeedsLayout(true, false); // Mark ourselves as needing a full layout. This way we'll repaint like
// we're supposed to.
RenderView* v = view();
if (v && !v->doingFullRepaint() && hasLayer()) {
// Because we waited until we were already inside layout to discover
// that the block really needed a full layout, we missed our chance to repaint the layer
// before layout started. Luckily the layer has cached the repaint rect for its original
// position and size, and so we can use that to make a repaint happen now.
repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
}
}
FloatingObject* lastFloat = m_floatingObjects ? m_floatingObjects->last() : 0;
LineMidpointState& lineMidpointState = resolver.midpointState();
// We also find the first clean line and extract these lines. We will add them back
// if we determine that we're able to synchronize after handling all our dirty lines.
InlineIterator cleanLineStart;
BidiStatus cleanLineBidiStatus;
int endLineYPos = 0;
RootInlineBox* endLine = (fullLayout || !startLine) ?
0 : determineEndPosition(startLine, cleanLineStart, cleanLineBidiStatus, endLineYPos);
if (startLine) {
useRepaintBounds = true;
repaintTop = height();
repaintBottom = height();
RenderArena* arena = renderArena();
RootInlineBox* box = startLine;
while (box) {
repaintTop = min(repaintTop, box->topVisibleOverflow());
repaintBottom = max(repaintBottom, box->bottomVisibleOverflow());
RootInlineBox* next = box->nextRootBox();
box->deleteLine(arena);
box = next;
}
}
InlineIterator end = resolver.position();
if (!fullLayout && lastRootBox() && lastRootBox()->endsWithBreak()) {
// If the last line before the start line ends with a line break that clear floats,
// adjust the height accordingly.
// A line break can be either the first or the last object on a line, depending on its direction.
if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
RenderObject* lastObject = lastLeafChild->renderer();
if (!lastObject->isBR())
lastObject = lastRootBox()->firstLeafChild()->renderer();
if (lastObject->isBR()) {
EClear clear = lastObject->style()->clear();
if (clear != CNONE)
newLine(clear);
}
}
}
bool endLineMatched = false;
bool checkForEndLineMatch = endLine;
bool checkForFloatsFromLastLine = false;
int lastHeight = height();
bool isLineEmpty = true;
while (!end.atEnd()) {
// FIXME: Is this check necessary before the first iteration or can it be moved to the end?
if (checkForEndLineMatch && (endLineMatched = matchedEndLine(resolver, cleanLineStart, cleanLineBidiStatus, endLine, endLineYPos, repaintBottom, repaintTop)))
break;
lineMidpointState.reset();
isLineEmpty = true;
EClear clear = CNONE;
end = findNextLineBreak(resolver, firstLine, isLineEmpty, previousLineBrokeCleanly, &clear);
if (resolver.position().atEnd()) {
resolver.deleteRuns();
checkForFloatsFromLastLine = true;
break;
}
ASSERT(end != resolver.position());
if (!isLineEmpty) {
bidiReorderLine(resolver, end, previousLineBrokeCleanly);
ASSERT(resolver.position() == end);
BidiRun* trailingSpaceRun = 0;
if (!previousLineBrokeCleanly && resolver.runCount() && resolver.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
&& resolver.logicallyLastRun()->m_object->style()->autoWrap()) {
trailingSpaceRun = resolver.logicallyLastRun();
RenderObject* lastObject = trailingSpaceRun->m_object;
if (lastObject->isText()) {
RenderText* lastText = toRenderText(lastObject);
const UChar* characters = lastText->characters();
int firstSpace = trailingSpaceRun->stop();
while (firstSpace > trailingSpaceRun->start()) {
UChar current = characters[firstSpace - 1];
if (!isCollapsibleSpace(current, lastText))
break;
firstSpace--;
}
if (firstSpace == trailingSpaceRun->stop())
trailingSpaceRun = 0;
else {
TextDirection direction = style()->direction();
bool shouldReorder = trailingSpaceRun != (direction == LTR ? resolver.lastRun() : resolver.firstRun());
if (firstSpace != trailingSpaceRun->start()) {
BidiContext* baseContext = resolver.context();
while (BidiContext* parent = baseContext->parent())
baseContext = parent;
BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
trailingSpaceRun->m_stop = firstSpace;
if (direction == LTR)
resolver.addRun(newTrailingRun);
else
resolver.prependRun(newTrailingRun);
trailingSpaceRun = newTrailingRun;
shouldReorder = false;
}
if (shouldReorder) {
if (direction == LTR) {
resolver.moveRunToEnd(trailingSpaceRun);
trailingSpaceRun->m_level = 0;
} else {
resolver.moveRunToBeginning(trailingSpaceRun);
trailingSpaceRun->m_level = 1;
}
}
}
} else
trailingSpaceRun = 0;
}
// Now that the runs have been ordered, we create the line boxes.
// At the same time we figure out where border/padding/margin should be applied for
// inline flow boxes.
RootInlineBox* lineBox = 0;
if (resolver.runCount()) {
lineBox = constructLine(resolver.runCount(), resolver.firstRun(), resolver.lastRun(), firstLine, !end.obj, end.obj && !end.pos ? end.obj : 0);
if (lineBox) {
lineBox->setEndsWithBreak(previousLineBrokeCleanly);
// Now we position all of our text runs horizontally.
computeHorizontalPositionsForLine(lineBox, firstLine, resolver.firstRun(), trailingSpaceRun, end.atEnd());
// Now position our text runs vertically.
computeVerticalPositionsForLine(lineBox, resolver.firstRun());
#if ENABLE(SVG)
// Special SVG text layout code
lineBox->computePerCharacterLayoutInformation();
#endif
#if PLATFORM(MAC)
// Highlight acts as an overflow inflation.
if (style()->highlight() != nullAtom)
lineBox->addHighlightOverflow();
#endif
}
}
resolver.deleteRuns();
if (lineBox) {
lineBox->setLineBreakInfo(end.obj, end.pos, resolver.status());
if (useRepaintBounds) {
repaintTop = min(repaintTop, lineBox->topVisibleOverflow());
repaintBottom = max(repaintBottom, lineBox->bottomVisibleOverflow());
}
}
firstLine = false;
newLine(clear);
}
if (m_floatingObjects && lastRootBox()) {
if (lastFloat) {
for (FloatingObject* f = m_floatingObjects->last(); f != lastFloat; f = m_floatingObjects->prev()) {
}
m_floatingObjects->next();
} else
m_floatingObjects->first();
for (FloatingObject* f = m_floatingObjects->current(); f; f = m_floatingObjects->next()) {
if (f->m_bottom > lastHeight)
lastRootBox()->floats().append(f->m_renderer);
ASSERT(f->m_renderer == floats[floatIndex].object);
// If a float's geometry has changed, give up on syncing with clean lines.
if (floats[floatIndex].rect != IntRect(f->m_left, f->m_top, f->m_width, f->m_bottom - f->m_top))
checkForEndLineMatch = false;
floatIndex++;
}
lastFloat = m_floatingObjects->last();
}
lastHeight = height();
lineMidpointState.reset();
resolver.setPosition(end);
}
if (endLine) {
if (endLineMatched) {
// Attach all the remaining lines, and then adjust their y-positions as needed.
int delta = height() - endLineYPos;
for (RootInlineBox* line = endLine; line; line = line->nextRootBox()) {
line->attachLine();
if (delta) {
repaintTop = min(repaintTop, line->topVisibleOverflow() + min(delta, 0));
repaintBottom = max(repaintBottom, line->bottomVisibleOverflow() + max(delta, 0));
line->adjustPosition(0, delta);
}
if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
Vector<RenderBox*>::iterator end = cleanLineFloats->end();
for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
int floatTop = (*f)->y() - (*f)->marginTop();
insertFloatingObject(*f);
setHeight(floatTop + delta);
positionNewFloats();
}
}
}
setHeight(lastRootBox()->blockHeight());
} else {
// Delete all the remaining lines.
RootInlineBox* line = endLine;
RenderArena* arena = renderArena();
while (line) {
repaintTop = min(repaintTop, line->topVisibleOverflow());
repaintBottom = max(repaintBottom, line->bottomVisibleOverflow());
RootInlineBox* next = line->nextRootBox();
line->deleteLine(arena);
line = next;
}
}
}
if (m_floatingObjects && (checkForFloatsFromLastLine || positionNewFloats()) && lastRootBox()) {
// In case we have a float on the last line, it might not be positioned up to now.
// This has to be done before adding in the bottom border/padding, or the float will
// include the padding incorrectly. -dwh
if (lastFloat) {
for (FloatingObject* f = m_floatingObjects->last(); f != lastFloat; f = m_floatingObjects->prev()) {
}
m_floatingObjects->next();
} else
m_floatingObjects->first();
for (FloatingObject* f = m_floatingObjects->current(); f; f = m_floatingObjects->next()) {
if (f->m_bottom > lastHeight)
lastRootBox()->floats().append(f->m_renderer);
}
lastFloat = m_floatingObjects->last();
}
size_t floatCount = floats.size();
// Floats that did not have layout did not repaint when we laid them out. They would have
// painted by now if they had moved, but if they stayed at (0, 0), they still need to be
// painted.
for (size_t i = 0; i < floatCount; ++i) {
if (!floats[i].everHadLayout) {
RenderBox* f = floats[i].object;
if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
f->repaint();
}
}
}
// Now add in the bottom border/padding.
setHeight(height() + toAdd);
if (!firstLineBox() && hasLineIfEmpty())
setHeight(height() + lineHeight(true, true));
// See if we have any lines that spill out of our block. If we do, then we will possibly need to
// truncate text.
if (hasTextOverflow)
checkLinesForTextOverflow();
}
RootInlineBox* RenderBlock::determineStartPosition(bool& firstLine, bool& fullLayout, bool& previousLineBrokeCleanly,
InlineBidiResolver& resolver, Vector<FloatWithRect>& floats, unsigned& numCleanFloats)
{
RootInlineBox* curr = 0;
RootInlineBox* last = 0;
bool dirtiedByFloat = false;
if (!fullLayout) {
size_t floatIndex = 0;
for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
if (Vector<RenderBox*>* cleanLineFloats = curr->floatsPtr()) {
Vector<RenderBox*>::iterator end = cleanLineFloats->end();
for (Vector<RenderBox*>::iterator o = cleanLineFloats->begin(); o != end; ++o) {
RenderBox* f = *o;
IntSize newSize(f->width() + f->marginLeft() +f->marginRight(), f->height() + f->marginTop() + f->marginBottom());
ASSERT(floatIndex < floats.size());
if (floats[floatIndex].object != f) {
// A new float has been inserted before this line or before its last known float.
// Just do a full layout.
fullLayout = true;
break;
}
if (floats[floatIndex].rect.size() != newSize) {
int floatTop = floats[floatIndex].rect.y();
curr->markDirty();
markLinesDirtyInVerticalRange(curr->blockHeight(), floatTop + max(floats[floatIndex].rect.height(), newSize.height()));
floats[floatIndex].rect.setSize(newSize);
dirtiedByFloat = true;
}
floatIndex++;
}
}
if (dirtiedByFloat || fullLayout)
break;
}
// Check if a new float has been inserted after the last known float.
if (!curr && floatIndex < floats.size())
fullLayout = true;
}
if (fullLayout) {
// Nuke all our lines.
if (firstRootBox()) {
RenderArena* arena = renderArena();
curr = firstRootBox();
while (curr) {
RootInlineBox* next = curr->nextRootBox();
curr->deleteLine(arena);
curr = next;
}
ASSERT(!firstLineBox() && !lastLineBox());
}
} else {
if (curr) {
// We have a dirty line.
if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
// We have a previous line.
if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
// The previous line didn't break cleanly or broke at a newline
// that has been deleted, so treat it as dirty too.
curr = prevRootBox;
}
} else {
// No dirty lines were found.
// If the last line didn't break cleanly, treat it as dirty.
if (lastRootBox() && !lastRootBox()->endsWithBreak())
curr = lastRootBox();
}
// If we have no dirty lines, then last is just the last root box.
last = curr ? curr->prevRootBox() : lastRootBox();
}
numCleanFloats = 0;
if (!floats.isEmpty()) {
int savedHeight = height();
// Restore floats from clean lines.
RootInlineBox* line = firstRootBox();
while (line != curr) {
if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
Vector<RenderBox*>::iterator end = cleanLineFloats->end();
for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
insertFloatingObject(*f);
setHeight((*f)->y() - (*f)->marginTop());
positionNewFloats();
ASSERT(floats[numCleanFloats].object == *f);
numCleanFloats++;
}
}
line = line->nextRootBox();
}
setHeight(savedHeight);
}
firstLine = !last;
previousLineBrokeCleanly = !last || last->endsWithBreak();
RenderObject* startObj;
int pos = 0;
if (last) {
setHeight(last->blockHeight());
startObj = last->lineBreakObj();
pos = last->lineBreakPos();
resolver.setStatus(last->lineBreakBidiStatus());
} else {
bool ltr = style()->direction() == LTR
#if ENABLE(SVG)
|| (style()->unicodeBidi() == UBNormal && isSVGText())
#endif
;
Direction direction = ltr ? LeftToRight : RightToLeft;
resolver.setLastStrongDir(direction);
resolver.setLastDir(direction);
resolver.setEorDir(direction);
resolver.setContext(BidiContext::create(ltr ? 0 : 1, direction, style()->unicodeBidi() == Override));
startObj = bidiFirst(this, &resolver);
}
resolver.setPosition(InlineIterator(this, startObj, pos));
return curr;
}
RootInlineBox* RenderBlock::determineEndPosition(RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus, int& yPos)
{
RootInlineBox* last = 0;
if (!startLine)
last = 0;
else {
for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
if (curr->isDirty())
last = 0;
else if (!last)
last = curr;
}
}
if (!last)
return 0;
RootInlineBox* prev = last->prevRootBox();
cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
cleanLineBidiStatus = prev->lineBreakBidiStatus();
yPos = prev->blockHeight();
for (RootInlineBox* line = last; line; line = line->nextRootBox())
line->extractLine(); // Disconnect all line boxes from their render objects while preserving
// their connections to one another.
return last;
}
#if PLATFORM(WKC)
static int numLines = 8;
#endif
bool RenderBlock::matchedEndLine(const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus, RootInlineBox*& endLine, int& endYPos, int& repaintBottom, int& repaintTop)
{
if (resolver.position() == endLineStart) {
if (resolver.status() != endLineStatus)
return false;
int delta = height() - endYPos;
if (!delta || !m_floatingObjects)
return true;
// See if any floats end in the range along which we want to shift the lines vertically.
int top = min(height(), endYPos);
RootInlineBox* lastLine = endLine;
while (RootInlineBox* nextLine = lastLine->nextRootBox())
lastLine = nextLine;
int bottom = lastLine->blockHeight() + abs(delta);
for (FloatingObject* f = m_floatingObjects->first(); f; f = m_floatingObjects->next()) {
if (f->m_bottom >= top && f->m_bottom < bottom)
return false;
}
return true;
}
// The first clean line doesn't match, but we can check a handful of following lines to try
// to match back up.
#if !PLATFORM(WKC)
static int numLines = 8; // The # of lines we're willing to match against.
#endif
RootInlineBox* line = endLine;
for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
if (line->lineBreakObj() == resolver.position().obj && line->lineBreakPos() == resolver.position().pos) {
// We have a match.
if (line->lineBreakBidiStatus() != resolver.status())
return false; // ...but the bidi state doesn't match.
RootInlineBox* result = line->nextRootBox();
// Set our yPos to be the block height of endLine.
if (result)
endYPos = line->blockHeight();
int delta = height() - endYPos;
if (delta && m_floatingObjects) {
// See if any floats end in the range along which we want to shift the lines vertically.
int top = min(height(), endYPos);
RootInlineBox* lastLine = endLine;
while (RootInlineBox* nextLine = lastLine->nextRootBox())
lastLine = nextLine;
int bottom = lastLine->blockHeight() + abs(delta);
for (FloatingObject* f = m_floatingObjects->first(); f; f = m_floatingObjects->next()) {
if (f->m_bottom >= top && f->m_bottom < bottom)
return false;
}
}
// Now delete the lines that we failed to sync.
RootInlineBox* boxToDelete = endLine;
RenderArena* arena = renderArena();
while (boxToDelete && boxToDelete != result) {
repaintTop = min(repaintTop, boxToDelete->topVisibleOverflow());
repaintBottom = max(repaintBottom, boxToDelete->bottomVisibleOverflow());
RootInlineBox* next = boxToDelete->nextRootBox();
boxToDelete->deleteLine(arena);
boxToDelete = next;
}
endLine = result;
return result;
}
}
return false;
}
static inline bool skipNonBreakingSpace(const InlineIterator& it, bool isLineEmpty, bool previousLineBrokeCleanly)
{
if (it.obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
return false;
// FIXME: This is bad. It makes nbsp inconsistent with space and won't work correctly
// with m_minWidth/m_maxWidth.
// Do not skip a non-breaking space if it is the first character
// on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
// |true|).
if (isLineEmpty && previousLineBrokeCleanly)
return false;
return true;
}
static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, bool isLineEmpty, bool previousLineBrokeCleanly)
{
return style->collapseWhiteSpace() || (style->whiteSpace() == PRE_WRAP && (!isLineEmpty || !previousLineBrokeCleanly));
}
static inline bool shouldPreserveNewline(RenderObject* object)
{
#if ENABLE(SVG)
if (object->isSVGText())
return false;
#endif
return object->style()->preserveNewline();
}
static bool inlineFlowRequiresLineBox(RenderInline* flow)
{
// FIXME: Right now, we only allow line boxes for inlines that are truly empty.
// We need to fix this, though, because at the very least, inlines containing only
// ignorable whitespace should should also have line boxes.
return !flow->firstChild() && flow->hasHorizontalBordersPaddingOrMargin();
}
static inline bool requiresLineBox(const InlineIterator& it, bool isLineEmpty, bool previousLineBrokeCleanly)
{
if (it.obj->isFloatingOrPositioned())
return false;
if (it.obj->isRenderInline() && !inlineFlowRequiresLineBox(toRenderInline(it.obj)))
return false;
if (!shouldCollapseWhiteSpace(it.obj->style(), isLineEmpty, previousLineBrokeCleanly) || it.obj->isBR())
return true;
UChar current = it.current();
return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || shouldPreserveNewline(it.obj))
&& !skipNonBreakingSpace(it, isLineEmpty, previousLineBrokeCleanly);
}
bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj, bool isLineEmpty, bool previousLineBrokeCleanly)
{
ASSERT(inlineObj->parent() == this);
InlineIterator it(this, inlineObj, 0);
while (!it.atEnd() && !requiresLineBox(it, isLineEmpty, previousLineBrokeCleanly))
it.increment();
return !it.atEnd();
}
// FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
// line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
// elements quite right. In other words, we need to build this function's work into the normal line
// object iteration process.
// NB. this function will insert any floating elements that would otherwise
// be skipped but it will not position them.
void RenderBlock::skipTrailingWhitespace(InlineIterator& iterator, bool isLineEmpty, bool previousLineBrokeCleanly)
{
while (!iterator.atEnd() && !requiresLineBox(iterator, isLineEmpty, previousLineBrokeCleanly)) {
RenderObject* object = iterator.obj;
if (object->isFloating()) {
insertFloatingObject(toRenderBox(object));
} else if (object->isPositioned()) {
// FIXME: The math here is actually not really right. It's a best-guess approximation that
// will work for the common cases
RenderObject* c = object->container();
if (c->isRenderInline()) {
// A relative positioned inline encloses us. In this case, we also have to determine our
// position as though we were an inline. Set |staticX| and |staticY| on the relative positioned
// inline so that we can obtain the value later.
toRenderInline(c)->layer()->setStaticX(style()->direction() == LTR ? leftOffset(height(), false) : rightOffset(height(), false));
toRenderInline(c)->layer()->setStaticY(height());
}
RenderBox* box = toRenderBox(object);
if (box->style()->hasStaticX()) {
if (box->style()->isOriginalDisplayInlineType())
box->layer()->setStaticX(style()->direction() == LTR ? leftOffset(height(), false) : width() - rightOffset(height(), false));
else
box->layer()->setStaticX(style()->direction() == LTR ? borderLeft() + paddingLeft() : borderRight() + paddingRight());
}
if (box->style()->hasStaticY())
box->layer()->setStaticY(height());
}
iterator.increment();
}
}
int RenderBlock::skipLeadingWhitespace(InlineBidiResolver& resolver, bool firstLine, bool isLineEmpty, bool previousLineBrokeCleanly)
{
int availableWidth = lineWidth(height(), firstLine);
while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), isLineEmpty, previousLineBrokeCleanly)) {
RenderObject* object = resolver.position().obj;
if (object->isFloating()) {
insertFloatingObject(toRenderBox(object));
positionNewFloats();
availableWidth = lineWidth(height(), firstLine);
} else if (object->isPositioned()) {
// FIXME: The math here is actually not really right. It's a best-guess approximation that
// will work for the common cases
RenderObject* c = object->container();
if (c->isRenderInline()) {
// A relative positioned inline encloses us. In this case, we also have to determine our
// position as though we were an inline. Set |staticX| and |staticY| on the relative positioned
// inline so that we can obtain the value later.
toRenderInline(c)->layer()->setStaticX(style()->direction() == LTR ? leftOffset(height(), firstLine) : rightOffset(height(), firstLine));
toRenderInline(c)->layer()->setStaticY(height());
}
RenderBox* box = toRenderBox(object);
if (box->style()->hasStaticX()) {
if (box->style()->isOriginalDisplayInlineType())
box->layer()->setStaticX(style()->direction() == LTR ? leftOffset(height(), firstLine) : width() - rightOffset(height(), firstLine));
else
box->layer()->setStaticX(style()->direction() == LTR ? borderLeft() + paddingLeft() : borderRight() + paddingRight());
}
if (box->style()->hasStaticY())
box->layer()->setStaticY(height());
}
resolver.increment();
}
resolver.commitExplicitEmbedding();
return availableWidth;
}
// This is currently just used for list markers and inline flows that have line boxes. Neither should
// have an effect on whitespace at the start of the line.
static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
{
RenderObject* next = bidiNext(block, o);
if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
RenderText* nextText = toRenderText(next);
UChar nextChar = nextText->characters()[0];
if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
return true;
}
}
return false;
}
void RenderBlock::fitBelowFloats(int widthToFit, bool firstLine, int& availableWidth)
{
ASSERT(widthToFit > availableWidth);
int floatBottom;
int lastFloatBottom = height();
int newLineWidth = availableWidth;
while (true) {
floatBottom = nextFloatBottomBelow(lastFloatBottom);
if (!floatBottom)
break;
newLineWidth = lineWidth(floatBottom, firstLine);
lastFloatBottom = floatBottom;
if (newLineWidth >= widthToFit)
break;
}
if (newLineWidth > availableWidth) {
setHeight(lastFloatBottom);
availableWidth = newLineWidth;
}
}
static inline unsigned textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, int xPos, bool isFixedPitch, bool collapseWhiteSpace)
{
if (isFixedPitch || (!from && len == text->textLength()))
return text->width(from, len, font, xPos);
return font.width(TextRun(text->characters() + from, len, !collapseWhiteSpace, xPos));
}
InlineIterator RenderBlock::findNextLineBreak(InlineBidiResolver& resolver, bool firstLine, bool& isLineEmpty, bool& previousLineBrokeCleanly,
EClear* clear)
{
ASSERT(resolver.position().block == this);
bool appliedStartWidth = resolver.position().pos > 0;
LineMidpointState& lineMidpointState = resolver.midpointState();
int width = skipLeadingWhitespace(resolver, firstLine, isLineEmpty, previousLineBrokeCleanly);
int w = 0;
int tmpW = 0;
if (resolver.position().atEnd())
return resolver.position();
// This variable is used only if whitespace isn't set to PRE, and it tells us whether
// or not we are currently ignoring whitespace.
bool ignoringSpaces = false;
InlineIterator ignoreStart;
// This variable tracks whether the very last character we saw was a space. We use
// this to detect when we encounter a second space so we know we have to terminate
// a run.
bool currentCharacterIsSpace = false;
bool currentCharacterIsWS = false;
RenderObject* trailingSpaceObject = 0;
InlineIterator lBreak = resolver.position();
RenderObject *o = resolver.position().obj;
RenderObject *last = o;
unsigned pos = resolver.position().pos;
int nextBreakable = resolver.position().nextBreakablePosition;
bool atStart = true;
bool prevLineBrokeCleanly = previousLineBrokeCleanly;
previousLineBrokeCleanly = false;
bool autoWrapWasEverTrueOnLine = false;
bool floatsFitOnLine = true;
// Firefox and Opera will allow a table cell to grow to fit an image inside it under
// very specific circumstances (in order to match common WinIE renderings).
// Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
bool allowImagesToBreak = !style()->htmlHacks() || !isTableCell() || !style()->width().isIntrinsicOrAuto();
EWhiteSpace currWS = style()->whiteSpace();
EWhiteSpace lastWS = currWS;
while (o) {
currWS = o->isReplaced() ? o->parent()->style()->whiteSpace() : o->style()->whiteSpace();
lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
bool autoWrap = RenderStyle::autoWrap(currWS);
autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
#if ENABLE(SVG)
bool preserveNewline = o->isSVGText() ? false : RenderStyle::preserveNewline(currWS);
#else
bool preserveNewline = RenderStyle::preserveNewline(currWS);
#endif
bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
if (o->isBR()) {
if (w + tmpW <= width) {
lBreak.obj = o;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
lBreak.increment();
// A <br> always breaks a line, so don't let the line be collapsed
// away. Also, the space at the end of a line with a <br> does not
// get collapsed away. It only does this if the previous line broke
// cleanly. Otherwise the <br> has no effect on whether the line is
// empty or not.
if (prevLineBrokeCleanly)
isLineEmpty = false;
trailingSpaceObject = 0;
previousLineBrokeCleanly = true;
if (!isLineEmpty && clear)
*clear = o->style()->clear();
}
goto end;
}
if (o->isFloatingOrPositioned()) {
// add to special objects...
if (o->isFloating()) {
RenderBox* floatBox = toRenderBox(o);
insertFloatingObject(floatBox);
// check if it fits in the current line.
// If it does, position it now, otherwise, position
// it after moving to next line (in newLine() func)
if (floatsFitOnLine && floatBox->width() + floatBox->marginLeft() + floatBox->marginRight() + w + tmpW <= width) {
positionNewFloats();
width = lineWidth(height(), firstLine);
} else
floatsFitOnLine = false;
} else if (o->isPositioned()) {
// If our original display wasn't an inline type, then we can
// go ahead and determine our static x position now.
RenderBox* box = toRenderBox(o);
bool isInlineType = box->style()->isOriginalDisplayInlineType();
bool needToSetStaticX = box->style()->hasStaticX();
if (box->style()->hasStaticX() && !isInlineType) {
box->layer()->setStaticX(o->parent()->style()->direction() == LTR ?
borderLeft() + paddingLeft() :
borderRight() + paddingRight());
needToSetStaticX = false;
}
// If our original display was an INLINE type, then we can go ahead
// and determine our static y position now.
bool needToSetStaticY = box->style()->hasStaticY();
if (box->style()->hasStaticY() && isInlineType) {
box->layer()->setStaticY(height());
needToSetStaticY = false;
}
bool needToCreateLineBox = needToSetStaticX || needToSetStaticY;
RenderObject* c = o->container();
if (c->isRenderInline() && (!needToSetStaticX || !needToSetStaticY))
needToCreateLineBox = true;
// If we're ignoring spaces, we have to stop and include this object and
// then start ignoring spaces again.
if (needToCreateLineBox) {
trailingSpaceObject = 0;
ignoreStart.obj = o;
ignoreStart.pos = 0;
if (ignoringSpaces) {
addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
}
}
}
} else if (o->isRenderInline()) {
// Right now, we should only encounter empty inlines here.
ASSERT(!o->firstChild());
RenderInline* flowBox = toRenderInline(o);
// Now that some inline flows have line boxes, if we are already ignoring spaces, we need
// to make sure that we stop to include this object and then start ignoring spaces again.
// If this object is at the start of the line, we need to behave like list markers and
// start ignoring spaces.
if (inlineFlowRequiresLineBox(flowBox)) {
isLineEmpty = false;
if (ignoringSpaces) {
trailingSpaceObject = 0;
addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); // Stop ignoring spaces.
addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); // Start ignoring again.
} else if (style()->collapseWhiteSpace() && resolver.position().obj == o
&& shouldSkipWhitespaceAfterStartObject(this, o, lineMidpointState)) {
// Like with list markers, we start ignoring spaces to make sure that any
// additional spaces we see will be discarded.
currentCharacterIsSpace = true;
currentCharacterIsWS = true;
ignoringSpaces = true;
}
}
tmpW += flowBox->marginLeft() + flowBox->borderLeft() + flowBox->paddingLeft() +
flowBox->marginRight() + flowBox->borderRight() + flowBox->paddingRight();
} else if (o->isReplaced()) {
RenderBox* replacedBox = toRenderBox(o);
// Break on replaced elements if either has normal white-space.
if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!o->isImage() || allowImagesToBreak)) {
w += tmpW;
tmpW = 0;
lBreak.obj = o;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
}
if (ignoringSpaces)
addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
isLineEmpty = false;
ignoringSpaces = false;
currentCharacterIsSpace = false;
currentCharacterIsWS = false;
trailingSpaceObject = 0;
// Optimize for a common case. If we can't find whitespace after the list
// item, then this is all moot. -dwh
if (o->isListMarker()) {
if (style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(this, o, lineMidpointState)) {
// Like with inline flows, we start ignoring spaces to make sure that any
// additional spaces we see will be discarded.
currentCharacterIsSpace = true;
currentCharacterIsWS = true;
ignoringSpaces = true;
}
if (toRenderListMarker(o)->isInside())
tmpW += replacedBox->width() + replacedBox->marginLeft() + replacedBox->marginRight() + inlineWidth(o);
} else
tmpW += replacedBox->width() + replacedBox->marginLeft() + replacedBox->marginRight() + inlineWidth(o);
} else if (o->isText()) {
if (!pos)
appliedStartWidth = false;
RenderText* t = toRenderText(o);
int strlen = t->textLength();
int len = strlen - pos;
const UChar* str = t->characters();
const Font& f = t->style(firstLine)->font();
bool isFixedPitch = f.isFixedPitch();
int lastSpace = pos;
int wordSpacing = o->style()->wordSpacing();
int lastSpaceWordSpacing = 0;
int wrapW = tmpW + inlineWidth(o, !appliedStartWidth, true);
int charWidth = 0;
bool breakNBSP = autoWrap && o->style()->nbspMode() == SPACE;
// Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
// which is only possible if the word is the first thing on the line, that is, if |w| is zero.
bool breakWords = o->style()->breakWords() && ((autoWrap && !w) || currWS == PRE);
bool midWordBreak = false;
bool breakAll = o->style()->wordBreak() == BreakAllWordBreak && autoWrap;
if (t->isWordBreak()) {
w += tmpW;
tmpW = 0;
lBreak.obj = o;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
ASSERT(!len);
}
while (len) {
bool previousCharacterIsSpace = currentCharacterIsSpace;
bool previousCharacterIsWS = currentCharacterIsWS;
UChar c = str[pos];
currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
if (!collapseWhiteSpace || !currentCharacterIsSpace)
isLineEmpty = false;
// Check for soft hyphens. Go ahead and ignore them.
if (c == softHyphen) {
if (!ignoringSpaces) {
// Ignore soft hyphens
InlineIterator beforeSoftHyphen;
if (pos)
beforeSoftHyphen = InlineIterator(0, o, pos - 1);
else
beforeSoftHyphen = InlineIterator(0, last, last->isText() ? toRenderText(last)->textLength() - 1 : 0);
// Two consecutive soft hyphens. Avoid overlapping midpoints.
if (lineMidpointState.numMidpoints && lineMidpointState.midpoints[lineMidpointState.numMidpoints - 1].obj == o &&
lineMidpointState.midpoints[lineMidpointState.numMidpoints - 1].pos == pos)
lineMidpointState.numMidpoints--;
else
addMidpoint(lineMidpointState, beforeSoftHyphen);
// Add the width up to but not including the hyphen.
tmpW += textWidth(t, lastSpace, pos - lastSpace, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
// For wrapping text only, include the hyphen. We need to ensure it will fit
// on the line if it shows when we break.
if (autoWrap)
tmpW += textWidth(t, pos, 1, f, w + tmpW, isFixedPitch, collapseWhiteSpace);
InlineIterator afterSoftHyphen(0, o, pos);
afterSoftHyphen.increment();
addMidpoint(lineMidpointState, afterSoftHyphen);
}
pos++;
len--;
lastSpaceWordSpacing = 0;
lastSpace = pos; // Cheesy hack to prevent adding in widths of the run twice.
continue;
}
bool applyWordSpacing = false;
currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
if ((breakAll || breakWords) && !midWordBreak) {
wrapW += charWidth;
charWidth = textWidth(t, pos, 1, f, w + wrapW, isFixedPitch, collapseWhiteSpace);
midWordBreak = w + wrapW + charWidth > width;
}
bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(str, pos, strlen, nextBreakable, breakNBSP));
if (betweenWords || midWordBreak) {
bool stoppedIgnoringSpaces = false;
if (ignoringSpaces) {
if (!currentCharacterIsSpace) {
// Stop ignoring spaces and begin at this
// new point.
ignoringSpaces = false;
lastSpaceWordSpacing = 0;
lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
addMidpoint(lineMidpointState, InlineIterator(0, o, pos));
stoppedIgnoringSpaces = true;
} else {
// Just keep ignoring these spaces.
pos++;
len--;
continue;
}
}
int additionalTmpW = textWidth(t, lastSpace, pos - lastSpace, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
tmpW += additionalTmpW;
if (!appliedStartWidth) {
tmpW += inlineWidth(o, true, false);
appliedStartWidth = true;
}
applyWordSpacing = wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
if (!w && autoWrap && tmpW > width)
fitBelowFloats(tmpW, firstLine, width);
if (autoWrap || breakWords) {
// If we break only after white-space, consider the current character
// as candidate width for this line.
bool lineWasTooWide = false;
if (w + tmpW <= width && currentCharacterIsWS && o->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) {
int charWidth = textWidth(t, pos, 1, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
// Check if line is too big even without the extra space
// at the end of the line. If it is not, do nothing.
// If the line needs the extra whitespace to be too long,
// then move the line break to the space and skip all
// additional whitespace.
if (w + tmpW + charWidth > width) {
lineWasTooWide = true;
lBreak.obj = o;
lBreak.pos = pos;
lBreak.nextBreakablePosition = nextBreakable;
skipTrailingWhitespace(lBreak, isLineEmpty, previousLineBrokeCleanly);
}
}
if (lineWasTooWide || w + tmpW > width) {
if (lBreak.obj && shouldPreserveNewline(lBreak.obj) && lBreak.obj->isText() && !toRenderText(lBreak.obj)->isWordBreak() && toRenderText(lBreak.obj)->characters()[lBreak.pos] == '\n') {
if (!stoppedIgnoringSpaces && pos > 0) {
// We need to stop right before the newline and then start up again.
addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); // Stop
addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); // Start
}
lBreak.increment();
previousLineBrokeCleanly = true;
}
goto end; // Didn't fit. Jump to the end.
} else {
if (!betweenWords || (midWordBreak && !autoWrap))
tmpW -= additionalTmpW;
if (pos > 0 && str[pos-1] == softHyphen)
// Subtract the width of the soft hyphen out since we fit on a line.
tmpW -= textWidth(t, pos - 1, 1, f, w + tmpW, isFixedPitch, collapseWhiteSpace);
}
}
if (c == '\n' && preserveNewline) {
if (!stoppedIgnoringSpaces && pos > 0) {
// We need to stop right before the newline and then start up again.
addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); // Stop
addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); // Start
}
lBreak.obj = o;
lBreak.pos = pos;
lBreak.nextBreakablePosition = nextBreakable;
lBreak.increment();
previousLineBrokeCleanly = true;
return lBreak;
}
if (autoWrap && betweenWords) {
w += tmpW;
wrapW = 0;
tmpW = 0;
lBreak.obj = o;
lBreak.pos = pos;
lBreak.nextBreakablePosition = nextBreakable;
// Auto-wrapping text should not wrap in the middle of a word once it has had an
// opportunity to break after a word.
breakWords = false;
}
if (midWordBreak) {
// Remember this as a breakable position in case
// adding the end width forces a break.
lBreak.obj = o;
lBreak.pos = pos;
lBreak.nextBreakablePosition = nextBreakable;
midWordBreak &= (breakWords || breakAll);
}
if (betweenWords) {
lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
lastSpace = pos;
}
if (!ignoringSpaces && o->style()->collapseWhiteSpace()) {
// If we encounter a newline, or if we encounter a
// second space, we need to go ahead and break up this
// run and enter a mode where we start collapsing spaces.
if (currentCharacterIsSpace && previousCharacterIsSpace) {
ignoringSpaces = true;
// We just entered a mode where we are ignoring
// spaces. Create a midpoint to terminate the run
// before the second space.
addMidpoint(lineMidpointState, ignoreStart);
}
}
} else if (ignoringSpaces) {
// Stop ignoring spaces and begin at this
// new point.
ignoringSpaces = false;
lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
addMidpoint(lineMidpointState, InlineIterator(0, o, pos));
}
if (currentCharacterIsSpace && !previousCharacterIsSpace) {
ignoreStart.obj = o;
ignoreStart.pos = pos;
}
if (!currentCharacterIsWS && previousCharacterIsWS) {
if (autoWrap && o->style()->breakOnlyAfterWhiteSpace()) {
lBreak.obj = o;
lBreak.pos = pos;
lBreak.nextBreakablePosition = nextBreakable;
}
}
if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
trailingSpaceObject = o;
else if (!o->style()->collapseWhiteSpace() || !currentCharacterIsSpace)
trailingSpaceObject = 0;
pos++;
len--;
atStart = false;
}
// IMPORTANT: pos is > length here!
if (!ignoringSpaces)
tmpW += textWidth(t, lastSpace, pos - lastSpace, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
tmpW += inlineWidth(o, !appliedStartWidth, true);
} else
ASSERT_NOT_REACHED();
RenderObject* next = bidiNext(this, o);
bool checkForBreak = autoWrap;
if (w && w + tmpW > width && lBreak.obj && currWS == NOWRAP)
checkForBreak = true;
else if (next && o->isText() && next->isText() && !next->isBR()) {
if (autoWrap || (next->style()->autoWrap())) {
if (currentCharacterIsSpace)
checkForBreak = true;
else {
checkForBreak = false;
RenderText* nextText = toRenderText(next);
if (nextText->textLength()) {
UChar c = nextText->characters()[0];
if (c == ' ' || c == '\t' || (c == '\n' && !shouldPreserveNewline(next)))
// If the next item on the line is text, and if we did not end with
// a space, then the next text run continues our word (and so it needs to
// keep adding to |tmpW|. Just update and continue.
checkForBreak = true;
} else if (nextText->isWordBreak())
checkForBreak = true;
bool willFitOnLine = w + tmpW <= width;
if (!willFitOnLine && !w) {
fitBelowFloats(tmpW, firstLine, width);
willFitOnLine = tmpW <= width;
}
bool canPlaceOnLine = willFitOnLine || !autoWrapWasEverTrueOnLine;
if (canPlaceOnLine && checkForBreak) {
w += tmpW;
tmpW = 0;
lBreak.obj = next;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
}
}
}
}
if (checkForBreak && (w + tmpW > width)) {
// if we have floats, try to get below them.
if (currentCharacterIsSpace && !ignoringSpaces && o->style()->collapseWhiteSpace())
trailingSpaceObject = 0;
if (w)
goto end;
fitBelowFloats(tmpW, firstLine, width);
// |width| may have been adjusted because we got shoved down past a float (thus
// giving us more room), so we need to retest, and only jump to
// the end label if we still don't fit on the line. -dwh
if (w + tmpW > width)
goto end;
}
if (!o->isFloatingOrPositioned()) {
last = o;
if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
w += tmpW;
tmpW = 0;
lBreak.obj = next;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
}
}
o = next;
nextBreakable = -1;
// Clear out our character space bool, since inline <pre>s don't collapse whitespace
// with adjacent inline normal/nowrap spans.
if (!collapseWhiteSpace)
currentCharacterIsSpace = false;
pos = 0;
atStart = false;
}
if (w + tmpW <= width || lastWS == NOWRAP) {
lBreak.obj = 0;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
}
end:
if (lBreak == resolver.position() && (!lBreak.obj || !lBreak.obj->isBR())) {
// we just add as much as possible
if (style()->whiteSpace() == PRE) {
// FIXME: Don't really understand this case.
if (pos != 0) {
lBreak.obj = o;
lBreak.pos = pos - 1;
} else {
lBreak.obj = last;
lBreak.pos = last->isText() ? last->length() : 0;
lBreak.nextBreakablePosition = -1;
}
} else if (lBreak.obj) {
if (last != o && !last->isListMarker()) {
// better to break between object boundaries than in the middle of a word (except for list markers)
lBreak.obj = o;
lBreak.pos = 0;
lBreak.nextBreakablePosition = -1;
} else {
// Don't ever break in the middle of a word if we can help it.
// There's no room at all. We just have to be on this line,
// even though we'll spill out.
lBreak.obj = o;
lBreak.pos = pos;
lBreak.nextBreakablePosition = -1;
}
}
}
// make sure we consume at least one char/object.
if (lBreak == resolver.position())
lBreak.increment();
// Sanity check our midpoints.
checkMidpoints(lineMidpointState, lBreak);
if (trailingSpaceObject) {
// This object is either going to be part of the last midpoint, or it is going
// to be the actual endpoint. In both cases we just decrease our pos by 1 level to
// exclude the space, allowing it to - in effect - collapse into the newline.
if (lineMidpointState.numMidpoints % 2) {
InlineIterator* midpoints = lineMidpointState.midpoints.data();
midpoints[lineMidpointState.numMidpoints - 1].pos--;
}
//else if (lBreak.pos > 0)
// lBreak.pos--;
else if (lBreak.obj == 0 && trailingSpaceObject->isText()) {
// Add a new end midpoint that stops right at the very end.
RenderText* text = toRenderText(trailingSpaceObject);
unsigned length = text->textLength();
unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
InlineIterator endMid(0, trailingSpaceObject, pos);
addMidpoint(lineMidpointState, endMid);
}
}
// We might have made lBreak an iterator that points past the end
// of the object. Do this adjustment to make it point to the start
// of the next object instead to avoid confusing the rest of the
// code.
if (lBreak.pos > 0) {
lBreak.pos--;
lBreak.increment();
}
if (lBreak.obj && lBreak.pos >= 2 && lBreak.obj->isText()) {
// For soft hyphens on line breaks, we have to chop out the midpoints that made us
// ignore the hyphen so that it will render at the end of the line.
UChar c = toRenderText(lBreak.obj)->characters()[lBreak.pos - 1];
if (c == softHyphen)
chopMidpointsAt(lineMidpointState, lBreak.obj, lBreak.pos - 2);
}
return lBreak;
}
void RenderBlock::addOverflowFromInlineChildren()
{
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
addLayoutOverflow(curr->layoutOverflowRect());
if (!hasOverflowClip())
addVisualOverflow(curr->visualOverflowRect());
}
}
void RenderBlock::deleteEllipsisLineBoxes()
{
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
curr->clearTruncation();
}
#if PLATFORM(WKC)
static AtomicString* ellipsisStr = 0;
#endif
void RenderBlock::checkLinesForTextOverflow()
{
// Determine the width of the ellipsis using the current font.
// FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
TextRun ellipsisRun(&horizontalEllipsis, 1);
#if PLATFORM(WKC)
if (!ellipsisStr) {
ellipsisStr = new AtomicString(&horizontalEllipsis, 1);
}
#else
DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
#endif
const Font& firstLineFont = firstLineStyle()->font();
const Font& font = style()->font();
int firstLineEllipsisWidth = firstLineFont.width(ellipsisRun);
int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(ellipsisRun);
// For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
// if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and
// check the left edge of the line box to see if it is less
// Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
bool ltr = style()->direction() == LTR;
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
int blockRightEdge = rightOffset(curr->y(), curr == firstRootBox());
int blockLeftEdge = leftOffset(curr->y(), curr == firstRootBox());
int lineBoxEdge = ltr ? curr->x() + curr->width() : curr->x();
if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
// This line spills out of our box in the appropriate direction. Now we need to see if the line
// can be truncated. In order for truncation to be possible, the line must have sufficient space to
// accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
// space.
int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
int blockEdge = ltr ? blockRightEdge : blockLeftEdge;
if (curr->canAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
#if PLATFORM(WKC)
curr->placeEllipsis(*ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
#else
curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
#endif
}
}
}
#if PLATFORM(WKC)
void RenderBlock::deleteSharedInstanceLineLayout()
{
delete ellipsisStr;
#ifndef NDEBUG
delete bidiRunCounter;
#endif
}
void RenderBlock::resetVariablesLineLayout()
{
ellipsisStr = 0;
numLines = 8;
#ifndef NDEBUG
bidiRunCounter = 0;
inBidiRunDestroy = false;
#endif
}
#endif
}
| 42.972795
| 213
| 0.556709
|
s1rcheese
|
d7033882a609c4f6412710eb1ce7736d5113a10d
| 2,779
|
hpp
|
C++
|
include/gba/video/palettes.hpp
|
felixjones/gba-hpp
|
66c84e2261c9a2d8e678e8cefb4f43f8c1c13cf3
|
[
"Zlib"
] | 5
|
2022-03-12T19:16:58.000Z
|
2022-03-24T20:35:45.000Z
|
include/gba/video/palettes.hpp
|
felixjones/gba-hpp
|
66c84e2261c9a2d8e678e8cefb4f43f8c1c13cf3
|
[
"Zlib"
] | null | null | null |
include/gba/video/palettes.hpp
|
felixjones/gba-hpp
|
66c84e2261c9a2d8e678e8cefb4f43f8c1c13cf3
|
[
"Zlib"
] | null | null | null |
/*
===============================================================================
Copyright (C) 2022 gba-hpp contributors
For conditions of distribution and use, see copyright notice in LICENSE.md
===============================================================================
*/
#ifndef GBAXX_VIDEO_PALETTES_HPP
#define GBAXX_VIDEO_PALETTES_HPP
#include <cstddef>
#include <gba/inttype.hpp>
#include <gba/video/modes.hpp>
namespace gba {
template <class T>
concept IsColorArray = util::Array<T> && BinaryDigits<util::array_value_type<T>, 16>;
template <class T>
concept IsPaletteEntry = IsColorArray<T> && (util::array_size<T> % 8) == 0;
template <std::uintptr_t Address>
struct palette {
static constexpr auto address = Address;
static void clear(BinaryDigits<16> auto c) noexcept {
#if defined(GBAXX_HAS_AGBABI)
__agbabi_wordset4(reinterpret_cast<uint16*>(address), (8 * 8) * sizeof(uint16), ((c << 16) | c));
#else
constexpr auto end = (8 * 8) / 2;
auto* buffer = reinterpret_cast<volatile uint32*>(address);
const auto cc = uint32((c << 16) | c);
for (int ii = 0; ii < end; ++ii) {
buffer[ii] = cc;
}
#endif
}
static void put(int x, int y, BinaryDigits<16> auto c) noexcept {
using int16_type = decltype(c);
auto* buffer = reinterpret_cast<volatile int16_type*>(address);
buffer[(y * 8) + x] = c;
}
static auto get(int x, int y) noexcept {
auto* buffer = reinterpret_cast<const volatile uint16*>(address);
return buffer[(y * 8) + x];
}
static void put_row(int y, const IsPaletteEntry auto line) noexcept {
#if defined(GBAXX_HAS_AGBABI)
__aeabi_memcpy4(reinterpret_cast<uint16*>(address) + (y * 8), &line[0], util::array_size<decltype(line)> * sizeof(uint16));
#else
auto* src = reinterpret_cast<const uint32*>(&line[0]);
auto* dst= reinterpret_cast<volatile uint32*>(address);
dst += y * 8;
for (int ii = 0; ii < util::array_size<decltype(line)> / 2; ++ii) {
dst[ii] = src[ii];
}
#endif
}
static void put_row(int x, int y, const IsColorArray auto line) noexcept {
#if defined(GBAXX_HAS_AGBABI)
__agbabi_memcpy2(reinterpret_cast<uint16*>(address) + (y * 8) + x, &line[0], sizeof(line));
#else
using int16_type = util::array_value_type<decltype(line)>;
auto* buffer = reinterpret_cast<volatile int16_type*>(address);
buffer += (y * 8) + x;
for (std::size_t ii = 0; ii < util::array_size<decltype(line)>; ++ii) {
buffer[ii] = line[ii];
}
#endif
}
};
using bg_palette = palette<0x5000000>;
using obj_palette = palette<0x5000200>;
} // namespace gba
#endif // define GBAXX_VIDEO_PALETTES_HPP
| 30.877778
| 131
| 0.600576
|
felixjones
|
d705b08b95b049207c09cdbde58f67de3dc48c16
| 857
|
cpp
|
C++
|
test/Statistics/Sample.cpp
|
kurocha/statistics
|
bc9ff66fc77af326fd9b70d1fd0c0e30b55aaa68
|
[
"MIT",
"Unlicense"
] | null | null | null |
test/Statistics/Sample.cpp
|
kurocha/statistics
|
bc9ff66fc77af326fd9b70d1fd0c0e30b55aaa68
|
[
"MIT",
"Unlicense"
] | null | null | null |
test/Statistics/Sample.cpp
|
kurocha/statistics
|
bc9ff66fc77af326fd9b70d1fd0c0e30b55aaa68
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// Distribution.cpp
// This file is part of the "Numerics" project and released under the MIT License.
//
// Created by Samuel Williams on 4/11/2017.
// Copyright, 2017, by Samuel Williams. All rights reserved.
//
#include <UnitTest/UnitTest.hpp>
#include <Statistics/Sample.hpp>
namespace Statistics
{
using namespace UnitTest::Expectations;
UnitTest::Suite SampleTestSuite {
"Statistics::Sample",
{"it can calculate standard deviation",
[](UnitTest::Examiner & examiner) {
Sample<float> distribution;
for (float s = 10; s <= 50; s += 10)
distribution.add(s);
examiner.expect(distribution.variance()).to(be == 250);
examiner.expect(distribution.standard_deviation()).to(be_equivalent(15.8113883008));
examiner.expect(distribution.standard_error()).to(be_equivalent(7.0710678118));
}
},
};
}
| 25.205882
| 88
| 0.693116
|
kurocha
|
d706e141b871e4cdd5374156ed41fc0436b224ec
| 344
|
cpp
|
C++
|
Systems/C++/Jumping/Refrences/memory.cpp
|
dheerajpv/Notes
|
95a697034ae07d70850f0f7b9dd24d3eb599ee20
|
[
"MIT"
] | null | null | null |
Systems/C++/Jumping/Refrences/memory.cpp
|
dheerajpv/Notes
|
95a697034ae07d70850f0f7b9dd24d3eb599ee20
|
[
"MIT"
] | null | null | null |
Systems/C++/Jumping/Refrences/memory.cpp
|
dheerajpv/Notes
|
95a697034ae07d70850f0f7b9dd24d3eb599ee20
|
[
"MIT"
] | null | null | null |
/* & can we used to find a variable memory adress
When & is used in a declaration, it is a reference operator.
When & is not used in a declaration, it is an address operator.
*/
#include <iostream>
int main() {
int power = 9000;
// Print power
std::cout << power << "\n";
// Print &power
std::cout << &power << "\n";
}
| 17.2
| 63
| 0.610465
|
dheerajpv
|
d7086144433011a86e8700f79c8fc8a9ef570213
| 544
|
cpp
|
C++
|
source/xyo/xyo-datastructures-json-varray.cpp
|
g-stefan/xyo
|
e203cb699d6bba46eae6c8157f27ea29ab7506f1
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/xyo/xyo-datastructures-json-varray.cpp
|
g-stefan/xyo
|
e203cb699d6bba46eae6c8157f27ea29ab7506f1
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/xyo/xyo-datastructures-json-varray.cpp
|
g-stefan/xyo
|
e203cb699d6bba46eae6c8157f27ea29ab7506f1
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// XYO
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#include "xyo-datastructures-json-varray.hpp"
namespace XYO {
namespace DataStructures {
namespace JSON {
XYO_DYNAMIC_TYPE_IMPLEMENT(VArray, "{3ECCB902-C928-4DBD-AD23-815EF4BFA6AF}");
VArray::VArray() {
XYO_DYNAMIC_TYPE_PUSH(VArray);
value.pointerLink(this);
value.newMemory();
};
};
};
};
| 18.133333
| 81
| 0.645221
|
g-stefan
|
d7098d33d17b333e9e46f9178df036df48ef4b09
| 850
|
cpp
|
C++
|
src/shapes/star.cpp
|
hermet/rive-cpp
|
d69378d97e7d987930c3764655153bf8ddc65966
|
[
"MIT"
] | null | null | null |
src/shapes/star.cpp
|
hermet/rive-cpp
|
d69378d97e7d987930c3764655153bf8ddc65966
|
[
"MIT"
] | null | null | null |
src/shapes/star.cpp
|
hermet/rive-cpp
|
d69378d97e7d987930c3764655153bf8ddc65966
|
[
"MIT"
] | null | null | null |
#include "shapes/star.hpp"
#include "shapes/straight_vertex.hpp"
#include <cmath>
using namespace rive;
Star::Star() {}
void Star::innerRadiusChanged() { markPathDirty(); }
int Star::expectedSize() { return points() * 2; }
void Star::buildPolygon()
{
auto actualPoints = expectedSize();
auto halfWidth = width() / 2;
auto halfHeight = height() / 2;
auto innerHalfWidth = width() * innerRadius() / 2;
auto innerHalfHeight = height() * innerRadius() / 2;
auto angle = -M_PI / 2;
auto inc = 2 * M_PI / actualPoints;
for (int i = 0; i < actualPoints; i++)
{
auto isInner = i & 1;
if (isInner)
{
buildVertex(m_Vertices[i], innerHalfHeight, innerHalfWidth, angle);
}
else
{
buildVertex(m_Vertices[i], halfHeight, halfWidth, angle);
}
angle += inc;
}
}
void Star::update(ComponentDirt value) { Super::update(value); }
| 21.794872
| 70
| 0.663529
|
hermet
|
d710afadd621bb289fdc523ad1024a154b77c014
| 2,716
|
cpp
|
C++
|
options/group.cpp
|
sheepsskullcity/opentrack
|
2742eebed2dd5db4dbf187504c95eca70aa624f2
|
[
"ISC"
] | 1
|
2021-06-14T09:00:47.000Z
|
2021-06-14T09:00:47.000Z
|
options/group.cpp
|
sheepsskullcity/opentrack
|
2742eebed2dd5db4dbf187504c95eca70aa624f2
|
[
"ISC"
] | null | null | null |
options/group.cpp
|
sheepsskullcity/opentrack
|
2742eebed2dd5db4dbf187504c95eca70aa624f2
|
[
"ISC"
] | null | null | null |
#include "group.hpp"
#include "defs.hpp"
#include <QStandardPaths>
#include <QDir>
#include <QDebug>
namespace options {
group::group(const QString& name) : name(name)
{
if (name == "")
return;
auto conf = ini_file();
conf->beginGroup(name);
for (auto& k_ : conf->childKeys())
{
auto tmp = k_.toUtf8();
QString k(tmp);
kvs[k] = conf->value(k_);
}
conf->endGroup();
}
void group::save() const
{
save_deferred(*ini_file());
}
void group::save_deferred(QSettings& s) const
{
if (name == "")
return;
s.beginGroup(name);
for (auto& i : kvs)
s.setValue(i.first, i.second);
s.endGroup();
}
void group::put(const QString &s, const QVariant &d)
{
kvs[s] = d;
}
bool group::contains(const QString &s) const
{
return kvs.count(s) != 0;
}
QString group::ini_directory()
{
const auto dirs = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
if (dirs.size() == 0)
return "";
if (QDir(dirs[0]).mkpath(OPENTRACK_ORG))
return dirs[0] + "/" OPENTRACK_ORG;
return "";
}
QString group::ini_filename()
{
QSettings settings(OPENTRACK_ORG);
return settings.value(OPENTRACK_CONFIG_FILENAME_KEY, OPENTRACK_DEFAULT_CONFIG).toString();
}
QString group::ini_pathname()
{
const auto dir = ini_directory();
if (dir == "")
return "";
return dir + "/" + ini_filename();
}
const QStringList group::ini_list()
{
const auto dirname = ini_directory();
if (dirname == "")
return QStringList();
QDir settings_dir(dirname);
QStringList list = settings_dir.entryList( QStringList { "*.ini" } , QDir::Files, QDir::Name );
std::sort(list.begin(), list.end());
return list;
}
const std::shared_ptr<QSettings> group::ini_file()
{
const auto pathname = ini_pathname();
if (pathname != "")
return std::make_shared<QSettings>(ini_pathname(), QSettings::IniFormat);
return std::make_shared<QSettings>();
}
bool group::operator==(const group& other) const
{
for (const auto& kv : kvs)
{
const QVariant val = other.get<QVariant>(kv.first);
if (!other.contains(kv.first) || kv.second != val)
{
qDebug() << "bundle" << name << "modified" << "key" << kv.first << "-" << val << "<>" << kv.second;
return false;
}
}
for (const auto& kv : other.kvs)
{
const QVariant val = get<QVariant>(kv.first);
if (!contains(kv.first) || kv.second != val)
{
qDebug() << "bundle" << name << "modified" << "key" << kv.first << "-" << kv.second << "<>" << val;
return false;
}
}
return true;
}
}
| 22.823529
| 111
| 0.582842
|
sheepsskullcity
|
d7135af8f57086948d86dbe63885cb0adecf2400
| 458
|
cpp
|
C++
|
codebook/graph/match.cpp
|
nella17/NYCU_gAwr_gurA
|
e168cafc9e728a2cab2d1cafa90a1cfd433b9f59
|
[
"CC0-1.0"
] | 1
|
2022-01-23T11:18:52.000Z
|
2022-01-23T11:18:52.000Z
|
codebook/graph/match.cpp
|
nella17/NYCU_gAwr_gurA
|
e168cafc9e728a2cab2d1cafa90a1cfd433b9f59
|
[
"CC0-1.0"
] | null | null | null |
codebook/graph/match.cpp
|
nella17/NYCU_gAwr_gurA
|
e168cafc9e728a2cab2d1cafa90a1cfd433b9f59
|
[
"CC0-1.0"
] | 1
|
2022-02-02T15:24:39.000Z
|
2022-02-02T15:24:39.000Z
|
array<int,SZ> mp;
array<bool,SZ> vis;
bool dfs(int now) {
if(vis[now]) return false;
vis[now] = true;
for(int i = 0 ; i < n ; ++i) {
if(!g[now][i]) continue;
if(mp[i] == -1 or dfs(mp[i]))
return mp[i] = now , 1;
}
return false;
}
int solve() {
mp.fill(-1);
int ret = 0 ;
for(int i = 0 ; i < n ; ++i) {
vis.fill(false);
if(dfs(i)) ++ret;
}
return ret;
}
| 20.818182
| 38
| 0.425764
|
nella17
|
d714da4c8b42ab9d28ea7cb3eaa59ffe581bf37c
| 3,043
|
hh
|
C++
|
include/Wektor.hh
|
KPO-2020-2021/zad5_3-258980
|
522ed2fa86b50f782826c2597f4d408e4a552d86
|
[
"Unlicense"
] | null | null | null |
include/Wektor.hh
|
KPO-2020-2021/zad5_3-258980
|
522ed2fa86b50f782826c2597f4d408e4a552d86
|
[
"Unlicense"
] | null | null | null |
include/Wektor.hh
|
KPO-2020-2021/zad5_3-258980
|
522ed2fa86b50f782826c2597f4d408e4a552d86
|
[
"Unlicense"
] | null | null | null |
#ifndef WEKTOR_HH
#define WEKTOR_HH
#include <iostream>
#include <cmath>
using namespace std;
template <int Wymiar>
class Wektor
{
static int wszystkie;
static int aktualne;
double _wsp[Wymiar];
public:
Wektor();
Wektor(Wektor<Wymiar> &wek)
{
for (int i = 0; i < Wymiar; i++)
_wsp[i] = wek._wsp[i];
aktualne++;
}
constexpr Wektor(const Wektor &other)
{
for (int i = 0; i < Wymiar; i++)
_wsp[i] = other._wsp[i];
aktualne++;
}
Wektor &operator=(const Wektor &other)
{
for (int i = 0; i < Wymiar; i++)
_wsp[i] = other._wsp[i];
return *this;
}
Wektor &operator=(const float &other)
{
for (int i = 0; i < Wymiar; i++)
_wsp[i] = other;
return *this;
}
~Wektor();
Wektor(double _wsp[Wymiar]);
double operator[](int index) const;
double &operator[](int index);
Wektor<Wymiar> operator+(Wektor<Wymiar> &arg);
Wektor<Wymiar> operator-(Wektor<Wymiar> &arg);
void informacje();
};
template <int Wymiar>
int Wektor<Wymiar>::wszystkie = 0;
template <int Wymiar>
int Wektor<Wymiar>::aktualne = 0;
template <int Wymiar>
void Wektor<Wymiar>::informacje()
{
cout << "akturalne obiekty: " << aktualne << endl;
cout << "wszystkie obiekty: " << wszystkie << endl;
}
template <int Wymiar>
Wektor<Wymiar>::Wektor()
{
for (int i = 0; i < Wymiar; i++)
_wsp[i] = 0;
aktualne++;
wszystkie++;
}
template <int Wymiar>
Wektor<Wymiar>::Wektor(double _wsp[Wymiar])
{
for (int i = 0; i < Wymiar; i++)
this->_wsp[i] = _wsp[i];
aktualne++;
wszystkie++;
}
template <int Wymiar>
Wektor<Wymiar>::~Wektor()
{
aktualne--;
}
template <int Wymiar>
double Wektor<Wymiar>::operator[](int index) const
{
if (index > Wymiar || index < 0)
{
std::cerr << "Indeks poza skala" << std::endl;
exit(1);
}
return _wsp[index];
}
template <int Wymiar>
double &Wektor<Wymiar>::operator[](int index)
{
if (index > Wymiar || index < 0)
{
std::cerr << "Indeks poza skala" << std::endl;
exit(1);
}
return _wsp[index];
}
template <int Wymiar>
Wektor<Wymiar> Wektor<Wymiar>::operator+(Wektor<Wymiar> &arg)
{
Wektor<Wymiar> Wynik;
for (int i = 0; i < Wymiar; i++)
{
Wynik[i] = _wsp[i] + arg[i];
}
return Wynik;
}
template <int Wymiar>
Wektor<Wymiar> Wektor<Wymiar>::operator-(Wektor<Wymiar> &arg)
{
Wektor<Wymiar> Wynik;
for (int i = 0; i < Wymiar; i++)
{
Wynik[i] = _wsp[i] - arg[i];
}
return Wynik;
}
template <int Wymiar>
std::istream &operator>>(std::istream &Strm, Wektor<Wymiar> &Wek)
{
for (int i = 0; i < Wymiar; i++)
{
Strm >> Wek[i];
}
return Strm;
return Strm;
}
template <int Wymiar>
inline std::ostream &operator<<(std::ostream &Strm, const Wektor<Wymiar> &Wek)
{
for (int i = 0; i < Wymiar; i++)
{
Strm << Wek[i] << " ";
}
return Strm;
}
#endif
| 19.632258
| 78
| 0.56096
|
KPO-2020-2021
|
d716504018243631a6ce13abf3d43dffb6ab8b6a
| 1,572
|
cpp
|
C++
|
CppPool/cpp_d07a/ex00/Skat.cpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 40
|
2018-01-28T14:23:27.000Z
|
2022-03-05T15:57:47.000Z
|
CppPool/cpp_d07a/ex00/Skat.cpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 1
|
2021-10-05T09:03:51.000Z
|
2021-10-05T09:03:51.000Z
|
CppPool/cpp_d07a/ex00/Skat.cpp
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 73
|
2019-01-07T18:47:00.000Z
|
2022-03-31T08:48:38.000Z
|
//
// Skat.cpp for skat in /home/gwendoline/Epitech/Tek2/rendu/Piscine_cpp/piscine_cpp_d07a/ex00
//
// Made by Gwendoline Rodriguez
// Login <gwendoline@epitech.net>
//
// Started on Tue Jan 12 22:51:08 2016 Gwendoline Rodriguez
// Last update Tue Jan 12 22:57:53 2016 Gwendoline Rodriguez
//
#include <iostream>
#include <string>
#include "Skat.h"
Skat::Skat() : _name("bob"), _nbrStimPacks(15) {}
Skat::Skat(std::string const& name, int stimPaks) {
_name = name;
_nbrStimPacks = stimPaks;
}
Skat::~Skat() {}
int& Skat::stimPaks() {
return (_nbrStimPacks);
}
const std::string &Skat::name() {
return (_name);
}
void Skat::shareStimPaks(int number, int& stock) {
if (_nbrStimPacks < number)
std::cout << "Don't be greedy" << std::endl;
else {
stock += number;
_nbrStimPacks -= number;
std::cout << "Keep the change." << std::endl;
}
}
void Skat::addStimPaks(unsigned int number) {
if (number == 0)
std::cout << "Hey boya, did you forget something ?" << std::endl;
else _nbrStimPacks += number;
}
void Skat::useStimPaks() {
if (_nbrStimPacks > 0)
{
std::cout << "Time to kick some ass and chew bubble gum." << std::endl;
--_nbrStimPacks;
}
else std::cout << "Mediiiiiic" << std::endl;
}
void Skat::status() {
std::cout << "Soldier " << _name << " reporting " << _nbrStimPacks << " stimpaks remaining sir !" << std::endl;
}
// int main()
// {
// Skat s("Junior", 5);
// std::cout << "Soldier " << s.name() << std::endl;
// s.status();
// s.useStimPaks();
// return 0;
// }
| 21.534247
| 113
| 0.613868
|
667MARTIN
|
d719bcf6300b8b22769044918e506f0773d3a849
| 681
|
cpp
|
C++
|
val_mountain.cpp
|
shirishbahirat/algorithm
|
ec743d4c16ab4f429f22bd6f71540341b3905b3b
|
[
"Apache-2.0"
] | null | null | null |
val_mountain.cpp
|
shirishbahirat/algorithm
|
ec743d4c16ab4f429f22bd6f71540341b3905b3b
|
[
"Apache-2.0"
] | null | null | null |
val_mountain.cpp
|
shirishbahirat/algorithm
|
ec743d4c16ab4f429f22bd6f71540341b3905b3b
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
bool validMountainArray(vector<int> &arr)
{
if (arr.size() < 3)
{
return false;
}
int i = 1;
while ((i < arr.size()) && (arr[i] > arr[i - 1]))
{
i++;
}
if ((i == 1) || (i == arr.size()))
return false;
while ((i < arr.size()) && (arr[i] < arr[i - 1]))
{
i++;
}
if (i == arr.size())
{
return true;
}
return false;
}
};
int main(int argc, char const *argv[])
{
Solution *obj = new Solution();
vector<int> arr = {0, 3, 2, 1};
cout << obj->validMountainArray(arr) << endl;
return 0;
}
| 13.352941
| 53
| 0.481645
|
shirishbahirat
|
d71bee6bfe2958e96d832768d46e405457209ac2
| 1,143
|
hpp
|
C++
|
platforms/linux/src/Application/Packets/Base/HostToControllerPacket.hpp
|
iotile/baBLE-linux
|
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
|
[
"MIT"
] | 13
|
2018-07-04T16:35:37.000Z
|
2021-03-03T10:41:07.000Z
|
platforms/linux/src/Application/Packets/Base/HostToControllerPacket.hpp
|
iotile/baBLE
|
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
|
[
"MIT"
] | 11
|
2018-06-01T20:32:32.000Z
|
2019-01-21T17:03:47.000Z
|
platforms/linux/src/Application/Packets/Base/HostToControllerPacket.hpp
|
iotile/baBLE-linux
|
faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db
|
[
"MIT"
] | null | null | null |
#ifndef BABLE_HOSTTOCONTROLLERPACKET_HPP
#define BABLE_HOSTTOCONTROLLERPACKET_HPP
#include "Application/PacketRouter/PacketRouter.hpp"
#include "Log/Log.hpp"
namespace Packet {
class HostToControllerPacket : public AbstractPacket {
public:
static Packet::Type initial_type() {
return Packet::Type::FLATBUFFERS;
};
PacketUuid get_response_uuid() const;
protected:
HostToControllerPacket(Packet::Id id, Packet::Type type, uint16_t packet_code, bool waiting_response = true);
void set_waiting_response(bool waiting_response);
void prepare(const std::shared_ptr<PacketRouter>& router) override;
std::vector<uint8_t> serialize(MGMTFormatBuilder& builder) const override;
std::vector<uint8_t> serialize(HCIFormatBuilder& builder) const override;
virtual std::shared_ptr<AbstractPacket> on_response_received(const std::shared_ptr<PacketRouter>& router,
const std::shared_ptr<AbstractPacket>& packet);
uint16_t m_response_packet_code;
bool m_waiting_response;
};
}
#endif //BABLE_HOSTTOCONTROLLERPACKET_HPP
| 30.078947
| 120
| 0.725284
|
iotile
|
d71ca307fe0f1fa24832f96a53c25de204595294
| 1,899
|
cpp
|
C++
|
pianoKeySet.cpp
|
planarian/relative_keys
|
43d2e46faaa3add82ff7e7a3b6441f1772249f82
|
[
"MIT"
] | 1
|
2021-11-01T12:11:53.000Z
|
2021-11-01T12:11:53.000Z
|
pianoKeySet.cpp
|
planarian/relative_keys
|
43d2e46faaa3add82ff7e7a3b6441f1772249f82
|
[
"MIT"
] | null | null | null |
pianoKeySet.cpp
|
planarian/relative_keys
|
43d2e46faaa3add82ff7e7a3b6441f1772249f82
|
[
"MIT"
] | null | null | null |
#include "pianoKeySet.h"
#include <QHBoxLayout>
#include "whiteKey.h"
#include "fullBlackKey.h"
PianoKeySet::PianoKeySet(const PianoSynth * a, const Instrument * i, const Switcher * swi, QWidget *parent) :
KeySet(a, i, swi, parent)
{
// determine which white keys have black keys
blackLocations << 0 << 2 << 3 << 5 << 6 << 7 << 9 << 10 << 12 << 13 << 14
<< 16 << 17 << 19 << 20 << 21 << 23 << 24 << 26 << 27 << 28
<< 30 << 31 << 33 << 34 << 35 << 37 << 38 << 40 << 41 << 42
<< 44 << 45 << 47 << 48 << 49;
createWhiteKeys();
createBlackKeys();
mapKeys();
initializeVar();
assignNumbers();
}
void PianoKeySet::arrangeBlackKeys()
{
int keyWidth = whiteKeys[0]->width() * 4 / 5 - 1;
int keyHeight = whiteKeys[0]->height() / 1.6;
int offset = whiteKeys[0]->width() - (keyWidth / 2);
int xLocation, yLocation = whiteKeys[0]->pos().y() - 1;
for (int x = 0; x < blackKeys_upper.length(); ++x)
{
xLocation = blackLocations[x];
blackKeys_upper[x]->resize(keyWidth, keyHeight);
blackKeys_upper[x]->move(whiteKeys[xLocation]->pos().x() + offset, yLocation);
}
}
void PianoKeySet::createWhiteKeys()
{
for (int x = 0; x < 52; ++x)
{
whiteKeys << new WhiteKey(audio, instr, toggles, gray_, white_, this);
layout->addWidget(whiteKeys[x]);
connect(whiteKeys[x], SIGNAL(switcherSignal(Key*)), toggles, SLOT(mostRecentPressSlot(Key*)), Qt::QueuedConnection);
}
}
void PianoKeySet::createBlackKeys()
{
for (int x = 0; x < 36; ++x)
{
blackKeys_upper << new FullBlackKey(audio, instr, toggles, gray_, black_, this);
connect(blackKeys_upper[x], SIGNAL(switcherSignal(Key *)), toggles, SLOT(mostRecentPressSlot(Key*)), Qt::QueuedConnection);
}
}
| 31.131148
| 132
| 0.564508
|
planarian
|
c013007036cc008c20aa256bb2dfafb94b5f1ed1
| 3,922
|
cpp
|
C++
|
amd_depthoffieldfx/src/AMD_DepthOfFieldFX.cpp
|
GPUOpen-Effects/DepthOfFieldFX
|
d6e07f36b4804975953958031536ab7876223d5b
|
[
"MIT"
] | 74
|
2017-03-28T15:07:11.000Z
|
2021-12-27T18:16:59.000Z
|
amd_depthoffieldfx/src/AMD_DepthOfFieldFX.cpp
|
amdvlk/amd_depthoffieldfx
|
d6e07f36b4804975953958031536ab7876223d5b
|
[
"MIT"
] | 1
|
2019-04-15T09:10:05.000Z
|
2019-04-22T07:41:14.000Z
|
amd_depthoffieldfx/src/AMD_DepthOfFieldFX.cpp
|
amdvlk/amd_depthoffieldfx
|
d6e07f36b4804975953958031536ab7876223d5b
|
[
"MIT"
] | 8
|
2017-05-31T11:06:12.000Z
|
2020-10-28T22:14:22.000Z
|
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// if the library is being compiled with "DYNAMIC_LIB" option
// it should do dclspec(dllexport)
#if AMD_DEPTHOFFIELDFX_COMPILE_DYNAMIC_LIB
#define AMD_DLL_EXPORT
#endif
#include <d3d11.h>
#include "AMD_DepthOfFieldFX.h"
#include "AMD_DepthOfFieldFX_Opaque.h"
#pragma warning(disable : 4100) // disable unreference formal parameter warnings for /W4 builds
namespace AMD {
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_DESC::DEPTHOFFIELDFX_DESC() : m_pDevice(nullptr), m_pDeviceContext(nullptr), m_pCircleOfConfusionSRV(nullptr)
{
static DEPTHOFFIELDFX_OPAQUE_DESC opaque(*this);
m_pOpaque = &opaque;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_GetVersion(uint* major, uint* minor, uint* patch)
{
*major = AMD_DEPTHOFFIELDFX_VERSION_MAJOR;
*minor = AMD_DEPTHOFFIELDFX_VERSION_MINOR;
*patch = AMD_DEPTHOFFIELDFX_VERSION_PATCH;
return DEPTHOFFIELDFX_RETURN_CODE_SUCCESS;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_Initialize(const DEPTHOFFIELDFX_DESC& desc)
{
if (nullptr == desc.m_pDevice)
{
return DEPTHOFFIELDFX_RETURN_CODE_INVALID_DEVICE;
}
if (nullptr == desc.m_pDeviceContext)
{
return DEPTHOFFIELDFX_RETURN_CODE_INVALID_DEVICE_CONTEXT;
}
desc.m_pOpaque->initalize(desc);
return DEPTHOFFIELDFX_RETURN_CODE_SUCCESS;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_Resize(const DEPTHOFFIELDFX_DESC& desc)
{
DEPTHOFFIELDFX_RETURN_CODE result = DEPTHOFFIELDFX_RETURN_CODE_SUCCESS;
if ((desc.m_screenSize.x > 16384)
|| (desc.m_screenSize.y > 16384)
|| (desc.m_maxBlurRadius > 64))
{
result = DEPTHOFFIELDFX_RETURN_CODE_INVALID_PARAMS;
}
else
{
result = desc.m_pOpaque->resize(desc);
}
return result;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_Render(const DEPTHOFFIELDFX_DESC& desc)
{
DEPTHOFFIELDFX_RETURN_CODE result = desc.m_pOpaque->render(desc);
return result;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_RenderQuarterRes(const DEPTHOFFIELDFX_DESC& desc)
{
DEPTHOFFIELDFX_RETURN_CODE result = desc.m_pOpaque->render_quarter_res(desc);
return result;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_RenderBox(const DEPTHOFFIELDFX_DESC& desc)
{
DEPTHOFFIELDFX_RETURN_CODE result = desc.m_pOpaque->render_box(desc);
return result;
}
AMD_DEPTHOFFIELDFX_DLL_API DEPTHOFFIELDFX_RETURN_CODE DepthOfFieldFX_Release(const DEPTHOFFIELDFX_DESC& desc)
{
DEPTHOFFIELDFX_RETURN_CODE result = desc.m_pOpaque->release();
return result;
}
}
| 36.654206
| 152
| 0.758032
|
GPUOpen-Effects
|
c0133c11a4e3a225fe8ca9208593c164f02e78f7
| 11,044
|
cpp
|
C++
|
qt-solutions/qtscriptclassic/src/qscriptecmaregexp.cpp
|
privet56/qDesktopSearch
|
702aac770a11895e19180bd4ed2279c7a8ab64be
|
[
"Apache-2.0"
] | 10
|
2016-04-15T15:31:08.000Z
|
2019-10-02T01:19:48.000Z
|
qt-solutions/qtscriptclassic/src/qscriptecmaregexp.cpp
|
privet56/qDesktopSearch
|
702aac770a11895e19180bd4ed2279c7a8ab64be
|
[
"Apache-2.0"
] | null | null | null |
qt-solutions/qtscriptclassic/src/qscriptecmaregexp.cpp
|
privet56/qDesktopSearch
|
702aac770a11895e19180bd4ed2279c7a8ab64be
|
[
"Apache-2.0"
] | 5
|
2016-04-15T15:31:10.000Z
|
2022-02-22T02:00:06.000Z
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Solutions component.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qscriptecmaregexp_p.h"
#include "qscriptengine_p.h"
#include "qscriptvalueimpl_p.h"
#include "qscriptcontext_p.h"
#include "qscriptmember_p.h"
#include "qscriptobject_p.h"
#include <QStringList>
#include <QRegExp>
#include <QtDebug>
QT_BEGIN_NAMESPACE
namespace QScript { namespace Ecma {
RegExp::RegExp(QScriptEnginePrivate *eng):
Core(eng, QLatin1String("RegExp"), QScriptClassInfo::RegExpType)
{
newRegExp(&publicPrototype, QString(), /*flags=*/0);
eng->newConstructor(&ctor, this, publicPrototype);
addPrototypeFunction(QLatin1String("exec"), method_exec, 1);
addPrototypeFunction(QLatin1String("test"), method_test, 1);
addPrototypeFunction(QLatin1String("toString"), method_toString, 1);
}
RegExp::~RegExp()
{
}
RegExp::Instance *RegExp::Instance::get(const QScriptValueImpl &object, QScriptClassInfo *klass)
{
if (! klass || klass == object.classInfo())
return static_cast<Instance*> (object.objectData());
return 0;
}
void RegExp::execute(QScriptContextPrivate *context)
{
#ifndef Q_SCRIPT_NO_EVENT_NOTIFY
engine()->notifyFunctionEntry(context);
#endif
QString P;
int F;
QScriptValueImpl pattern = context->argument(0);
QScriptValueImpl flags = context->argument(1);
if (!context->isCalledAsConstructor()) {
if ((pattern.classInfo() == classInfo()) && flags.isUndefined()) {
context->m_result = pattern;
goto Lout;
}
}
if (pattern.classInfo() == classInfo()) {
if (!flags.isUndefined()) {
context->throwTypeError(QString::fromLatin1("cannot specify flags when creating a copy of a RegExp"));
goto Lout;
}
Instance *data = Instance::get(pattern, classInfo());
#ifndef QT_NO_REGEXP
P = data->value.pattern();
#else
P = data->pattern;
#endif
F = data->flags;
} else {
if (!pattern.isUndefined())
P = pattern.toString();
F = 0;
if (!flags.isUndefined()) {
QString flagsStr = flags.toString();
for (int i = 0; i < flagsStr.length(); ++i) {
int bitflag = flagFromChar(flagsStr.at(i));
if (bitflag == 0) {
context->throwError(
QScriptContext::SyntaxError,
QString::fromUtf8("invalid regular expression flag '%0'")
.arg(flagsStr.at(i)));
goto Lout;
}
F |= bitflag;
}
}
}
if (context->isCalledAsConstructor()) {
QScriptValueImpl &object = context->m_thisObject;
object.setClassInfo(classInfo());
object.setPrototype(publicPrototype);
#ifndef QT_NO_REGEXP
initRegExp(&object, toRegExp(P, F), F);
#else
initRegExp(&object, P, F);
#endif
} else {
newRegExp(&context->m_result, P, F);
}
Lout: ;
#ifndef Q_SCRIPT_NO_EVENT_NOTIFY
engine()->notifyFunctionExit(context);
#endif
}
void RegExp::newRegExp(QScriptValueImpl *result, const QString &pattern, int flags)
{
#ifndef QT_NO_REGEXP
QRegExp rx = toRegExp(pattern, flags);
newRegExp_helper(result, rx, flags);
#else
engine()->newObject(result, publicPrototype, classInfo());
initRegExp(result, pattern, flags);
#endif // QT_NO_REGEXP
}
#ifndef QT_NO_REGEXP
void RegExp::newRegExp(QScriptValueImpl *result, const QRegExp &rx, int flags)
{
Q_ASSERT(!(flags & IgnoreCase) || (rx.caseSensitivity() == Qt::CaseInsensitive));
newRegExp_helper(result, rx, flags);
}
void RegExp::newRegExp_helper(QScriptValueImpl *result, const QRegExp &rx,
int flags)
{
engine()->newObject(result, publicPrototype, classInfo());
initRegExp(result, rx, flags);
}
QRegExp RegExp::toRegExp(const QScriptValueImpl &value) const
{
Instance *rx_data = Instance::get(value, classInfo());
Q_ASSERT(rx_data != 0);
return rx_data->value;
}
QRegExp RegExp::toRegExp(const QString &pattern, int flags)
{
bool ignoreCase = (flags & IgnoreCase) != 0;
return QRegExp(pattern,
(ignoreCase ? Qt::CaseInsensitive: Qt::CaseSensitive),
QRegExp::RegExp2);
}
#endif // QT_NO_REGEXP
void RegExp::initRegExp(QScriptValueImpl *result,
#ifndef QT_NO_REGEXP
const QRegExp &rx,
#else
const QString &pattern,
#endif
int flags)
{
Instance *instance = new Instance();
#ifndef QT_NO_REGEXP
instance->value = rx;
#else
instance->pattern = pattern;
#endif
instance->flags = flags;
result->setObjectData(instance);
bool global = (flags & Global) != 0;
bool ignoreCase = (flags & IgnoreCase) != 0;
bool multiline = (flags & Multiline) != 0;
QScriptValue::PropertyFlags propertyFlags = QScriptValue::SkipInEnumeration
| QScriptValue::Undeletable
| QScriptValue::ReadOnly;
result->setProperty(QLatin1String("global"), QScriptValueImpl(global),
propertyFlags);
result->setProperty(QLatin1String("ignoreCase"), QScriptValueImpl(ignoreCase),
propertyFlags);
result->setProperty(QLatin1String("multiline"), QScriptValueImpl(multiline),
propertyFlags);
#ifndef QT_NO_REGEXP
const QString &pattern = rx.pattern();
#endif
result->setProperty(QLatin1String("source"), QScriptValueImpl(engine(), pattern),
propertyFlags);
result->setProperty(QLatin1String("lastIndex"), QScriptValueImpl(0),
propertyFlags & ~QScriptValue::ReadOnly);
}
int RegExp::flagFromChar(const QChar &ch)
{
static QHash<QChar, int> flagsHash;
if (flagsHash.isEmpty()) {
flagsHash[QLatin1Char('g')] = Global;
flagsHash[QLatin1Char('i')] = IgnoreCase;
flagsHash[QLatin1Char('m')] = Multiline;
}
QHash<QChar, int>::const_iterator it;
it = flagsHash.constFind(ch);
if (it == flagsHash.constEnd())
return 0;
return it.value();
}
QString RegExp::flagsToString(int flags)
{
QString result;
if (flags & Global)
result += QLatin1Char('g');
if (flags & IgnoreCase)
result += QLatin1Char('i');
if (flags & Multiline)
result += QLatin1Char('m');
return result;
}
QScriptValueImpl RegExp::method_exec(QScriptContextPrivate *context, QScriptEnginePrivate *eng, QScriptClassInfo *classInfo)
{
QScriptValueImpl self = context->thisObject();
if (self.classInfo() != classInfo) {
return throwThisObjectTypeError(
context, QLatin1String("RegExp.prototype.exec"));
}
Instance *rx_data = Instance::get(self, classInfo);
Q_ASSERT(rx_data != 0);
QString S = context->argument(0).toString();
int length = S.length();
QScriptValueImpl lastIndex = self.property(QLatin1String("lastIndex"));
int i = lastIndex.isValid() ? int (lastIndex.toInteger()) : 0;
bool global = self.property(QLatin1String("global")).toBoolean();
if (! global)
i = 0;
if (i < 0 || i >= length)
return (eng->nullValue());
#ifndef QT_NO_REGEXP
int index = rx_data->value.indexIn(S, i);
if (index == -1)
#endif // QT_NO_REGEXP
return eng->nullValue();
#ifndef QT_NO_REGEXP
int e = index + rx_data->value.matchedLength();
if (global)
self.setProperty(QLatin1String("lastIndex"), QScriptValueImpl(e));
QScript::Array elts(eng);
QStringList capturedTexts = rx_data->value.capturedTexts();
for (int i = 0; i < capturedTexts.count(); ++i)
elts.assign(i, QScriptValueImpl(eng, capturedTexts.at(i)));
QScriptValueImpl r = eng->newArray(elts);
r.setProperty(QLatin1String("index"), QScriptValueImpl(index));
r.setProperty(QLatin1String("input"), QScriptValueImpl(eng, S));
return r;
#endif // QT_NO_REGEXP
}
QScriptValueImpl RegExp::method_test(QScriptContextPrivate *context, QScriptEnginePrivate *eng, QScriptClassInfo *classInfo)
{
QScriptValueImpl r = method_exec(context, eng, classInfo);
return QScriptValueImpl(!r.isNull());
}
QScriptValueImpl RegExp::method_toString(QScriptContextPrivate *context, QScriptEnginePrivate *eng, QScriptClassInfo *classInfo)
{
if (Instance *instance = Instance::get(context->thisObject(), classInfo)) {
QString result;
result += QLatin1Char('/');
#ifndef QT_NO_REGEXP
const QString &pattern = instance->value.pattern();
#else
const QString &pattern = instance->pattern;
#endif
if (pattern.isEmpty())
result += QLatin1String("(?:)");
else
result += pattern; // ### quote
result += QLatin1Char('/');
result += flagsToString(instance->flags);
return (QScriptValueImpl(eng, result));
}
return throwThisObjectTypeError(
context, QLatin1String("RegExp.prototype.toString"));
}
} } // namespace QScript::Ecma
QT_END_NAMESPACE
| 32.674556
| 128
| 0.644603
|
privet56
|
c0134e53b20391e75b46a74e808fd577475e06ff
| 860
|
hh
|
C++
|
include/Vector2.hh
|
KPO-2020-2021/zad4-259355
|
3090b8aca05b95d22e456edd147d29541fdf58bd
|
[
"Unlicense"
] | null | null | null |
include/Vector2.hh
|
KPO-2020-2021/zad4-259355
|
3090b8aca05b95d22e456edd147d29541fdf58bd
|
[
"Unlicense"
] | null | null | null |
include/Vector2.hh
|
KPO-2020-2021/zad4-259355
|
3090b8aca05b95d22e456edd147d29541fdf58bd
|
[
"Unlicense"
] | null | null | null |
#ifndef Vector2_HH
#define Vector2_HH
#include "vector.hh"
typedef Vector<double, 2> Vector2;
//Definicje metod szczegolnych gdy dzialamy na wektorach2D
//Przeciazenie operatora porownania
//Przeciazenie operatora roznych
//Przeciazenie operatora wejscia i wyjscia
template<>
bool Vector2::operator == (const Vector2 tmp) const ;
template<>
bool Vector2::operator != (const Vector2 tmp) const ;
// template<>
// Vector2 Vector();
// template<>
// Vector2(double tmp[2]);
template<>
Vector2 Vector2::operator + (const Vector2 &v);
template<>
Vector2 Vector2::operator - (const Vector2 &v);
template<>
Vector2 Vector2::operator * (const double &tmp);
template<>
Vector2 Vector2::operator / (const double &tmp);
std::istream &operator >> (std::istream &in, Vector2 &tmp);
std::ostream &operator << (std::ostream &stream, Vector2 const &tmp);
#endif
| 20.47619
| 69
| 0.72907
|
KPO-2020-2021
|
c017cca7693a58c8720766c2c29e12eee58572ef
| 1,373
|
cpp
|
C++
|
src/bindings/python/PyLogTransform.cpp
|
rakoman/OpenColorIO
|
7ec3772ac7f3594584041261f362cd952b8b6acf
|
[
"BSD-3-Clause"
] | 1
|
2021-10-20T03:06:38.000Z
|
2021-10-20T03:06:38.000Z
|
src/bindings/python/PyLogTransform.cpp
|
rakoman/OpenColorIO
|
7ec3772ac7f3594584041261f362cd952b8b6acf
|
[
"BSD-3-Clause"
] | 2
|
2020-05-21T11:19:23.000Z
|
2020-05-21T11:26:09.000Z
|
src/bindings/python/PyLogTransform.cpp
|
rakoman/OpenColorIO
|
7ec3772ac7f3594584041261f362cd952b8b6acf
|
[
"BSD-3-Clause"
] | 1
|
2020-05-21T11:25:19.000Z
|
2020-05-21T11:25:19.000Z
|
// SPDX-License-Identifier: BSD-3-Clause
// Copyright Contributors to the OpenColorIO Project.
#include "PyTransform.h"
namespace OCIO_NAMESPACE
{
void bindPyLogTransform(py::module & m)
{
LogTransformRcPtr DEFAULT = LogTransform::Create();
py::class_<LogTransform,
LogTransformRcPtr /* holder */,
Transform /* base */>(m, "LogTransform")
.def(py::init(&LogTransform::Create))
.def(py::init([](double base, TransformDirection dir)
{
LogTransformRcPtr p = LogTransform::Create();
p->setBase(base);
p->setDirection(dir);
p->validate();
return p;
}),
"base"_a = DEFAULT->getBase(),
"dir"_a = DEFAULT->getDirection())
.def("getFormatMetadata",
(FormatMetadata & (LogTransform::*)()) &LogTransform::getFormatMetadata,
py::return_value_policy::reference_internal)
.def("getFormatMetadata",
(const FormatMetadata & (LogTransform::*)() const) &LogTransform::getFormatMetadata,
py::return_value_policy::reference_internal)
.def("equals", &LogTransform::equals, "other"_a)
.def("getBase", &LogTransform::getBase)
.def("setBase", &LogTransform::setBase, "val"_a);
}
} // namespace OCIO_NAMESPACE
| 33.487805
| 97
| 0.588492
|
rakoman
|
c018c4936bda07707c1e9a37173b829b61e552c9
| 19,816
|
cpp
|
C++
|
src/sip-transports.cpp
|
danias/drachtio-server
|
cf8bb18e74a1eb2380053e3c31cfa398efd513d4
|
[
"MIT"
] | null | null | null |
src/sip-transports.cpp
|
danias/drachtio-server
|
cf8bb18e74a1eb2380053e3c31cfa398efd513d4
|
[
"MIT"
] | null | null | null |
src/sip-transports.cpp
|
danias/drachtio-server
|
cf8bb18e74a1eb2380053e3c31cfa398efd513d4
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2013, David C Horton
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 <algorithm>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <arpa/inet.h>
#include "sip-transports.hpp"
#include "controller.hpp"
#include "drachtio.h"
namespace {
/* needed to be able to live in a boost unordered container */
size_t hash_value( const drachtio::SipTransport& d) {
std::size_t seed = 0;
boost::hash_combine(seed, d.getTport());
return seed;
}
}
namespace drachtio {
SipTransport::SipTransport(const string& contact, const string& localNet, const string& externalIp) :
m_strContact(contact), m_strExternalIp(externalIp), m_strLocalNet(localNet), m_tp(NULL) {
init() ;
}
SipTransport::SipTransport(const string& contact, const string& localNet) :
m_strContact(contact), m_strLocalNet(localNet), m_tp(NULL) {
init() ;
}
SipTransport::SipTransport(const string& contact) : m_strContact(contact), m_tp(NULL) {
init() ;
}
SipTransport::SipTransport(const std::shared_ptr<drachtio::SipTransport> other) :
m_strContact(other->m_strContact), m_strLocalNet(other->m_strLocalNet), m_strExternalIp(other->m_strExternalIp),
m_dnsNames(other->m_dnsNames), m_tp(NULL) {
init() ;
}
SipTransport::~SipTransport() {
}
void SipTransport::init() {
if( !parseSipUri(m_strContact, m_contactScheme, m_contactUserpart, m_contactHostpart, m_contactPort, m_contactParams) ) {
cerr << "SipTransport::init - contact: " << m_strContact << endl ;
throw std::runtime_error(string("SipTransport::init - invalid contact ") + m_strContact);
}
if( !m_strExternalIp.empty() ) {
try {
std::regex re("^([0-9\\.]*)$");
std::smatch mr;
if (!std::regex_search(m_strExternalIp, mr, re)) {
cerr << "SipTransport::init - invalid format for externalIp, must be ipv4 dot decimal address: " << m_strExternalIp << endl ;
throw std::runtime_error("SipTransport::init - invalid format for externalIp, must be ipv4 dot decimal address");
}
} catch( std::regex_error& e) {
DR_LOG(log_error) << "SipTransport::init - regex error " << e.what();
}
}
bool hasNetmask = false;
string network, bits;
uint32_t netbits;
if( !m_strLocalNet.empty() ) {
hasNetmask = true;
try {
std::regex re("^([0-9\\.]*)\\/(.*)$");
std::smatch mr;
if (!std::regex_search(m_strLocalNet, mr, re)) {
cerr << "SipTransport::init - invalid format for localNet, must be CIDR format: " << m_strLocalNet << endl ;
throw std::runtime_error("SipTransport::init - invalid format for localNet, must be CIDR format");
}
network = mr[1] ;
bits = mr[2];
} catch (std::regex_error& e) {
DR_LOG(log_error) << "SipTransport::init - regex error 2 " << e.what();
}
}
if (hasNetmask) {
struct sockaddr_in range;
inet_pton(AF_INET, network.c_str(), &(range.sin_addr));
m_range = htonl(range.sin_addr.s_addr) ;
uint32_t netbits = ::atoi( bits.c_str() ) ;
m_netmask = ~(~uint32_t(0) >> netbits);
}
}
bool SipTransport::shouldAdvertisePublic( const char* address ) const {
if( !hasExternalIp() ) return false ;
return !isInNetwork(address) ;
}
bool SipTransport::isInNetwork(const char* address) const {
if (!m_netmask) return false;
struct sockaddr_in addr;
inet_pton(AF_INET, address, &(addr.sin_addr));
uint32_t ip = htonl(addr.sin_addr.s_addr) ;
return (ip & m_netmask) == (m_range & m_netmask) ;
}
void SipTransport::getDescription(string& s, bool shortVersion) {
s = "" ;
if( hasTport() ) {
s += getProtocol() ;
s += "/" ;
s += getHost() ;
s += ":" ;
s += getPort() ;
if( shortVersion ) return ;
s += " ";
}
s += "(";
s += getContact() ;
s += ", external-ip: " ;
s += getExternalIp() ;
s += ", local-net: " ;
s += getLocalNet() ;
s += ")" ;
if( m_dnsNames.size() ) {
s += " dns names: " ;
int i = 0 ;
for( vector<string>::const_iterator it = m_dnsNames.begin(); it != m_dnsNames.end(); ++it, i++ ) {
if( i++ ) {
s+= ", " ;
}
s += *it ;
}
}
}
void SipTransport::getHostport(string& s) {
assert(hasTport()) ;
s = "" ;
s += getProtocol() ;
s += "/" ;
s += hasExternalIp() ? getExternalIp() : getHost() ;
s += ":" ;
s += getPort() ;
}
void SipTransport::getBindableContactUri(string& contact) {
contact = m_contactScheme ;
contact.append(":");
//host
if (hasExternalIp()) {
contact.append(m_strExternalIp) ;
}
else {
contact.append(m_contactHostpart) ;
}
//port
if (!m_contactPort.empty()) {
contact.append(":") ;
contact.append(m_contactPort) ;
}
//parameters
for (vector< pair<string,string> >::const_iterator it = m_contactParams.begin(); it != m_contactParams.end(); ++it) {
contact.append(";");
contact.append(it->first) ;
if( !it->second.empty() ) {
contact.append("=");
contact.append(it->second) ;
}
}
if (hasExternalIp()) {
contact.append(";maddr=");
contact.append(m_contactHostpart);
}
DR_LOG(log_debug) << "SipTransport::getBindableContactUri: " << contact;
}
void SipTransport::getContactUri(string& contact, bool useExternalIp) {
contact = m_contactScheme ;
contact.append(":");
if( !m_contactUserpart.empty() ) {
contact.append(m_contactUserpart) ;
contact.append("@") ;
}
if( m_tp ) {
contact.append(useExternalIp && !m_strExternalIp.empty() ? m_strExternalIp : getHost()) ;
const char* szPort = getPort() ;
const char* szProto = getProtocol() ;
if( szPort && strlen(szPort) > 0 ) {
contact.append(":") ;
contact.append(szPort);
}
}
else {
contact.append(useExternalIp && !m_strExternalIp.empty() ? m_strExternalIp : m_contactHostpart) ;
if( !m_contactPort.empty() ) {
contact.append(":") ;
contact.append(m_contactPort);
}
if( m_contactParams.size() > 0 ) {
for (vector< pair<string,string> >::const_iterator it = m_contactParams.begin(); it != m_contactParams.end(); ++it) {
pair<string,string> kv = *it ;
contact.append(";") ;
contact.append(kv.first);
if( !kv.second.empty() ) {
contact.append("=") ;
contact.append(kv.second) ;
}
}
}
}
DR_LOG(log_debug) << "SipTransport::getContactUri - created Contact header: " << contact;
}
sip_via_t* SipTransport::makeVia(su_home_t * h, const char* szRemoteHost) {
bool isInSubnet = szRemoteHost ? this->isInNetwork(szRemoteHost) : false;
string host = this->getHost();
if (this->hasExternalIp() && !isInSubnet) {
host = this->getExternalIp();
}
string proto = this->getProtocol();
if (0 == proto.length()) proto = "UDP";
boost::to_upper(proto);
string transport = string("SIP/2.0/") + proto;
DR_LOG(log_debug) << "SipTransport::makeVia - host " << host << ", port " << this->getPort() << ", transport " << transport ;
return sip_via_create(h, host.c_str(), this->getPort(), transport.c_str());
}
bool SipTransport::isIpV6(void) {
return hasTport() && NULL != strstr( getHost(), "[") && NULL != strstr( getHost(), "]") ;
}
bool SipTransport::isLocalhost(void) {
return hasTport() && (0 == strcmp(getHost(), "127.0.0.1") || 0 == strcmp(getHost(), "[::1]"));
}
bool SipTransport::isLocal(const char* szHost) {
if( 0 == strcmp(getHost(), szHost) ) {
return true ;
}
else if( 0 == m_contactHostpart.compare(szHost) ) {
return true ;
}
else if( hasExternalIp() && 0 == m_strExternalIp.compare(szHost) ) {
return true ;
}
for( vector<string>::const_iterator it = m_dnsNames.begin(); it != m_dnsNames.end(); ++it ) {
if( 0 == (*it).compare(szHost) ) {
return true ;
}
}
return false ;
}
uint32_t SipTransport::getOctetMatchCount(const string& address) {
uint32_t count = 0 ;
string them[4], mine[4];
try {
std::regex re("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");
std::smatch mr;
if (std::regex_search(address, mr, re) && mr.size() > 1) {
them[0] = mr[1] ;
them[1] = mr[2] ;
them[2] = mr[3] ;
them[3] = mr[4] ;
string host = this->getHost();
if (std::regex_search(host, mr, re) && mr.size() > 1) {
mine[0] = mr[1] ;
mine[1] = mr[2] ;
mine[2] = mr[3] ;
mine[3] = mr[4] ;
for(int i = 0; i < 4; i++) {
if(0 != them[i].compare(mine[i])) return count;
count++;
}
}
}
} catch (std::regex_error& e) {
DR_LOG(log_error) << "SipTransport::getOctetMatchCount - regex error " << e.what();
}
return count;
}
/** static methods */
SipTransport::mapTport2SipTransport SipTransport::m_mapTport2SipTransport ;
std::shared_ptr<SipTransport> SipTransport::m_masterTransport ;
/**
* iterate all tport_t* that have been created, and any that are "unassigned" associate
* them with the provided SipTransport
*
* @param config - SipTransport that was used to create the currently unassigned tport_t*
*/
void SipTransport::addTransports(std::shared_ptr<SipTransport> config, unsigned int mtu) {
tport_t* tp = nta_agent_tports(theOneAndOnlyController->getAgent());
m_masterTransport = std::make_shared<SipTransport>( config ) ;
m_masterTransport->setTport(tp) ;
while (NULL != (tp = tport_next(tp) )) {
const tp_name_t* tpn = tport_name(tp) ;
string desc ;
getTransportDescription( tp, desc );
if (0 == strcmp(tpn->tpn_proto, "udp") && mtu > 0) {
tport_set_params(tp, TPTAG_MTU(mtu), TAG_END());
}
mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.find(tp) ;
if (it == m_mapTport2SipTransport.end()) {
DR_LOG(log_info) << "SipTransport::addTransports - creating transport: " << hex << tp << ": " << desc ;
std::shared_ptr<SipTransport> p = std::make_shared<SipTransport>( config ) ;
p->setTport(tp);
p->setTportName(tpn) ;
m_mapTport2SipTransport.insert(mapTport2SipTransport::value_type(tp, p)) ;
if (p->getLocalNet().empty()) {
string network, bits;
string host = p->hasExternalIp() ? p->getExternalIp() : p->getHost();
if(0 == host.compare("127.0.0.1")) {
network = "127.0.0.1";
bits = "32";
}
else if(0 == host.find("192.168.0.")) {
network = "192.168.0.0";
bits = "24";
}
else if(0 == host.find("172.16.")) {
network = "172.16.0.0";
bits = "16";
}
else if(0 == host.find("10.")) {
network = "10.0.0.0";
bits = "8";
}
if (!network.empty()) {
struct sockaddr_in range;
inet_pton(AF_INET, network.c_str(), &(range.sin_addr));
p->setRange(htonl(range.sin_addr.s_addr)) ;
uint32_t netbits = ::atoi( bits.c_str() ) ;
p->setNetmask(~(~uint32_t(0) >> netbits));
p->setNetwork(network);
p->setLocalNet(network, bits);
}
}
}
}
}
std::shared_ptr<SipTransport> SipTransport::findTransport(tport_t* tp) {
mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.find(tp) ;
if( it == m_mapTport2SipTransport.end() ) {
tport_t* tpp = tport_parent(tp);
DR_LOG(log_debug) << "SipTransport::findTransport - could not find transport: " << hex << tp << " searching for parent " << tpp ;
it = m_mapTport2SipTransport.find(tport_parent(tpp));
}
assert( it != m_mapTport2SipTransport.end() ) ;
return it->second ;
}
std::shared_ptr<SipTransport> SipTransport::findAppropriateTransport(const char* remoteHost, const char* proto) {
string scheme, userpart, hostpart, port ;
vector< pair<string,string> > vecParam ;
string host = remoteHost ;
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport: searching for a transport to reach " << proto << "/" << remoteHost ;
if( parseSipUri(host, scheme, userpart, hostpart, port, vecParam) ) {
host = hostpart ;
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport: host parsed as " << host;
}
string desc ;
bool wantsIpV6 = (NULL != strstr( remoteHost, "[") && NULL != strstr( remoteHost, "]")) ;
// create vector of candidates, remove those with wrong transport or protocol
// then sort from most to least desirable:
// - transports within the subnet of the remote host
// - transports that have an external address
// - ...all others, and finally..
// - transports bound to localhost
std::vector< std::shared_ptr<SipTransport> > candidates;
std::pair< tport_t*, boost::shared_ptr<SipTransport> > myPair;
for (auto pair : m_mapTport2SipTransport) {
candidates.push_back(pair.second);
}
// filter by transport
auto it = std::remove_if(candidates.begin(), candidates.end(), [wantsIpV6](const std::shared_ptr<SipTransport>& p) {
return (wantsIpV6 && !p->isIpV6()) || (!wantsIpV6 && p->isIpV6());
});
candidates.erase(it, candidates.end());
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport - after filtering for transport we have " << candidates.size() << " candidates";
// filter by protocol
it = std::remove_if(candidates.begin(), candidates.end(), [proto](const std::shared_ptr<SipTransport>& p) {
if (!proto) return false;
return 0 != strcmp(p->getProtocol(), proto);
});
candidates.erase(it, candidates.end());
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport - after filtering for protocol we have " << candidates.size() << " candidates";
sort(candidates.begin(), candidates.end(), [host](const std::shared_ptr<SipTransport>& pA, const std::shared_ptr<SipTransport>& pB) {
if (pA->isInNetwork(host.c_str())) {
return true;
}
if (pB->isInNetwork(host.c_str())) {
return false;
}
uint32_t a = pA->getOctetMatchCount(host);
uint32_t b = pB->getOctetMatchCount(host);
if (a > b) return true;
if (a < b) return false;
if (pA->hasExternalIp()) return true;
if (pB->hasExternalIp()) return false;
if (pA->isLocalhost()) return false;
if (pB->isLocalhost()) return true;
return true;
});
#ifdef DEBUG
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport - in priority order, here are the candidates for sending to " << host;
BOOST_FOREACH(std::shared_ptr<SipTransport>& p, candidates) {
string desc;
p->getDescription(desc);
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport - " << desc;
}
#endif
if (candidates.empty()) {
m_masterTransport->getDescription(desc) ;
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport: - returning master transport " << hex << m_masterTransport->getTport() <<
" as we found no better matches: " << desc ;
return m_masterTransport ;
}
std::shared_ptr<SipTransport> p = candidates[0];
p->getDescription(desc);
DR_LOG(log_debug) << "SipTransport::findAppropriateTransport: - returning the best match " << hex << p->getTport() << ": " << desc ;
return p ;
}
void SipTransport::getAllExternalIps( vector<string>& vec ) {
for (mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.begin(); m_mapTport2SipTransport.end() != it; ++it ) {
std::shared_ptr<SipTransport> p = it->second ;
if( p->hasExternalIp() ) {
vec.push_back(p->getExternalIp()) ;
}
for( vector<string>::const_iterator itDns = p->getDnsNames().begin(); itDns != p->getDnsNames().end(); ++itDns ) {
vec.push_back(*itDns) ;
}
}
}
void SipTransport::getAllExternalContacts( vector< pair<string, string> >& vec ) {
for (mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.begin(); m_mapTport2SipTransport.end() != it; ++it ) {
std::shared_ptr<SipTransport> p = it->second ;
string port = p->getPort() != NULL ? p->getPort() : "5060";
if( p->hasExternalIp() ) {
vec.push_back( make_pair(p->getExternalIp(), port)) ;
}
for( vector<string>::const_iterator itDns = p->getDnsNames().begin(); itDns != p->getDnsNames().end(); ++itDns ) {
vec.push_back( make_pair(*itDns, port)) ;
}
}
}
void SipTransport::getAllHostports( vector<string>& vec ) {
for (mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.begin(); m_mapTport2SipTransport.end() != it; ++it ) {
std::shared_ptr<SipTransport> p = it->second ;
string desc ;
p->getHostport(desc);
vec.push_back(desc) ;
}
}
bool SipTransport::isLocalAddress(const char* szHost, tport_t* tp) {
if( tp ) {
std::shared_ptr<SipTransport> p = SipTransport::findTransport(tp) ;
return p->isLocal(szHost);
}
// search all
for (mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.begin(); m_mapTport2SipTransport.end() != it; ++it ) {
std::shared_ptr<SipTransport> p = it->second ;
if( p->isLocal(szHost) ) {
return true ;
}
for( vector<string>::const_iterator itDns = p->getDnsNames().begin(); itDns != p->getDnsNames().end(); ++itDns ) {
if( 0 == (*itDns).compare(szHost) ) {
return true;
}
}
}
return false;
}
void SipTransport::logTransports() {
DR_LOG(log_info) << "SipTransport::logTransports - there are : " << dec << m_mapTport2SipTransport.size() << " transports";
for (mapTport2SipTransport::const_iterator it = m_mapTport2SipTransport.begin(); m_mapTport2SipTransport.end() != it; ++it ) {
std::shared_ptr<SipTransport> p = it->second ;
string desc ;
p->getDescription(desc, false) ;
if (0 == strcmp(p->getProtocol(), "udp")) {
unsigned int mtuSize = 0;
const tport_t* tp = p->getTport();
tport_get_params(tp, TPTAG_MTU_REF(mtuSize), TAG_END());
DR_LOG(log_info) << "SipTransport::logTransports - " << desc << ", mtu size: " << mtuSize;
}
else {
DR_LOG(log_info) << "SipTransport::logTransports - " << desc ;
}
}
}
}
| 34.643357
| 146
| 0.606833
|
danias
|
c021f01b79d0f331a61a7f0aba6a7bdc21cb98a6
| 5,454
|
cpp
|
C++
|
die_source/gui_source/threadentropy.cpp
|
jha334201553/DIE-engine-PEID-
|
f251958c2bbb1ed23a5dac87f3e72659c85dc276
|
[
"MIT"
] | null | null | null |
die_source/gui_source/threadentropy.cpp
|
jha334201553/DIE-engine-PEID-
|
f251958c2bbb1ed23a5dac87f3e72659c85dc276
|
[
"MIT"
] | null | null | null |
die_source/gui_source/threadentropy.cpp
|
jha334201553/DIE-engine-PEID-
|
f251958c2bbb1ed23a5dac87f3e72659c85dc276
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2012-2019 hors<horsicq@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "threadentropy.h"
ThreadEntropy::ThreadEntropy(QObject *parent) :
QObject(parent)
{
bIsRun=false;
bIsCompleted=true;
}
void ThreadEntropy::setData(Binary *_binary,unsigned int nOffset,unsigned int nSize,double *pXEntropy,double *pYEntropy,double *pXHistogram,double *pYHistogram,int nPunkts)
{
this->_binary=_binary;
this->nOffset=nOffset;
this->nSize=nSize;
this->pXEntropy=pXEntropy;
this->pYEntropy=pYEntropy;
this->pXHistogram=pXHistogram;
this->pYHistogram=pYHistogram;
this->nPunkts=nPunkts;
}
void ThreadEntropy::_stop()
{
bIsRun=false;
}
bool ThreadEntropy::isCompleted()
{
return bIsCompleted;
}
double ThreadEntropy::getEntropy(unsigned int nDataOffset,unsigned int nDataSize,bool bProgressBar)
{
if(nDataSize==0)
{
return 0;
}
double dEntropy=1.4426950408889634073599246810023;
QByteArray baTemp;
baTemp.resize(BUFFER_SIZE);
unsigned int _nSize=nDataSize;
double bytes[256]= {0.0};
double temp;
unsigned int nTemp=0;
unsigned int nCount=nDataSize/BUFFER_SIZE;
unsigned int _nOffset=nDataOffset;
int k=0;
for(unsigned int i=0; (i<nCount+1)&&(bIsRun); i++)
{
nTemp=MINIMAL(BUFFER_SIZE,_nSize);
if(!_binary->readArrayFromFile(_nOffset,baTemp.data(),nTemp))
{
bIsRun=false;
}
for(unsigned int m=0; m<nTemp; m++)
{
bytes[(unsigned char)baTemp.data()[m]]+=1;
}
_nSize-=nTemp;
_nOffset+=nTemp;
if(bProgressBar)
{
if(i+1>(nCount/30)*k)
{
emit setProgressBar(nCount,i+1);
k++;
}
}
}
for(int j=0; (j<256)&&(bIsRun); j++)
{
temp=bytes[j]/(double)nDataSize;
if(temp)
{
dEntropy+=(-log(temp)/log((double)2))*bytes[j];
}
}
dEntropy=dEntropy/(double)nDataSize;
return dEntropy;
}
void ThreadEntropy::getHistogram(unsigned int nDataOffset, unsigned int nDataSize, double *pX,bool bProgressBar)
{
QByteArray baTemp;
baTemp.resize(BUFFER_SIZE);
unsigned int _nSize=nDataSize;
unsigned int nTemp=0;
unsigned int nCount=nDataSize/BUFFER_SIZE;
unsigned int _nOffset=nDataOffset;
int k=0;
for(unsigned int i=0; (i<nCount+1)&&(bIsRun); i++)
{
nTemp=MINIMAL(BUFFER_SIZE,_nSize);
if(!_binary->readArrayFromFile(_nOffset,baTemp.data(),nTemp))
{
bIsRun=false;
}
for(unsigned int m=0; m<nTemp; m++)
{
pX[(unsigned char)baTemp.data()[m]]+=1;
}
_nSize-=nTemp;
_nOffset+=nTemp;
if(bProgressBar)
{
if(i+1>(nCount/30)*k)
{
emit setProgressBar(nCount,i+1);
k++;
}
}
}
}
void ThreadEntropy::process()
{
if(bIsRun)
{
return;
}
bIsRun=true;
bIsCompleted=false;
getHistogram(nOffset,nSize,pYHistogram);
double dEntropy=getEntropy(nOffset,nSize);
// new>>
pYEntropy[nPunkts]=dEntropy;
//<<
emit setEntropy(dEntropy);
unsigned int nProcent=nSize/nPunkts;
if(nProcent)
{
for(int i=0; (i<nPunkts)&&(bIsRun); i++)
{
pXEntropy[i]=i*nProcent+nOffset;
pYEntropy[i]=dEntropy;
// qDebug("%d x=%f y=%f",i,pXEntropy[i],pYEntropy[i]);
}
}
else
{
for(int i=0; (i<nPunkts)&&(bIsRun); i++)
{
pXEntropy[i]=0;
pYEntropy[i]=dEntropy;
}
pXEntropy[0]=nOffset;
pYEntropy[0]=dEntropy;
pXEntropy[1]=nOffset+nSize;
pYEntropy[1]=dEntropy;
}
emit reloadGraph();
if(nProcent)
{
int k=0;
for(int j=0; (j<nPunkts-nPunkts/10)&&(bIsRun); j++)
{
dEntropy=getEntropy(nOffset+j*nProcent,nProcent*(nPunkts/10),false);
pYEntropy[j]=dEntropy;
if(j+1>(100/30)*k)
{
emit setProgressBar(nPunkts,j+1);
k++;
}
emit reloadGraph();
}
}
emit setProgressBar(1,1);
emit _finished();
bIsRun=false;
// msleep(1000);
bIsCompleted=true;
}
| 23.110169
| 172
| 0.59956
|
jha334201553
|
c026e664cab0985bf31353f1535f996277729da0
| 560
|
hpp
|
C++
|
src/ir/ir_member_access.hpp
|
traplol/malang
|
3c02f4f483b7580a557841c31a65bf190fd1228f
|
[
"MIT"
] | 4
|
2017-10-31T14:01:58.000Z
|
2019-07-16T04:53:32.000Z
|
src/ir/ir_member_access.hpp
|
traplol/malang
|
3c02f4f483b7580a557841c31a65bf190fd1228f
|
[
"MIT"
] | null | null | null |
src/ir/ir_member_access.hpp
|
traplol/malang
|
3c02f4f483b7580a557841c31a65bf190fd1228f
|
[
"MIT"
] | 2
|
2018-01-23T12:59:07.000Z
|
2019-07-16T04:53:39.000Z
|
#ifndef MALANG_IR_IR_MEMBER_ACCESS_HPP
#define MALANG_IR_IR_MEMBER_ACCESS_HPP
#include "ir_values.hpp"
struct IR_Member_Access : IR_LValue
{
virtual ~IR_Member_Access() = default;
IR_Member_Access(const Source_Location &src_loc, IR_Value *thing, const std::string &member_name)
: IR_LValue(src_loc)
, thing(thing)
, member_name(member_name)
{}
IR_NODE_OVERRIDES;
virtual Type_Info *get_type() const override;
IR_Value *thing;
std::string member_name;
};
#endif /* MALANG_IR_IR_MEMBER_ACCESS_HPP */
| 23.333333
| 101
| 0.719643
|
traplol
|
c02a9d0b06b03f0a55ffa2f292f21fe6ac497f9e
| 1,134
|
cpp
|
C++
|
Binary-String-MEX.cpp
|
Sayan3990/Codechef
|
e693927efb4ce12c3e12875aa7082c2001d09b7c
|
[
"MIT"
] | 1
|
2021-07-11T10:34:25.000Z
|
2021-07-11T10:34:25.000Z
|
Binary-String-MEX.cpp
|
Sayan3990/Codechef
|
e693927efb4ce12c3e12875aa7082c2001d09b7c
|
[
"MIT"
] | null | null | null |
Binary-String-MEX.cpp
|
Sayan3990/Codechef
|
e693927efb4ce12c3e12875aa7082c2001d09b7c
|
[
"MIT"
] | null | null | null |
// https://www.codechef.com/APRIL21B/problems/MEXSTR
#include <iostream>
#include <cstring>
#include <cmath>
#include <bitset>
#define lli long long int
#define SIZE 1000000
using namespace std;
int match(bitset<SIZE> &S, bitset<SIZE> &sub, lli num, lli num2) {
lli i = num, j = num2;
while(1) {
if (j == -1) break;
if (i == -1) return -1;
if (sub[j] == S[i]) j--;
i--;
}
return 1;
}
void MEX(string &S) {
if (S.find('0') == string::npos) {
cout << "0" << endl;
return;
}
bitset<SIZE> ans;
bitset<SIZE> Sbit(S);
lli lim = pow(2, 4*S.length()), i, j;
for (i = 1; i <= lim; i++) {
ans = i;
j = (lli)log2(i)+1;
//cout << i << " HI " << j << endl;
if (match(Sbit, ans, S.length(), j) == -1) break;
}
while(j>0)
cout << ans[--j];
cout << endl;
}
void solution() {
string S;
cin >> S;
MEX(S);
}
int main() {
long test;
cin >> test;
while (test--) solution();
return 0;
}
| 18.9
| 67
| 0.444444
|
Sayan3990
|
c02db33cd76a23bd303fba601861377ad2564e87
| 23,789
|
cpp
|
C++
|
imap/src/ImapClient.cpp
|
webOS-ports/mojomail
|
49358ac2878e010f5c6e3bd962f047c476c11fc3
|
[
"Apache-2.0"
] | 6
|
2015-01-09T02:20:27.000Z
|
2021-01-02T08:14:23.000Z
|
mojomail/imap/src/ImapClient.cpp
|
openwebos/app-services
|
021d509d609fce0cb41a0e562650bdd1f3bf4e32
|
[
"Apache-2.0"
] | 3
|
2019-05-11T19:17:56.000Z
|
2021-11-24T16:04:36.000Z
|
mojomail/imap/src/ImapClient.cpp
|
openwebos/app-services
|
021d509d609fce0cb41a0e562650bdd1f3bf4e32
|
[
"Apache-2.0"
] | 6
|
2015-01-09T02:21:13.000Z
|
2021-01-02T02:37:10.000Z
|
// @@@LICENSE
//
// Copyright (c) 2010-2013 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// LICENSE@@@
#include "ImapClient.h"
#include "commands/ImapAccountFinder.h"
#include "data/ImapAccount.h"
#include "boost/shared_ptr.hpp"
#include "data/DatabaseInterface.h"
#include "ImapServiceApp.h"
#include "ImapPrivate.h"
#include "client/ImapSession.h"
#include "client/FileCacheClient.h"
#include "client/SyncSession.h"
#include "client/PowerManager.h"
#include "commands/DeleteAccountCommand.h"
#include "commands/DisableAccountCommand.h"
#include "commands/CheckOutboxCommand.h"
#include "commands/ImapSyncSessionCommand.h"
#include "commands/ScheduleRetryCommand.h"
#include "commands/SyncAccountCommand.h"
#include "commands/SyncFolderCommand.h"
#include "commands/UpdateAccountCommand.h"
#include "commands/SyncFolderCommand.h"
#include "commands/CheckOutboxCommand.h"
#include "commands/CheckDraftsCommand.h"
#include "commands/EnableAccountCommand.h"
#include "commands/UpdateAccountErrorCommand.h"
#include "client/DownloadListener.h"
using namespace boost;
using namespace std;
MojLogger ImapClient::s_log("com.palm.imap.client");
ImapClient::ImapClient(MojLunaService* service, ImapBusDispatcher* dispatcher, const MojObject& accountId, const boost::shared_ptr<DatabaseInterface>& dbInterface)
: BusClient(service),
m_busDispatcher(dispatcher),
m_dbInterface(dbInterface),
m_fileCacheClient(new FileCacheClient(*this)),
m_powerManager(new PowerManager(*this)),
m_accountId(accountId),
m_accountIdString(AsJsonString(accountId)),
m_log(s_log),
m_commandManager(new CommandManager(CommandManager::DEFAULT_MAX_CONCURRENT_COMMANDS, true)),
m_state(State_NeedsAccountInfo),
m_retryInterval(0),
m_cleanupSessionCallbackId(0),
m_getAccountRetries(0),
m_smtpAccountEnabledSlot(this, &ImapClient::SmtpAccountEnabledResponse)
{
}
ImapClient::~ImapClient()
{
}
void ImapClient::LoginSuccess()
{
}
/**
* Set the account using an account object from the database.
*/
void ImapClient::SetAccount(const boost::shared_ptr<ImapAccount>& account)
{
MojLogTrace(m_log);
if(account.get()) {
m_account = account;
HookUpFolderSessionAccounts();
if(m_state == State_GettingAccount) {
SetState(State_RunCommand);
CheckQueue();
}
} else {
MojLogCritical(m_log, "failed to get account %s from database", AsJsonString(GetAccountId()).c_str());
if(!DisableAccountInProgress()) {
// Reset so it can try again later
SetState(State_NeedsAccountInfo);
}
// The first time, check the queue immediately so it tries again quickly.
// After that, only if something else nudges it.
if(m_getAccountRetries++ < 1) {
MojLogInfo(m_log, "retrying getting account");
CheckQueue();
} else {
CancelPendingCommands(ImapCommand::CancelType_NoAccount);
}
}
}
/**
* Create a session for this client. If client already has a member account
* will be automatically assigned into the session
*/
ImapClient::ImapSessionPtr ImapClient::CreateSession() {
MojRefCountedPtr<ImapClient> clientPtr(this);
ImapSessionPtr session(new ImapSession(clientPtr));
session->SetDatabase(*m_dbInterface.get());
session->SetFileCacheClient(*m_fileCacheClient.get());
session->SetBusClient(*this);
session->SetPowerManager(m_powerManager);
if (m_account.get() != NULL) {
session->SetAccount(m_account);
} // otherwise, rely on getAccount handler to set account for map sessions
return session;
}
/**
* Create session with folder id. account will be assigned if one exists in client
*/
ImapClient::ImapSessionPtr ImapClient::CreateSession(const MojObject& folderId) {
MojLogInfo(m_log, "creating session for folderId %s", AsJsonString(folderId).c_str());
ImapSessionPtr sess = CreateSession();
sess->SetFolder(folderId);
return sess;
}
void ImapClient::SetState(ClientState state)
{
MojLogInfo(m_log, "setting client state from %s (%d) to %s (%d)",
GetStateName(m_state), m_state, GetStateName(state), state);
m_state = state;
if(m_state != State_RunCommand) {
m_commandManager->Pause();
}
// Update bus dispatcher so it knows that we're now active/inactive
if(m_busDispatcher)
m_busDispatcher->UpdateClientActive(this, IsActive());
}
void ImapClient::CheckQueue()
{
MojLogInfo(m_log, "checking the queue for client %s. current state: %s (%d)", m_accountIdString.c_str(), GetStateName(m_state), m_state);
switch(m_state)
{
case State_None:
{
MojLogCritical(m_log, "unable to run commands, no account available");
break;
}
case State_NeedsAccountInfo:
{
SetState(State_GettingAccount);
MojRefCountedPtr<ImapAccountFinder> command(new ImapAccountFinder(*this, m_accountId, true));
m_commandManager->RunCommand(command);
break;
}
case State_GettingAccount:
{
break;
}
case State_LoginFailed:
{
break;
}
case State_RunCommand:
{
// Implicitly runs commands
m_commandManager->Resume();
break;
}
case State_TerminatingSessions:
{
break;
}
case State_DisableAccount:
{
MojLogNotice(m_log, "disabling account %s", AsJsonString(m_accountId).c_str());
SetState(State_DisablingAccount);
MojRefCountedPtr<DisableAccountCommand> command(new DisableAccountCommand(*this, m_accountEnabledMsg, m_payload));
m_commandManager->RunCommand(command);
break;
}
case State_DisablingAccount:
{
break;
}
case State_DisabledAccount:
{
break;
}
case State_DeleteAccount:
{
MojLogNotice(m_log, "deleting account %s", AsJsonString(m_accountId).c_str());
SetState(State_DeletingAccount);
MojRefCountedPtr<DeleteAccountCommand> command(new DeleteAccountCommand(*this, m_deleteAccountMsg, m_payload));
m_commandManager->RunCommand(command);
break;
}
case State_DeletingAccount:
{
break;
}
case State_DeletedAccount:
{
break;
}
default:
{
MojLogError(m_log, "CheckQueue in unknown state %d", m_state);
}
}
}
void ImapClient::RunCommandsInQueue()
{
m_commandManager->RunCommands();
}
void ImapClient::SyncAccount(SyncParams syncParams)
{
// TODO: debounce multiple sync requests
MojRefCountedPtr<SyncAccountCommand> command(new SyncAccountCommand(*this, syncParams));
m_commandManager->QueueCommand(command);
CheckQueue();
}
void ImapClient::CheckOutbox(SyncParams syncParams)
{
MojRefCountedPtr<CheckOutboxCommand> command(new CheckOutboxCommand(*this, syncParams));
m_commandManager->QueueCommand(command);
CheckQueue();
}
void ImapClient::CheckDrafts(const ActivityPtr& activity)
{
MojRefCountedPtr<CheckDraftsCommand> command(new CheckDraftsCommand(*this, activity));
m_commandManager->QueueCommand(command);
CheckQueue();
}
void ImapClient::UploadSentEmails(const ActivityPtr& activity)
{
MojObject folderId = GetAccount().GetSentFolderId();
if(!IsValidId(folderId)) {
folderId = GetAccount().GetInboxFolderId();
}
if(IsValidId(folderId)) {
GetOrCreateSession(folderId)->UpSyncSentEmails(folderId, activity);
}
}
void ImapClient::UploadDrafts(const ActivityPtr& activity)
{
MojObject folderId = GetAccount().GetDraftsFolderId();
if(!IsValidId(folderId)) {
folderId = GetAccount().GetDraftsFolderId();
}
if(IsValidId(folderId)) {
GetOrCreateSession(folderId)->UpSyncDrafts(folderId, activity);
}
}
void ImapClient::EnableAccount(MojServiceMessage* msg)
{
if(m_state == State_DisabledAccount) {
// Reset state in case we're re-enabling an account
SetState(State_NeedsAccountInfo);
}
// Run the EnableAccountCommand, which will create the default folders, call SMTP accountEnabled, and setup watches
MojRefCountedPtr<EnableAccountCommand> command(new EnableAccountCommand(*this, msg));
m_commandManager->QueueCommand(command, false);
CheckQueue();
}
/**
* Update account
*/
void ImapClient::UpdateAccount(const MojObject& accountId, const ActivityPtr& activity, bool credentialsChanged)
{
// Don't do anything if it is in progress disabling the account.
if(!DisableAccountInProgress())
{
fprintf(stderr, "Updating Account from ImapClient \n\n");
m_activity = activity;
MojRefCountedPtr<UpdateAccountCommand> command(new UpdateAccountCommand(*this, m_activity, credentialsChanged));
m_commandManager->QueueCommand(command, false);
CheckQueue();
}
}
/**
* Disable account is divided to two parts.
* 1. Close the session.
* 2. Remove folders and emails.
*/
void ImapClient::DisableAccount(MojServiceMessage* msg, MojObject& payload)
{
fprintf(stderr, "Disabling Account from ImapClient \n\n");
m_accountEnabledMsg = msg;
m_payload = payload;
if(!DisableAccountInProgress())
{
SetState(State_TerminatingSessions);
if(m_folderSessionMap.empty())
{
SetState(State_DisableAccount);
CheckQueue();
}
else
{
CleanupOneSession();
}
}
}
void ImapClient::CleanupOneSession()
{
map<const MojObject, MojRefCountedPtr<ImapSession> >::iterator it = m_folderSessionMap.begin();
((*it).second)->DisconnectSession();
}
/**
* Delete account
*/
void ImapClient::DeleteAccount(MojServiceMessage* msg, MojObject& payload)
{
fprintf(stderr, "Deleting Account from ImapClient \n\n");
m_deleteAccountMsg = msg;
m_payload = payload;
SetState(State_DeleteAccount);
CheckQueue();
}
// Queue sync folder command
void ImapClient::SyncFolder(const MojObject& folderId, SyncParams syncParams)
{
MojRefCountedPtr<SyncFolderCommand> command(new SyncFolderCommand(*this, folderId, syncParams));
m_commandManager->QueueCommand(command, false);
CheckQueue();
}
// Ask the session to sync a folder
void ImapClient::StartFolderSync(const MojObject& folderId, SyncParams syncParams)
{
MojLogDebug(m_log, "%s: preparing to sync folder", __PRETTY_FUNCTION__);
// FIXME: check for account being deleted
ImapSessionPtr session = GetOrCreateSession(folderId);
// Connection-related activities go to the session
session->AddActivities(syncParams.GetConnectionActivities());
// Ask the session to queue a sync command if one isn't already pending
session->SyncFolder(folderId, syncParams);
}
void ImapClient::DownloadPart(const MojObject& folderId, const MojObject& emailId, const MojObject& partId, const MojRefCountedPtr<DownloadListener>& listener)
{
MojLogTrace(m_log);
GetOrCreateSession(folderId)->DownloadPart(folderId, emailId, partId, listener, Command::HighPriority);
CheckQueue();
}
void ImapClient::SearchFolder(const MojObject& folderId, const MojRefCountedPtr<SearchRequest>& searchRequest)
{
GetOrCreateSession(folderId)->SearchFolder(folderId, searchRequest);
CheckQueue();
}
ImapClient::ImapSessionPtr ImapClient::GetSession(const MojObject& folderId)
{
if (m_folderSessionMap.find(folderId) != m_folderSessionMap.end()) {
return m_folderSessionMap[folderId];
}
return NULL;
}
ImapClient::ImapSessionPtr ImapClient::GetOrCreateSession(const MojObject& folderId)
{
if (m_folderSessionMap.find(folderId) == m_folderSessionMap.end()) {
ImapSessionPtr session = CreateSession(folderId);
// NOTE: assignment needs to be on a separate line so it doesn't create an
// uninitialized map entry before CreateSession is run.
m_folderSessionMap[folderId] = session;
}
return m_folderSessionMap[folderId];
}
/**
* Iterates over folderSessionMap, assigning accounts into sessions lacking one. This
* method should only be called by the setAccount(boost::shared_ptr<ImapAccount>& method);
*/
void ImapClient::HookUpFolderSessionAccounts() {
if(m_account.get() == NULL) {
throw MailException("account is null", __FILE__, __LINE__);
}
std::map< const MojObject, ImapSessionPtr >::iterator it;
for (it = m_folderSessionMap.begin(); it != m_folderSessionMap.end(); ++it) {
it->second->SetAccount(m_account);
}
}
ImapClient::SyncSessionPtr ImapClient::GetSyncSession(const MojObject& folderId)
{
if(m_syncSessions.find(folderId) != m_syncSessions.end()) {
const SyncSessionPtr& syncSession = m_syncSessions[folderId];
if(syncSession->IsRunning()) {
return syncSession;
}
}
return NULL;
}
ImapClient::SyncSessionPtr ImapClient::GetOrCreateSyncSession(const MojObject& folderId)
{
SyncSessionPtr& syncSession = m_syncSessions[folderId];
if(syncSession.get() == NULL) {
syncSession.reset(new SyncSession(*this, folderId));
}
return syncSession;
}
void ImapClient::StartSyncSession(const MojObject& folderId, const vector<ActivityPtr>& activities)
{
SyncSessionPtr syncSession = GetOrCreateSyncSession(folderId);
BOOST_FOREACH(const ActivityPtr& activity, activities) {
syncSession->AdoptActivity(activity);
}
syncSession->RequestStart();
}
void ImapClient::AddToSyncSession(const MojObject& folderId, ImapSyncSessionCommand* command)
{
assert(command);
SyncSessionPtr syncSession = GetOrCreateSyncSession(folderId);
// Need to set this before calling RegisterCommand
// since it may be ready to start the command immediately
command->SetSyncSession(syncSession);
syncSession->RegisterCommand(command);
}
void ImapClient::RequestSyncSession(const MojObject& folderId, ImapSyncSessionCommand* command, MojSignal<>::SlotRef slot)
{
assert(command);
SyncSessionPtr syncSession = GetOrCreateSyncSession(folderId);
// Need to set this before calling RegisterCommand
// since it may be ready to start the command immediately
command->SetSyncSession(syncSession);
syncSession->RegisterCommand(command, slot);
}
// TODO: Error handling. Probably remove the functions below
void ImapClient::CommandComplete(Command* command)
{
m_commandManager->CommandComplete(command);
// Check if we're idle; if so, report to dispatcher
if(m_busDispatcher)
m_busDispatcher->UpdateClientActive(this, IsActive());
}
void ImapClient::CommandFailure(ImapCommand* command)
{
MojLogTrace(m_log);
// m_failedCommandTotal++;
// m_successfulCommandTotal--;
CommandComplete(command);
}
void ImapClient::CommandFailure(ImapCommand* command, const std::exception& e)
{
MojLogTrace(m_log);
MojLogError(m_log, "command failure in %s, exception: %s", command->Describe().c_str(), e.what());
CommandFailure(command);
}
const char* ImapClient::GetStateName(ClientState state)
{
switch(state) {
case State_None: return "None";
case State_NeedsAccountInfo: return "NeedsAccountInfo";
case State_GettingAccount: return "GettingAccount";
case State_LoginFailed: return "LoginFailed";
case State_RunCommand: return "RunCommand";
case State_TerminatingSessions: return "TerminatingSessions";
case State_DisableAccount: return "DisableAccount";
case State_DisablingAccount: return "DisablingAccount";
case State_DisabledAccount: return "DisabledAccount";
case State_DeleteAccount: return "DeleteAccount";
case State_DeletingAccount: return "DeletingAccount";
case State_DeletedAccount: return "DeletedAccount";
}
return "unknown";
}
void ImapClient::Status(MojObject& status)
{
MojErr err;
MojObject sessions(MojObject::TypeArray);
if(!m_folderSessionMap.empty()) {
std::map<const MojObject, ImapSessionPtr >::const_iterator it;
for(it = m_folderSessionMap.begin(); it != m_folderSessionMap.end(); ++it) {
MojObject sessionStatus;
if(it->second.get()) {
it->second->Status(sessionStatus);
err = sessions.push(sessionStatus);
ErrorToException(err);
}
}
}
if(!m_syncSessions.empty()) {
MojObject syncSessions(MojObject::TypeArray);
std::map<const MojObject, SyncSessionPtr>::const_iterator it;
for(it = m_syncSessions.begin(); it != m_syncSessions.end(); ++it) {
MojObject syncSessionStatus;
it->second->Status(syncSessionStatus);
syncSessions.push(syncSessionStatus);
}
status.put("syncSessions", syncSessions);
}
err = status.put("accountId", m_accountId);
ErrorToException(err);
err = status.put("sessions", sessions);
ErrorToException(err);
err = status.putString("clientState", GetStateName(m_state));
ErrorToException(err);
if(m_account.get()) {
MojObject accountStatus;
err = accountStatus.putString("templateId", m_account->GetTemplateId().c_str());
ErrorToException(err);
const EmailAccount::AccountError& error = m_account->GetError();
if(error.errorCode != MailError::NONE) {
err = accountStatus.put("errorCode", error.errorCode);
ErrorToException(err);
err = accountStatus.putString("errorText", error.errorText.c_str());
ErrorToException(err);
}
const EmailAccount::RetryStatus& retry = m_account->GetRetry();
if(retry.GetInterval() > 0) {
MojObject retryStatus;
err = retryStatus.put("interval", retry.GetInterval());
ErrorToException(err);
err = accountStatus.put("retry", retryStatus);
ErrorToException(err);
}
MojObject folderIdStatus;
err = folderIdStatus.put("inboxFolderId", m_account->GetInboxFolderId());
ErrorToException(err);
err = folderIdStatus.put("draftsFolderId", m_account->GetDraftsFolderId());
ErrorToException(err);
err = folderIdStatus.put("sentFolderId", m_account->GetSentFolderId());
ErrorToException(err);
err = folderIdStatus.put("outboxFolderId", m_account->GetOutboxFolderId());
ErrorToException(err);
err = folderIdStatus.put("trashFolderId", m_account->GetTrashFolderId());
ErrorToException(err);
err = accountStatus.put("folders", folderIdStatus);
ErrorToException(err);
err = accountStatus.put("syncFrequencyMins", m_account->GetSyncFrequencyMins());
err = status.put("accountInfo", accountStatus);
ErrorToException(err);
}
if(m_commandManager->GetActiveCommandCount() > 0 || m_commandManager->GetPendingCommandCount() > 0) {
MojObject commandManagerStatus;
m_commandManager->Status(commandManagerStatus);
err = status.put("clientCommands", commandManagerStatus);
ErrorToException(err);
}
}
void ImapClient::SessionDisconnected(MojObject& folderId)
{
// Cleanup sync session (if any)
SyncSessionPtrMap::iterator it = m_syncSessions.find(folderId);
if(it != m_syncSessions.end()) {
SyncSessionPtr syncSession = it->second;
if(syncSession.get() && syncSession->IsFinished()) {
m_syncSessions.erase(it);
}
}
if(m_state == State_TerminatingSessions) {
// Remove the closed session.
if(m_folderSessionMap.find(folderId) != m_folderSessionMap.end()) {
m_pendingDeletefolderSessions.push_back(m_folderSessionMap[folderId]);
m_folderSessionMap.erase(folderId);
}
if(m_pendingDeletefolderSessions.size() == 1) {
m_cleanupSessionCallbackId = g_idle_add(&ImapClient::CleanupSessionsCallback, gpointer(this));
}
} else {
m_busDispatcher->UpdateClientActive(this, IsActive());
}
}
void ImapClient::HandleSessionCleanup()
{
m_cleanupSessionCallbackId = 0;
m_pendingDeletefolderSessions.clear();
if(m_state == State_TerminatingSessions) {
// Delete the account data when all sessions are closed.
if(m_folderSessionMap.empty())
{
SetState(State_DisableAccount);
CheckQueue();
}
else
{
CleanupOneSession();
}
}
}
gboolean ImapClient::CleanupSessionsCallback(gpointer data)
{
ImapClient* client = static_cast<ImapClient*>(data);
assert(data);
client->HandleSessionCleanup();
return false;
}
void ImapClient::DisabledAccount()
{
MojLogNotice(m_log, "account %s disabled successfully", AsJsonString(m_accountId).c_str());
SetState(State_DisabledAccount);
}
void ImapClient::SendSmtpAccountEnableRequest(bool enabling)
{
MojObject payload;
MojErr err;
err = payload.put("accountId", m_accountId);
ErrorToException(err);
err = payload.put("enabled", enabling);
ErrorToException(err);
// Cancel any existing outstanding request to avoid crashing
// FIXME move this into a command
m_smtpAccountEnabledSlot.cancel();
SendRequest(m_smtpAccountEnabledSlot, "com.palm.smtp", "accountEnabled", payload);
}
MojErr ImapClient::SmtpAccountEnabledResponse(MojObject& response, MojErr err)
{
if (err)
return m_accountEnabledMsg->replyError(err);
return m_accountEnabledMsg->replySuccess();
}
void ImapClient::DeletedAccount()
{
SetState(State_DeletedAccount);
}
bool ImapClient::DisableAccountInProgress()
{
return m_state == State_TerminatingSessions ||
m_state == State_DisableAccount ||
m_state == State_DisablingAccount ||
m_state == State_DisabledAccount ||
m_state == State_DeleteAccount ||
m_state == State_DeletingAccount ||
m_state == State_DeletedAccount;
}
void ImapClient::WakeupIdle(const MojObject& folderId)
{
if(m_folderSessionMap.find(folderId) != m_folderSessionMap.end()) {
m_folderSessionMap[folderId]->WakeupIdle();
}
}
void ImapClient::UpdateAccountStatus(const MailError::ErrorInfo& error)
{
// Set updated error on account
if(m_account.get()) {
m_account->SetError(error);
}
MojRefCountedPtr<UpdateAccountErrorCommand> command(new UpdateAccountErrorCommand(*this, error));
m_commandManager->RunCommand(command);
}
bool ImapClient::IsPushReady(const MojObject& folderId)
{
const ImapSessionPtr& session = this->GetSession(folderId);
if(session.get() && session->IsPushEnabled(folderId)) {
return true;
} else {
return false;
}
}
// Debug method for testing
void ImapClient::MagicWand(MojServiceMessage* msg, const MojObject& payload)
{
MojErr err;
MojString command;
err = payload.getRequired("command", command);
ErrorToException(err);
vector<ImapSessionPtr> sessions;
MojObject folderId;
if(payload.get("folderId", folderId)) {
ImapSessionPtr session = GetSession(folderId);
if(session.get())
sessions.push_back(session);
} else {
map<const MojObject, ImapSessionPtr>::iterator it;
for(it = m_folderSessionMap.begin(); it != m_folderSessionMap.end(); ++it) {
const ImapSessionPtr& session = it->second;
sessions.push_back(session);
}
}
if(command == "disconnect") {
BOOST_FOREACH(const ImapSessionPtr& session, sessions) {
fprintf(stderr, "disconnecting\n");
session->DisconnectSession();
}
msg->replySuccess();
} else {
msg->replyError(MojErrUnknown, "no such command");
}
}
void ImapClient::UpdateSessionActive(ImapSession* session, bool isActive)
{
if(m_busDispatcher)
m_busDispatcher->UpdateClientActive(this, IsActive());
}
bool ImapClient::IsActive()
{
// Don't shut down if any commands are running
if(m_commandManager->GetActiveCommandCount() > 0) {
return true;
}
// If the account is disabled, it's not active
switch(m_state) {
case State_DisabledAccount:
case State_DeletedAccount:
case State_LoginFailed:
return false;
default:
break;
}
// Don't shut down if we have commands queued
if(m_commandManager->GetPendingCommandCount() > 0) {
return true;
}
// Check if any sessions are active
map<const MojObject, ImapSessionPtr>::iterator it;
for(it = m_folderSessionMap.begin(); it != m_folderSessionMap.end(); ++it) {
const ImapSessionPtr& session = it->second;
if(session->IsActive()) {
return true;
}
}
return false;
}
NetworkStatusMonitor& ImapClient::GetNetworkStatusMonitor() const
{
return m_busDispatcher->GetNetworkStatusMonitor();
}
void ImapClient::CancelPendingCommands(ImapCommand::CancelType cancelType)
{
BOOST_FOREACH(const MojRefCountedPtr<Command>& pendingCommand, m_commandManager->GetPendingCommandIterators()) {
// Assume it's an ImapCommand
ImapCommand* imapCommand = static_cast<ImapCommand*>(pendingCommand.get());
bool cancelled = imapCommand->Cancel(cancelType);
if (cancelled) {
MojLogInfo(m_log, "cancelled command %s (%p)", imapCommand->Describe().c_str(), imapCommand);
}
}
}
| 27.469977
| 163
| 0.754508
|
webOS-ports
|
c03160e21ef08c9d499bda6616c6af83a39fef26
| 2,250
|
cpp
|
C++
|
Projects/Skylicht/Components/Source/ParticleSystem/Particles/CInterpolator.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 310
|
2019-11-25T04:14:11.000Z
|
2022-03-31T23:39:19.000Z
|
Projects/Skylicht/Components/Source/ParticleSystem/Particles/CInterpolator.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 79
|
2019-11-17T07:51:02.000Z
|
2022-03-22T08:49:41.000Z
|
Projects/Skylicht/Components/Source/ParticleSystem/Particles/CInterpolator.cpp
|
tsukoyumi/skylicht-engine
|
3b88d9718e87e552152633ef60e3f889869b71de
|
[
"MIT"
] | 24
|
2020-05-10T09:37:55.000Z
|
2022-03-05T13:19:31.000Z
|
/*
!@
MIT License
Copyright (c) 2020 Skylicht Technology CO., LTD
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.
This file is part of the "Skylicht Engine".
https://github.com/skylicht-lab/skylicht-engine
!#
*/
#include "pch.h"
#include "CInterpolator.h"
namespace Skylicht
{
namespace Particle
{
CInterpolator::CInterpolator()
{
}
CInterpolator::~CInterpolator()
{
}
float CInterpolator::interpolate(float x)
{
SInterpolatorEntry currentKey(x, 0.0f);
std::set<SInterpolatorEntry>::const_iterator nextIt = m_graph.upper_bound(currentKey);
if (nextIt == m_graph.end())
{
if (m_graph.empty())
{
// If the graph has no entry, sets the default value
return 0.0f;
}
else
{
// Else sets the value of the last entry
return (*(--nextIt)).y;
}
}
else if (nextIt == m_graph.begin())
{
// If the current X is lower than the first entry, sets the value to the first entry
return (*nextIt).y;
}
const SInterpolatorEntry& nextEntry = *nextIt;
const SInterpolatorEntry& previousEntry = *(--nextIt);
float y0 = previousEntry.y;
float y1 = nextEntry.y;
float ratioX = (x - previousEntry.x) / (nextEntry.x - previousEntry.x);
return y0 + ratioX * (y1 - y0);
}
}
}
| 29.220779
| 141
| 0.718222
|
tsukoyumi
|
c03301d9184673383e859046f98c628428f78c93
| 4,210
|
cpp
|
C++
|
common/my_capture.cpp
|
ThreeD-Tracker-FAB/3DTrackerFAB-main
|
e91660f9391feac02f5657a792771230450cf4f8
|
[
"MIT"
] | 2
|
2019-01-23T09:15:34.000Z
|
2019-04-18T08:45:33.000Z
|
common/my_capture.cpp
|
ThreeD-Tracker-FAB/3DTrackerFAB-main
|
e91660f9391feac02f5657a792771230450cf4f8
|
[
"MIT"
] | 1
|
2018-11-05T13:10:55.000Z
|
2019-11-18T13:34:50.000Z
|
common/my_capture.cpp
|
ThreeD-Tracker-FAB/3DTrackerFAB-main
|
e91660f9391feac02f5657a792771230450cf4f8
|
[
"MIT"
] | 2
|
2018-03-11T22:16:02.000Z
|
2019-09-05T15:36:14.000Z
|
#include "my_capture.h"
#include "my_capture_d400.h"
#include "my_capture_r200.h"
#include "my_capture_kinect1.h"
#include <iostream>
#include <pcl/filters/radius_outlier_removal.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/filters/crop_box.h>
#include <pcl/filters/voxel_grid.h>
std::shared_ptr<MyCapture> MyCapture::create(const std::string & model_name, StreamSetting ss)
{
if (model_name == "D400")
{
std::cout << "MyCapture::create - D400 is selected as the model" << std::endl;
return std::shared_ptr<MyCapture>(new MyCaptureD400(ss));
}
else if (model_name == "R200")
{
std::cout << "MyCapture::create - R200 is selected as the model" << std::endl;
return std::shared_ptr<MyCapture>(new MyCaptureR200(ss));
}
else if (model_name == "Kinect1")
{
std::cout << "MyCapture::create - Kinect1 is selected as the model" << std::endl;
return std::shared_ptr<MyCapture>(new MyCaptureKinect1());
}
std::cout << "MyCapture::create - Unknown camera model" << std::endl;
return std::shared_ptr<MyCapture>(nullptr);
}
void removeNoiseFromThresholdedPc(pcl::PointCloud<pcl::PointXYZRGB> & pc, int meanK, float thresh)
{
if (pc.size() == 0) return;
pcl::RadiusOutlierRemoval<pcl::PointXYZRGB> outrem;
outrem.setInputCloud(pc.makeShared());
outrem.setRadiusSearch(thresh);
outrem.setMinNeighborsInRadius(meanK);
outrem.filter(pc);
}
void preprocessFrame(MyMetadata & metadata, std::vector<pcl::PointCloud<pcl::PointXYZRGB>> & pc_input, pcl::PointCloud<pcl::PointXYZRGBNormal> & pc_merged, float gridsize, std::vector<bool> cam_enable)
{
int i;
std::vector<pcl::PointCloud<pcl::PointXYZRGBNormal>> pc_processed;
pc_processed.resize(pc_input.size());
for (i = 0; i < metadata.num_camera; i++)
{
if (cam_enable.size() == metadata.num_camera && !cam_enable[i]) continue;
// ROI filtering
pcl::CropBox<pcl::PointXYZRGB> cb;
cb.setMin(Eigen::Vector4f(metadata.roi.x[0], metadata.roi.y[0], metadata.roi.z[0], 1.0));
cb.setMax(Eigen::Vector4f(metadata.roi.x[1], metadata.roi.y[1], metadata.roi.z[1], 1.0));
cb.setInputCloud(pc_input[i].makeShared());
cb.filter(pc_input[i]);
// VoxelGrid filter
pcl::VoxelGrid<pcl::PointXYZRGB> vgf;
vgf.setLeafSize(gridsize, gridsize, gridsize);
vgf.setInputCloud(pc_input[i].makeShared());
vgf.filter(pc_input[i]);
// calculate camera position
pcl::PointCloud<pcl::PointXYZ> pc_camera_pos;
pcl::PointXYZ p_o(0.0, 0.0, 0.0);
pc_camera_pos.push_back(p_o);
pcl::transformPointCloud(pc_camera_pos, pc_camera_pos, metadata.pc_transforms[i]);
pcl::transformPointCloud(pc_camera_pos, pc_camera_pos, metadata.ref_cam_transform);
// calculate surface normal
pcl::PointCloud<pcl::PointXYZ> pc_input_xyz;
for (auto p : pc_input[i])
{
pcl::PointXYZ pxyz(p.x, p.y, p.z);
pc_input_xyz.push_back(pxyz);
}
pcl::PointCloud<pcl::Normal> pc_n;
pcl::NormalEstimationOMP<pcl::PointXYZ, pcl::Normal> ne;
ne.setInputCloud(pc_input_xyz.makeShared());
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>());
ne.setSearchMethod(tree);
ne.setRadiusSearch(gridsize*5.0);
ne.setViewPoint(pc_camera_pos[0].x, pc_camera_pos[0].y, pc_camera_pos[0].z);
ne.compute(pc_n);
pcl::PointCloud<pcl::PointXYZRGBNormal> pc_to_add;
pcl::concatenateFields(pc_input[i], pc_n, pc_to_add);
pc_merged += pc_to_add;
}
for (i = 0; i < metadata.num_camera; i++) pc_merged += pc_processed[i];
// VoxelGrid filter
pcl::VoxelGrid<pcl::PointXYZRGBNormal> vgf;
vgf.setLeafSize(gridsize, gridsize, gridsize);
vgf.setInputCloud(pc_merged.makeShared());
vgf.filter(pc_merged);
}
bool checkR200Connection()
{
rs::context rs_ctx;
if (rs_ctx.get_device_count() > 0) return true;
return false;
}
bool checkD400Connection()
{
rs2::context rs_ctx;
const std::string platform_camera_name = "Platform Camera";
for (auto&& dev : rs_ctx.query_devices())
{
if (dev.get_info(RS2_CAMERA_INFO_NAME) == platform_camera_name) continue;
else return true;
}
return false;
}
bool checkKinect1Connection()
{
int num_camera = 0;
::NuiGetSensorCount(&num_camera);
if (num_camera > 0) return true;
return false;
}
| 28.835616
| 201
| 0.723515
|
ThreeD-Tracker-FAB
|
c03d0241e201ed10088367487461c3ee237c9b49
| 16,857
|
cpp
|
C++
|
test/clang-tidy/modernize-use-emplace.cpp
|
Szelethus/clang-tools-extra
|
4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022
|
[
"Apache-2.0"
] | 171
|
2018-09-17T13:15:12.000Z
|
2022-03-18T03:47:04.000Z
|
test/clang-tidy/modernize-use-emplace.cpp
|
Szelethus/clang-tools-extra
|
4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022
|
[
"Apache-2.0"
] | 7
|
2018-10-05T04:54:18.000Z
|
2020-10-02T07:58:13.000Z
|
test/clang-tidy/modernize-use-emplace.cpp
|
Szelethus/clang-tools-extra
|
4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022
|
[
"Apache-2.0"
] | 35
|
2018-09-18T07:46:53.000Z
|
2022-03-27T07:59:48.000Z
|
// RUN: %check_clang_tidy %s modernize-use-emplace %t -- \
// RUN: -config="{CheckOptions: \
// RUN: [{key: modernize-use-emplace.ContainersWithPushBack, \
// RUN: value: '::std::vector; ::std::list; ::std::deque; llvm::LikeASmallVector'}, \
// RUN: {key: modernize-use-emplace.TupleTypes, \
// RUN: value: '::std::pair; std::tuple; ::test::Single'}, \
// RUN: {key: modernize-use-emplace.TupleMakeFunctions, \
// RUN: value: '::std::make_pair; ::std::make_tuple; ::test::MakeSingle'}] \
// RUN: }" -- -std=c++11
namespace std {
template <typename>
class initializer_list
{
public:
initializer_list() noexcept {}
};
template <typename T>
class vector {
public:
vector() = default;
vector(initializer_list<T>) {}
void push_back(const T &) {}
void push_back(T &&) {}
template <typename... Args>
void emplace_back(Args &&... args){};
~vector();
};
template <typename T>
class list {
public:
void push_back(const T &) {}
void push_back(T &&) {}
template <typename... Args>
void emplace_back(Args &&... args){};
~list();
};
template <typename T>
class deque {
public:
void push_back(const T &) {}
void push_back(T &&) {}
template <typename... Args>
void emplace_back(Args &&... args){};
~deque();
};
template <typename T> struct remove_reference { using type = T; };
template <typename T> struct remove_reference<T &> { using type = T; };
template <typename T> struct remove_reference<T &&> { using type = T; };
template <typename T1, typename T2> class pair {
public:
pair() = default;
pair(const pair &) = default;
pair(pair &&) = default;
pair(const T1 &, const T2 &) {}
pair(T1 &&, T2 &&) {}
template <typename U1, typename U2> pair(const pair<U1, U2> &){};
template <typename U1, typename U2> pair(pair<U1, U2> &&){};
};
template <typename T1, typename T2>
pair<typename remove_reference<T1>::type, typename remove_reference<T2>::type>
make_pair(T1 &&, T2 &&) {
return {};
};
template <typename... Ts> class tuple {
public:
tuple() = default;
tuple(const tuple &) = default;
tuple(tuple &&) = default;
tuple(const Ts &...) {}
tuple(Ts &&...) {}
template <typename... Us> tuple(const tuple<Us...> &){};
template <typename... Us> tuple(tuple<Us...> &&) {}
template <typename U1, typename U2> tuple(const pair<U1, U2> &) {
static_assert(sizeof...(Ts) == 2, "Wrong tuple size");
};
template <typename U1, typename U2> tuple(pair<U1, U2> &&) {
static_assert(sizeof...(Ts) == 2, "Wrong tuple size");
};
};
template <typename... Ts>
tuple<typename remove_reference<Ts>::type...> make_tuple(Ts &&...) {
return {};
}
template <typename T>
class unique_ptr {
public:
explicit unique_ptr(T *) {}
~unique_ptr();
};
} // namespace std
namespace llvm {
template <typename T>
class LikeASmallVector {
public:
void push_back(const T &) {}
void push_back(T &&) {}
template <typename... Args>
void emplace_back(Args &&... args){};
};
} // llvm
void testInts() {
std::vector<int> v;
v.push_back(42);
v.push_back(int(42));
v.push_back(int{42});
v.push_back(42.0);
int z;
v.push_back(z);
}
struct Something {
Something(int a, int b = 41) {}
Something() {}
void push_back(Something);
int getInt() { return 42; }
};
struct Convertable {
operator Something() { return Something{}; }
};
struct Zoz {
Zoz(Something, int = 42) {}
};
Zoz getZoz(Something s) { return Zoz(s); }
void test_Something() {
std::vector<Something> v;
v.push_back(Something(1, 2));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back instead of push_back [modernize-use-emplace]
// CHECK-FIXES: v.emplace_back(1, 2);
v.push_back(Something{1, 2});
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, 2);
v.push_back(Something());
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back();
v.push_back(Something{});
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back();
Something Different;
v.push_back(Something(Different.getInt(), 42));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(Different.getInt(), 42);
v.push_back(Different.getInt());
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(Different.getInt());
v.push_back(42);
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(42);
Something temporary(42, 42);
temporary.push_back(temporary);
v.push_back(temporary);
v.push_back(Convertable());
v.push_back(Convertable{});
Convertable s;
v.push_back(s);
}
template <typename ElemType>
void dependOnElem() {
std::vector<ElemType> v;
v.push_back(ElemType(42));
}
template <typename ContainerType>
void dependOnContainer() {
ContainerType v;
v.push_back(Something(42));
}
void callDependent() {
dependOnElem<Something>();
dependOnContainer<std::vector<Something>>();
}
void test2() {
std::vector<Zoz> v;
v.push_back(Zoz(Something(21, 37)));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(Something(21, 37));
v.push_back(Zoz(Something(21, 37), 42));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(Something(21, 37), 42);
v.push_back(getZoz(Something(1, 2)));
}
struct GetPair {
std::pair<int, long> getPair();
};
void testPair() {
std::vector<std::pair<int, int>> v;
v.push_back(std::pair<int, int>(1, 2));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, 2);
GetPair g;
v.push_back(g.getPair());
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(g.getPair());
std::vector<std::pair<Something, Zoz>> v2;
v2.push_back(std::pair<Something, Zoz>(Something(42, 42), Zoz(Something(21, 37))));
// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use emplace_back
// CHECK-FIXES: v2.emplace_back(Something(42, 42), Zoz(Something(21, 37)));
}
void testTuple() {
std::vector<std::tuple<bool, char, int>> v;
v.push_back(std::tuple<bool, char, int>(false, 'x', 1));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(false, 'x', 1);
v.push_back(std::tuple<bool, char, int>{false, 'y', 2});
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(false, 'y', 2);
v.push_back({true, 'z', 3});
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(true, 'z', 3);
std::vector<std::tuple<int, bool>> x;
x.push_back(std::make_pair(1, false));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: x.emplace_back(1, false);
x.push_back(std::make_pair(2LL, 1));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: x.emplace_back(2LL, 1);
}
struct Base {
Base(int, int *, int = 42);
};
struct Derived : Base {
Derived(int *, Something) : Base(42, nullptr) {}
};
void testDerived() {
std::vector<Base> v;
v.push_back(Derived(nullptr, Something{}));
}
void testNewExpr() {
std::vector<Derived> v;
v.push_back(Derived(new int, Something{}));
}
void testSpaces() {
std::vector<Something> v;
// clang-format off
v.push_back(Something(1, //arg1
2 // arg2
) // Something
);
// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, //arg1
// CHECK-FIXES: 2 // arg2
// CHECK-FIXES: // Something
// CHECK-FIXES: );
v.push_back( Something (1, 2) );
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, 2 );
v.push_back( Something {1, 2} );
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, 2 );
v.push_back( Something {} );
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back( );
v.push_back(
Something(1, 2) );
// CHECK-MESSAGES: :[[@LINE-2]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, 2 );
std::vector<Base> v2;
v2.push_back(
Base(42, nullptr));
// CHECK-MESSAGES: :[[@LINE-2]]:6: warning: use emplace_back
// CHECK-FIXES: v2.emplace_back(42, nullptr);
// clang-format on
}
void testPointers() {
std::vector<int *> v;
v.push_back(new int(5));
std::vector<std::unique_ptr<int>> v2;
v2.push_back(std::unique_ptr<int>(new int(42)));
// This call can't be replaced with emplace_back.
// If emplacement will fail (not enough memory to add to vector)
// we will have leak of int because unique_ptr won't be constructed
// (and destructed) as in push_back case.
auto *ptr = new int;
v2.push_back(std::unique_ptr<int>(ptr));
// Same here
}
void testMakePair() {
std::vector<std::pair<int, int>> v;
v.push_back(std::make_pair(1, 2));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, 2);
v.push_back(std::make_pair(42LL, 13));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(42LL, 13);
v.push_back(std::make_pair<char, char>(0, 3));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(std::make_pair<char, char>(0, 3));
//
// Even though the call above could be turned into v.emplace_back(0, 3),
// we don't eliminate the make_pair call here, because of the explicit
// template parameters provided. make_pair's arguments can be convertible
// to its explicitly provided template parameter, but not to the pair's
// element type. The examples below illustrate the problem.
struct D {
D(...) {}
operator char() const { return 0; }
};
v.push_back(std::make_pair<D, int>(Something(), 2));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(std::make_pair<D, int>(Something(), 2));
struct X {
X(std::pair<int, int>) {}
};
std::vector<X> x;
x.push_back(std::make_pair(1, 2));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: x.emplace_back(std::make_pair(1, 2));
// make_pair cannot be removed here, as X is not constructible with two ints.
struct Y {
Y(std::pair<int, int>&&) {}
};
std::vector<Y> y;
y.push_back(std::make_pair(2, 3));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: y.emplace_back(std::make_pair(2, 3));
// make_pair cannot be removed here, as Y is not constructible with two ints.
}
void testMakeTuple() {
std::vector<std::tuple<int, bool, char>> v;
v.push_back(std::make_tuple(1, true, 'v'));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1, true, 'v');
v.push_back(std::make_tuple(2ULL, 1, 0));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(2ULL, 1, 0);
v.push_back(std::make_tuple<long long, int, int>(3LL, 1, 0));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(std::make_tuple<long long, int, int>(3LL, 1, 0));
// make_tuple is not removed when there are explicit template
// arguments provided.
}
namespace test {
template <typename T> struct Single {
Single() = default;
Single(const Single &) = default;
Single(Single &&) = default;
Single(const T &) {}
Single(T &&) {}
template <typename U> Single(const Single<U> &) {}
template <typename U> Single(Single<U> &&) {}
template <typename U> Single(const std::tuple<U> &) {}
template <typename U> Single(std::tuple<U> &&) {}
};
template <typename T>
Single<typename std::remove_reference<T>::type> MakeSingle(T &&) {
return {};
}
} // namespace test
void testOtherTuples() {
std::vector<test::Single<int>> v;
v.push_back(test::Single<int>(1));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(1);
v.push_back({2});
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(2);
v.push_back(test::MakeSingle(3));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(3);
v.push_back(test::MakeSingle<long long>(4));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(test::MakeSingle<long long>(4));
// We don't remove make functions with explicit template parameters.
v.push_back(test::MakeSingle(5LL));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(5LL);
v.push_back(std::make_tuple(6));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(6);
v.push_back(std::make_tuple(7LL));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(7LL);
}
void testOtherContainers() {
std::list<Something> l;
l.push_back(Something(42, 41));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: l.emplace_back(42, 41);
std::deque<Something> d;
d.push_back(Something(42));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: d.emplace_back(42);
llvm::LikeASmallVector<Something> ls;
ls.push_back(Something(42));
// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use emplace_back
// CHECK-FIXES: ls.emplace_back(42);
}
class IntWrapper {
public:
IntWrapper(int x) : value(x) {}
IntWrapper operator+(const IntWrapper other) const {
return IntWrapper(value + other.value);
}
private:
int value;
};
void testMultipleOpsInPushBack() {
std::vector<IntWrapper> v;
v.push_back(IntWrapper(42) + IntWrapper(27));
}
// Macro tests.
#define PUSH_BACK_WHOLE(c, x) c.push_back(x)
#define PUSH_BACK_NAME push_back
#define PUSH_BACK_ARG(x) (x)
#define SOME_OBJ Something(10)
#define MILLION 3
#define SOME_WEIRD_PUSH(v) v.push_back(Something(
#define OPEN (
#define CLOSE )
void macroTest() {
std::vector<Something> v;
Something s;
PUSH_BACK_WHOLE(v, Something(5, 6));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use emplace_back
v.PUSH_BACK_NAME(Something(5));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
v.push_back PUSH_BACK_ARG(Something(5, 6));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
v.push_back(SOME_OBJ);
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
v.push_back(Something(MILLION));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(MILLION);
// clang-format off
v.push_back( Something OPEN 3 CLOSE );
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// clang-format on
PUSH_BACK_WHOLE(s, Something(1));
}
struct A {
int value1, value2;
};
struct B {
B(A) {}
};
struct C {
int value1, value2, value3;
};
void testAggregation() {
// This should not be noticed or fixed; after the correction, the code won't
// compile.
std::vector<A> v;
v.push_back(A({1, 2}));
std::vector<B> vb;
vb.push_back(B({10, 42}));
}
struct Bitfield {
unsigned bitfield : 1;
unsigned notBitfield;
};
void testBitfields() {
std::vector<Something> v;
Bitfield b;
v.push_back(Something(42, b.bitfield));
v.push_back(Something(b.bitfield));
v.push_back(Something(42, b.notBitfield));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(42, b.notBitfield);
int var;
v.push_back(Something(42, var));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(42, var);
}
class PrivateCtor {
PrivateCtor(int z);
public:
void doStuff() {
std::vector<PrivateCtor> v;
// This should not change it because emplace back doesn't have permission.
// Check currently doesn't support friend declarations because pretty much
// nobody would want to be friend with std::vector :(.
v.push_back(PrivateCtor(42));
}
};
struct WithDtor {
WithDtor(int) {}
~WithDtor();
};
void testWithDtor() {
std::vector<WithDtor> v;
v.push_back(WithDtor(42));
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back
// CHECK-FIXES: v.emplace_back(42);
}
void testInitializerList() {
std::vector<std::vector<int>> v;
v.push_back(std::vector<int>({1}));
// Test against the bug reported in PR32896.
v.push_back({{2}});
using PairIntVector = std::pair<int, std::vector<int>>;
std::vector<PairIntVector> x;
x.push_back(PairIntVector(3, {4}));
x.push_back({5, {6}});
}
| 27.725329
| 107
| 0.644599
|
Szelethus
|
c03f765978b0e3bde7d4ec612271646aa28e3f9f
| 11,065
|
hpp
|
C++
|
RetroSnake/RetroSnake/GameMap.hpp
|
VoidYTMain/RetroSnake
|
f3080ad424dddbda5440d5205597081cf5b9e93b
|
[
"MIT"
] | 2
|
2019-01-18T07:37:54.000Z
|
2019-01-19T10:57:16.000Z
|
RetroSnake/RetroSnake/GameMap.hpp
|
Vyterm/RetroSnake
|
f3080ad424dddbda5440d5205597081cf5b9e93b
|
[
"MIT"
] | null | null | null |
RetroSnake/RetroSnake/GameMap.hpp
|
Vyterm/RetroSnake
|
f3080ad424dddbda5440d5205597081cf5b9e93b
|
[
"MIT"
] | null | null | null |
#ifndef GAME_MAP_HPP
#define GAME_MAP_HPP
#include "GameModel.hpp"
#include "GameMapItem.hpp"
#include "winapi.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
using std::string;
template <int Width, int Height>
class LayerTemplate
{
protected:
MapItem m_items[Width][Height];
public:
const MapItem& operator[](Vector2 position) const { return m_items[position.x][position.y]; }
MapItem& operator[](Vector2 position) { return m_items[position.x][position.y]; }
const MapItem& Index(int x, int y) const { return m_items[x][y]; }
MapItem& Index(int x, int y) { return m_items[x][y]; }
};
class PlayerCtrl;
class SnakePlayerCtrl;
class TankPlayerCtrl;
template <size_t Width, size_t Height>
class MapTemplate
{
private:
#pragma region Fields
MapItem m_items[Width][Height];
MapItem m_staticItems[Width][Height];
bool &m_isUpdateUI;
std::vector<PlayerCtrl*> m_players;
size_t m_activePlayerCount = 0;
Vector2 m_position;
MapItem m_zCacheItems[Width][Height];
GameMapModel m_model;
#pragma endregion
#pragma region Load Map Model
void LoadStaticCell(const GameMapModel &model, int ci, int ri)
{
Vector2 position = { ci, ri };
m_staticItems[ci][ri].Set(E_CellType::None, E_SubType::SubType0, DEFAULT_COLOR);
m_items[ci][ri].Set(E_CellType::None, E_SubType::SubType0, DEFAULT_COLOR);
switch (model.GetType(position))
{
case E_StaticCellType::OpenSpace:
m_staticItems[ci][ri].Set(E_CellType::None, E_SubType::SubType0, DEFAULT_COLOR);
break;
case E_StaticCellType::JebelLand:
m_staticItems[ci][ri].Set(E_CellType::Land, E_SubType::SubType0, DEFAULT_COLOR);
break;
case E_StaticCellType::GrassLand:
m_staticItems[ci][ri].Set(E_CellType::Land, E_SubType::SubType1, { DEFAULT_BACK_COLOR, SubTypeColors[1] });
break;
case E_StaticCellType::MagmaLand:
m_staticItems[ci][ri].Set(E_CellType::Land, E_SubType::SubType3, { DEFAULT_BACK_COLOR, SubTypeColors[3] });
break;
case E_StaticCellType::FrostLand:
m_staticItems[ci][ri].Set(E_CellType::Land, E_SubType::SubType4, { DEFAULT_BACK_COLOR, SubTypeColors[4] });
break;
case E_StaticCellType::GermPoint:
m_items[ci][ri].Set(E_CellType::Head, E_SubType::SubType0, { model.GetColor(position), DEFAULT_BACK_COLOR });
break;
// Some bug need be fixed
//case E_StaticCellType::JumpPoint:
// m_staticItems[ci][ri].Set(E_CellType::Jump, E_SubType::SubType0, { model.GetColor(position), DEFAULT_BACK_COLOR });
// break;
}
}
void LoadPlayerCell(const GameMapModel &model)
{
m_activePlayerCount = model.PlayerCount();
for (size_t i = 0; i < m_activePlayerCount; ++i)
m_players[i]->Reset(model.GetPlayer(i));
if (m_activePlayerCount == 1)
m_players[0]->SetEnemy(*m_players[0]);
else
{
m_players[0]->SetEnemy(*m_players[1]);
m_players[1]->SetEnemy(*m_players[0]);
}
}
void LoadJumpCell(const GameMapModel &model)
{
for (auto &jpm : model.GetJumpPoints())
{
m_items[jpm.src.x][jpm.src.y].Set(E_CellType::Jump, jpm.color);
m_items[jpm.src.x][jpm.src.y].jumpPoint = jpm.dest;
m_items[jpm.dest.x][jpm.dest.y].Set(E_CellType::Jump, jpm.color);
m_items[jpm.dest.x][jpm.dest.y].jumpPoint = jpm.src;
}
}
#pragma endregion
public:
#pragma region Construct & Destruct
MapTemplate(bool &updateUI) : m_isUpdateUI(updateUI)
{
m_players.push_back(new SnakePlayerCtrl("玩家一", *this, updateUI, E_4BitColor::LCyan, 'W', 'A', 'S', 'D'));
m_players.push_back(new SnakePlayerCtrl("玩家二", *this, updateUI, E_4BitColor::LWhite, VK_UP, VK_LEFT, VK_DOWN, VK_RIGHT));
//m_players.push_back(new TankPlayerCtrl("玩家一", *this, updateUI, E_4BitColor::LCyan, 'W', 'A', 'S', 'D'));
//m_players.push_back(new TankPlayerCtrl("玩家二", *this, updateUI, E_4BitColor::LWhite, VK_UP, VK_LEFT, VK_DOWN, VK_RIGHT));
for (auto &player : m_players)
player->Clear();
m_position = { 0, 0 };
}
~MapTemplate()
{
for (auto &pPlayer : m_players)
delete pPlayer;
}
void SetModel(const GameMapModel &model)
{
m_model = model;
}
#pragma endregion
#pragma region Load Map Model Interfaces
void LoadModel(const GameMapModel &model)
{
LoadStaticModel(model);
LoadPlayerCell(model);
// Some bug need be fixed
//LoadJumpCell(model);
GenerateRandomFood(model.get_FoodCount());
}
void LoadStaticModel(const GameMapModel &model)
{
for (int ci = 0; ci < Width; ++ci)
for (int ri = 0; ri < Height; ++ri)
LoadStaticCell(model, ci, ri);
LoadJumpCell(model);
}
#pragma endregion
#pragma region Reuse Methods
void Reset()
{
srand((unsigned)time(nullptr));
ClearCell();
LoadModel(m_model);
SetColor(DEFAULT_COLOR);
system("cls");
Draw();
}
PlayerCtrl& GetPlayer(int index) { return m_activePlayerCount == 1 || index == 0 ? *m_players[0] : *m_players[1]; }
PlayerCtrl* CheckOver()
{
PlayerCtrl *winer = nullptr;
if (m_activePlayerCount == 2)
winer = !m_players[0]->get_Alive() ? m_players[1] : !m_players[1]->get_Alive() ? m_players[0] : nullptr;
else
winer = !m_players[0]->get_Alive() ? m_players[0] : nullptr;
if (nullptr == winer) return winer;
m_players[0]->Clear();
m_players[1]->Clear();
vyt::timer::get_instance().HandleClock();
return winer;
}
#pragma endregion
#pragma region Render Methods
MapItem MixCell(int x, int y)
{
MapItem upperLayer = m_items[x][y] == E_CellType::None ? m_staticItems[x][y] : m_items[x][y];
if (m_staticItems[x][y] != E_CellType::Land) return upperLayer;
if (m_staticItems[x][y] == E_SubType::SubType0)
upperLayer.Set(DEFAULT_COLOR);
if (upperLayer.type != E_CellType::Body && upperLayer.type != E_CellType::Head) return upperLayer;
else if (m_staticItems[x][y] == E_SubType::SubType1)
{
auto type = upperLayer.type == E_CellType::Head ? E_CellType::Head : E_CellType::Land;
auto subType = upperLayer.type == E_CellType::Head ? E_SubType::SubType0 : E_SubType::SubType1;
ConsoleColor color = { upperLayer.color.fore, m_staticItems[x][y].color.back };
upperLayer.Set(type, subType, color);
}
else if (m_staticItems[x][y] == E_SubType::SubType4)
{
auto type = upperLayer.type;
auto subType = upperLayer.subType;
ConsoleColor color = { upperLayer.color.fore, m_staticItems[x][y].color.back };
upperLayer.Set(type, subType, color);
}
return upperLayer;
}
static ConsoleColor ToSubColor(E_SubType subType)
{
return { SubTypeColors[int(subType)], DEFAULT_BACK_COLOR };
}
static string ToString(const MapItem &item)
{
static const string images[] = { " ", "■", "☆", "◎", "¤", "※", "〓" };
//static const string images[] = { " ", "〓", "❀", "◎", "¤", "※" };
if (item.type == E_CellType::Land)
{
switch (item.subType)
{
case E_SubType::SubType1:
return "≡";
case E_SubType::SubType3:
return "≈";
case E_SubType::SubType4:
return "〓";
}
}
return images[int(item.type)];
}
void DrawCell(int x, int y, bool isForce)
{
auto item = MixCell(x, y);
if (!isForce && m_zCacheItems[x][y] == item)
return;
m_zCacheItems[x][y] = item;
DrawCell(m_position.x + x, m_position.y + y, m_zCacheItems[x][y]);
}
static void DrawCell(int x, int y, const MapItem &item)
{
DrawCell(x, y, item.color, ToString(item));
}
static void DrawCell(int x, int y, ConsoleColor color, const string &text)
{
SetPosition(x, y);
SetColor(color);
cout << text;
}
void Draw(bool isForce = false)
{
for (int ri = 0; ri < Height; ++ri)
for (int ci = 0; ci < Width; ++ci)
DrawCell(ci, ri, isForce);
}
void ClearCell()
{
for (int ri = 0; ri < Height; ++ri)
for (int ci = 0; ci < Width; ++ci)
m_zCacheItems[ci][ri] = m_items[ci][ri] = MapItem();
}
#pragma endregion
#pragma region Create Methods
bool SearchEmptyPosition(Vector2 &emptyPoint)
{
std::vector<Vector2> emptyPoints;
for (int ri = 0; ri < GAME_HEIGHT; ++ri)
for (int ci = 0; ci < GAME_WIDTH; ++ci)
if (E_CellType::None == m_staticItems[ci][ri] && E_CellType::None == m_items[ci][ri])
emptyPoints.push_back({ ci,ri });
if (0 == emptyPoints.size())
return false;
emptyPoint = emptyPoints[rand() % emptyPoints.size()];
return true;
}
bool GenerateRandomFood()
{
Vector2 emptyPoint;
if (!SearchEmptyPosition(emptyPoint))
return false;
auto randomType = (unsigned)rand() % 100;
//E_SubType subType = randomType < m_model.FoodWeight(E_FoodType::NormalEffect) ? E_SubType::SubType0 :
// randomType < m_model.FoodWeight(E_FoodType::AppendLength) ? E_SubType::SubType1 :
// randomType < m_model.FoodWeight(E_FoodType::RemoveLength) ? E_SubType::SubType2 :
// randomType < m_model.FoodWeight(E_FoodType::Acceleration) ? E_SubType::SubType3 :
// randomType < m_model.FoodWeight(E_FoodType::Deceleration) ? E_SubType::SubType4 :
// randomType < m_model.FoodWeight(E_FoodType::Reverse ) ? E_SubType::SubType5 :
// randomType < m_model.FoodWeight(E_FoodType::BuffStrong ) ? E_SubType::SubType6 : E_SubType::SubType7;
E_SubType subType = randomType < 0 ? E_SubType::SubType0 :
randomType < 20 ? E_SubType::SubType1 :
randomType < 30 ? E_SubType::SubType2 :
randomType < 40 ? E_SubType::SubType3 :
randomType < 60 ? E_SubType::SubType4 :
randomType < 65 ? E_SubType::SubType5 :
randomType < 95 ? E_SubType::SubType6 : E_SubType::SubType7;
m_items[emptyPoint.x][emptyPoint.y].Set(E_CellType::Food, subType, { SubTypeColors[int(subType)] ,DEFAULT_BACK_COLOR });
return true;
}
bool GenerateRandomFood(size_t count)
{
for (size_t i = 0; i < count; ++i)
if (!GenerateRandomFood())
return false;
return true;
}
#pragma endregion
#pragma region CellType Methods
const MapItem& operator[](Vector2 position) const { return m_items[position.x][position.y]; }
MapItem& operator[](Vector2 position) { return m_items[position.x][position.y]; }
const MapItem& Index(int x, int y) const { return m_items[x][y]; }
MapItem& Index(int x, int y) { return m_items[x][y]; }
const MapItem& GetItem(Vector2 position) { return E_CellType::None == m_items[position.x][position.y] ? m_staticItems[position.x][position.y] : m_items[position.x][position.y]; }
const MapItem& GetStaticItem(Vector2 position) { return m_staticItems[position.x][position.y]; }
bool MoveAble(int x, int y)
{
auto item = GetItem({ x, y });
return E_CellType::None == item.type || E_CellType::Food == item.type || E_CellType::Jump == item.type ||
(E_CellType::Land == item.type && E_SubType::SubType1 == item.subType) ||
//(E_CellType::Land == item.type && E_SubType::SubType4 == item.subType) ||
(E_CellType::Land == item.type && E_SubType::SubType4 == item.subType);
}
bool IsBlocked(const Vector2 &position)
{
bool isBlocked = true;
isBlocked &= !MoveAble(position.x + 1, position.y);
isBlocked &= !MoveAble(position.x - 1, position.y);
isBlocked &= !MoveAble(position.x, position.y + 1);
isBlocked &= !MoveAble(position.x, position.y - 1);
return isBlocked;
}
#pragma endregion
};
typedef MapTemplate<GAME_WIDTH + MAZE_WIDTH, GAME_HEIGHT> GameMap;
#endif
| 30.65097
| 179
| 0.690285
|
VoidYTMain
|
c047457e5014c0962a53d506e38c46529f6f7530
| 14,372
|
cpp
|
C++
|
arangod/Aql/WindowExecutor.cpp
|
lo-ca/arangodb
|
92a2cdda102279fc18ba238efafde118355cb000
|
[
"Apache-2.0"
] | 12,278
|
2015-01-29T17:11:33.000Z
|
2022-03-31T21:12:00.000Z
|
arangod/Aql/WindowExecutor.cpp
|
solisoft/arangodb
|
ebb11f901fdcac72ca298f7f329427c7ec51b157
|
[
"Apache-2.0"
] | 9,469
|
2015-01-30T05:33:07.000Z
|
2022-03-31T16:17:21.000Z
|
arangod/Aql/WindowExecutor.cpp
|
solisoft/arangodb
|
ebb11f901fdcac72ca298f7f329427c7ec51b157
|
[
"Apache-2.0"
] | 892
|
2015-01-29T16:26:19.000Z
|
2022-03-20T07:44:30.000Z
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Simon Grätzer
////////////////////////////////////////////////////////////////////////////////
#include "WindowExecutor.h"
#include "Aql/Aggregator.h"
#include "Aql/AqlCall.h"
#include "Aql/AqlValue.h"
#include "Aql/ExecutionNode.h"
#include "Aql/InputAqlItemRow.h"
#include "Aql/OutputAqlItemRow.h"
#include "Aql/RegisterInfos.h"
#include "Aql/RegisterPlan.h"
#include "Aql/SingleRowFetcher.h"
#include <utility>
using namespace arangodb;
using namespace arangodb::aql;
namespace {
static const AqlValue EmptyValue;
}
WindowExecutorInfos::WindowExecutorInfos(WindowBounds const& bounds, RegisterId rangeRegister,
std::vector<std::string>&& aggregateTypes,
std::vector<std::pair<RegisterId, RegisterId>>&& aggregateRegisters,
QueryWarnings& w, velocypack::Options const* opts)
: _bounds(bounds),
_rangeRegister(rangeRegister),
_aggregateTypes(std::move(aggregateTypes)),
_aggregateRegisters(std::move(aggregateRegisters)),
_warnings(w),
_vpackOptions(opts) {
TRI_ASSERT(!_aggregateRegisters.empty());
}
WindowBounds const& WindowExecutorInfos::bounds() const { return _bounds; }
RegisterId WindowExecutorInfos::rangeRegister() const { return _rangeRegister; }
std::vector<std::pair<RegisterId, RegisterId>> WindowExecutorInfos::getAggregatedRegisters() const {
return _aggregateRegisters;
}
std::vector<std::string> WindowExecutorInfos::getAggregateTypes() const {
return _aggregateTypes;
}
QueryWarnings& WindowExecutorInfos::warnings() const { return _warnings; }
velocypack::Options const* WindowExecutorInfos::getVPackOptions() const {
return _vpackOptions;
}
BaseWindowExecutor::AggregatorList BaseWindowExecutor::createAggregators(
WindowExecutor::Infos const& infos) {
AggregatorList aggregators;
TRI_ASSERT(!infos.getAggregateTypes().empty());
if (infos.getAggregateTypes().empty()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "no aggregators found in WindowExecutor");
}
// we do have aggregate registers. create them as empty AqlValues
aggregators.reserve(infos.getAggregatedRegisters().size());
// initialize aggregators
for (auto const& r : infos.getAggregateTypes()) {
auto& factory = Aggregator::factoryFromTypeString(r);
aggregators.emplace_back(factory(infos.getVPackOptions()));
}
return aggregators;
}
BaseWindowExecutor::BaseWindowExecutor(Infos& infos)
: _infos(infos), _aggregators(createAggregators(infos)) {}
BaseWindowExecutor::~BaseWindowExecutor() = default;
const BaseWindowExecutor::Infos& BaseWindowExecutor::infos() const noexcept {
return _infos;
}
void BaseWindowExecutor::applyAggregators(InputAqlItemRow& input) {
TRI_ASSERT(_aggregators.size() == _infos.getAggregatedRegisters().size());
size_t j = 0;
for (auto const& r : _infos.getAggregatedRegisters()) {
if (r.second.value() == RegisterId::maxRegisterId) { // e.g. LENGTH / COUNT
_aggregators[j]->reduce(::EmptyValue);
} else {
_aggregators[j]->reduce(input.getValue(/*inRegister*/ r.second));
}
++j;
}
}
void BaseWindowExecutor::resetAggregators() {
for (auto& agg : _aggregators) {
agg->reset();
}
}
// produce output row, reset aggregator
void BaseWindowExecutor::produceOutputRow(InputAqlItemRow& input,
OutputAqlItemRow& output, bool reset) {
size_t j = 0;
auto const& registers = _infos.getAggregatedRegisters();
for (std::unique_ptr<Aggregator> const& agg : _aggregators) {
AqlValue r = agg->get();
AqlValueGuard guard{r, /*destroy*/ true};
output.moveValueInto(/*outRegister*/ registers[j++].first, input, guard);
if (reset) {
agg->reset();
}
}
output.advanceRow();
}
void BaseWindowExecutor::produceInvalidOutputRow(InputAqlItemRow& input, OutputAqlItemRow& output) {
VPackSlice const nullSlice = VPackSlice::nullSlice();
for (auto const& regId : _infos.getAggregatedRegisters()) {
output.moveValueInto(/*outRegister*/ regId.first, input, nullSlice);
}
output.advanceRow();
}
// -------------- AccuWindowExecutor --------------
AccuWindowExecutor::AccuWindowExecutor(Fetcher& fetcher, Infos& infos)
: BaseWindowExecutor(infos) {
TRI_ASSERT(_infos.bounds().unboundedPreceding());
}
AccuWindowExecutor::~AccuWindowExecutor() = default;
void AccuWindowExecutor::initializeCursor() {
resetAggregators();
}
std::tuple<ExecutorState, NoStats, AqlCall> AccuWindowExecutor::produceRows(
AqlItemBlockInputRange& inputRange, OutputAqlItemRow& output) {
// This block is passhthrough.
static_assert(Properties::allowsBlockPassthrough == BlockPassthrough::Enable,
"For WINDOW with passthrough to work, there must be "
"exactly enough space for all input in the output.");
// simple optimization for culmulative SUM and the likes
while (inputRange.hasDataRow()) {
// So there will always be enough place for all inputRows within
// the output.
TRI_ASSERT(!output.isFull());
auto [state, input] = inputRange.nextDataRow(AqlItemBlockInputRange::HasDataRow{});
TRI_ASSERT(input.isInitialized());
applyAggregators(input);
produceOutputRow(input, output, /*reset*/ false);
}
// Just fetch everything from above, allow overfetching
AqlCall upstreamCall{};
return {inputRange.upstreamState(), NoStats{}, upstreamCall};
}
/**
* @brief Skip Rows
* We need to consume all rows from the inputRange
*
* @param inputRange Data from input
* @param call Call from client
* @return std::tuple<ExecutorState, NoStats, size_t, AqlCall>
*/
auto AccuWindowExecutor::skipRowsRange(AqlItemBlockInputRange& inputRange, AqlCall& call)
-> std::tuple<ExecutorState, NoStats, size_t, AqlCall> {
// we do not keep any state
AqlCall upstreamCall{};
return {inputRange.upstreamState(), NoStats{}, call.getSkipCount(), upstreamCall};
}
[[nodiscard]] auto AccuWindowExecutor::expectedNumberOfRowsNew(
AqlItemBlockInputRange const& input, AqlCall const& call) const noexcept -> size_t {
if (input.finalState() == ExecutorState::DONE) {
// For every input row we produce a new row.
auto estOnInput = input.countDataRows();
return std::min(call.getLimit(), estOnInput);
}
// We do not know how many more rows will be returned from upstream.
// So we can only overestimate
return call.getLimit();
}
// -------------- WindowExecutor --------------
WindowExecutor::WindowExecutor(Fetcher& fetcher, Infos& infos)
: BaseWindowExecutor(infos) {}
WindowExecutor::~WindowExecutor() = default;
ExecutorState WindowExecutor::consumeInputRange(AqlItemBlockInputRange& inputRange) {
const RegisterId rangeRegister = _infos.rangeRegister();
QueryWarnings& qc = _infos.warnings();
WindowBounds const& b = _infos.bounds();
while (inputRange.hasDataRow()) {
auto [state, input] = inputRange.nextDataRow(AqlItemBlockInputRange::HasDataRow{});
TRI_ASSERT(input.isInitialized());
if (rangeRegister.isValid()) {
AqlValue val = input.getValue(rangeRegister);
_windowRows.emplace_back(b.calcRow(val, qc));
}
_rows.emplace_back(std::move(input));
if (state == ExecutorState::DONE) {
return state;
}
}
return inputRange.finalState();
}
void WindowExecutor::trimBounds() {
TRI_ASSERT(!_rows.empty());
if (_infos.rangeRegister() == RegisterPlan::MaxRegisterId) {
const size_t numPreceding = size_t(_infos.bounds().numPrecedingRows());
// trim out of bound rows, _currentIdx may eq _rows.size()
if (_currentIdx > numPreceding) {
auto toRemove = _currentIdx - numPreceding;
// remove elements [0, numPreceding), excluding elem at idx numPreceding
_rows.erase(_rows.begin(), _rows.begin() + decltype(_rows)::difference_type(toRemove));
_currentIdx -= toRemove;
}
TRI_ASSERT(_currentIdx <= numPreceding || _rows.empty());
return;
}
TRI_ASSERT(_rows.size() == _windowRows.size());
// trim out of bound rows
while (_currentIdx < _rows.size() &&
!_windowRows[_currentIdx].valid) {
_currentIdx++;
}
if (_currentIdx >= _rows.size() &&
_windowRows.back().lowBound == _windowRows.back().value) {
// processed all rows, do not need preceding values
_rows.clear();
_windowRows.clear();
_currentIdx = 0;
return;
}
if (_currentIdx == 0) { // nothing lower to remove
return;
}
size_t i = std::min(_currentIdx, _rows.size() - 1);
WindowBounds::Row row = _windowRows[i];
bool foundLimit = false;
while (i-- > 0) { // i might underflow, but thats ok
if (_windowRows[i].value < row.lowBound && _windowRows[i].valid) {
TRI_ASSERT(_windowRows[i].value < row.highBound);
foundLimit = true;
break;
}
}
if (foundLimit) {
TRI_ASSERT(i < _currentIdx);
_rows.erase(_rows.begin(), _rows.begin() + decltype(_rows)::difference_type(i + 1));
_windowRows.erase(_windowRows.begin(), _windowRows.begin() + decltype(_windowRows)::difference_type(i + 1));
_currentIdx -= (i + 1);
}
}
/**
* @brief Produce rows.
* We need to consume all rows from the inputRange
*
* @param inputRange Data from input
* @param output Where to write the output
* @return std::tuple<ExecutorState, NoStats, AqlCall>
*/
std::tuple<ExecutorState, NoStats, AqlCall> WindowExecutor::produceRows(
AqlItemBlockInputRange& inputRange, OutputAqlItemRow& output) {
ExecutorState state = consumeInputRange(inputRange);
if (_rows.empty()) {
return {state, NoStats{}, AqlCall{}};
}
if (_infos.rangeRegister() == RegisterPlan::MaxRegisterId) {
// row based WINDOW
const size_t numPreceding = size_t(_infos.bounds().numPrecedingRows());
const size_t numFollowing = size_t(_infos.bounds().numFollowingRows());
auto haveRows = [&]() -> bool {
return (state == ExecutorState::DONE && _currentIdx < _rows.size()) ||
(numPreceding <= _currentIdx &&
numFollowing + _currentIdx < _rows.size());
};
// simon; Fairly inefficient aggregation loop, would need a better
// Aggregation API allowing removal of values to avoid re-scanning entire range
while (!output.isFull() && haveRows()) {
size_t start = _currentIdx > numPreceding ? _currentIdx - numPreceding : 0;
size_t end = std::min(_rows.size(), _currentIdx + numFollowing + 1);
while (start != end) {
applyAggregators(_rows[start]);
start++;
}
produceOutputRow(_rows[_currentIdx], output, /*reset*/ true);
_currentIdx++;
}
trimBounds();
} else { // range based WINDOW
TRI_ASSERT(_rows.size() == _windowRows.size());
// fairly inefficient loop, see comment above
size_t offset = 0;
while (!output.isFull() && _currentIdx < _rows.size()) {
auto const& row = _windowRows[_currentIdx];
if (!row.valid) {
produceInvalidOutputRow(_rows[_currentIdx], output);
_currentIdx++;
continue;
}
size_t i = offset;
bool foundLimit = false;
for (; i < _windowRows.size(); i++) {
if (!row.valid) {
continue; // skip
}
if (row.lowBound <= _windowRows[i].value) {
if (row.highBound < _windowRows[i].value) {
foundLimit = true;
break; // do not consider higher values
}
applyAggregators(_rows[size_t(i)]);
} else {
// lower index have _windowRows[i].value < row.lowBound
offset = i + 1;
}
}
if (foundLimit || state == ExecutorState::DONE) {
produceOutputRow(_rows[_currentIdx], output, /*reset*/ true);
_currentIdx++;
continue;
}
TRI_ASSERT(state == ExecutorState::HASMORE);
resetAggregators();
break; // need more data from upstream
}
trimBounds();
}
if (_currentIdx < _rows.size()) {
state = ExecutorState::HASMORE;
}
return {state, NoStats{}, AqlCall{}};
}
/**
* @brief Skip Rows
* We need to consume all rows from the inputRange
*
* @param inputRange Data from input
* @param call Call from client
* @return std::tuple<ExecutorState, NoStats, size_t, AqlCall>
*/
std::tuple<ExecutorState, NoStats, size_t, AqlCall> WindowExecutor::skipRowsRange(
AqlItemBlockInputRange& inputRange, AqlCall& call) {
TRI_ASSERT(_currentIdx < _rows.size());
std::ignore = consumeInputRange(inputRange);
if (!_rows.empty()) {
// TODO a bit loopy
while (call.needSkipMore() && _currentIdx < _windowRows.size()) {
_currentIdx++;
call.didSkip(1);
}
trimBounds();
}
ExecutorState state = inputRange.upstreamState();
if (_currentIdx < _rows.size()) {
state = ExecutorState::HASMORE;
}
// Just fetch everything from above, allow overfetching
AqlCall upstreamCall{};
return {state, NoStats{}, call.getSkipCount(), upstreamCall};
}
[[nodiscard]] auto WindowExecutor::expectedNumberOfRowsNew(
AqlItemBlockInputRange const& input, AqlCall const& call) const noexcept -> size_t {
if (input.finalState() == ExecutorState::DONE) {
size_t remain = _currentIdx < _rows.size() ? _rows.size() - _currentIdx : 0;
remain += input.countDataRows();
return std::min(call.getLimit(), remain);
}
// We do not know how many more rows will be returned from upstream.
// So we can only overestimate
return call.getLimit();
}
| 32.812785
| 112
| 0.671236
|
lo-ca
|
c047a2b1488bc328fccce013da5856484156ac48
| 20,350
|
cpp
|
C++
|
src/Sniffles.cpp
|
Nextomics/Sniffles
|
92e5f2e994b3e10cc3d1f8c96d12d439613c08b5
|
[
"MIT"
] | 1
|
2021-05-16T03:31:49.000Z
|
2021-05-16T03:31:49.000Z
|
src/Sniffles.cpp
|
Nextomics/Sniffles
|
92e5f2e994b3e10cc3d1f8c96d12d439613c08b5
|
[
"MIT"
] | null | null | null |
src/Sniffles.cpp
|
Nextomics/Sniffles
|
92e5f2e994b3e10cc3d1f8c96d12d439613c08b5
|
[
"MIT"
] | null | null | null |
//============================================================================
// Name : Sniffles.cpp
// Author : Fritz Sedlazeck
// Version :
// Copyright : MIT License
// Description : Detection of SVs for long read data.
//============================================================================
//For mac: cmake -D CMAKE_C_COMPILER=/opt/local/bin/gcc-mp-4.7 -D CMAKE_CXX_COMPILER=/opt/local/bin/g++-mp-4.7 ..
#include <iostream>
#include "Paramer.h"
#include <tclap/CmdLine.h>
#include <unistd.h>
#include <omp.h>
#include "Genotyper/Genotyper.h"
#include "realign/Realign.h"
#include "sub/Detect_Breakpoints.h"
#include "print/IPrinter.h"
#include "print/VCFPrinter.h"
#include "print/BedpePrinter.h"
#include "print/NGMPrinter.h"
#include "Ignore_Regions.h"
#include "plane-sweep/PlaneSweep_slim.h"
#include "print/BedpePrinter.h"
#include "ArgParseOutput.h"
#include "force_calling/Force_calling.h"
//cmake -D CMAKE_C_COMPILER=/usr/local/bin/gcc-8 -D CMAKE_CXX_COMPILER=/usr/local/bin/g++-8 ..
//TODO:
//check strand headers.
// strand bias??
// I think you could make your performance on PacBio reads even better with a few modifications:
//b. In pbsv, I use a simply mononucleotide consistency check to determine whether to cluster insertions from different reads as supporting the "same" events. In addition to looking at the similarity of length and breakpoints,
//you could measure [min(Act)+min(Cct)+min(Gct)+min(Tct) / max(Act)+max(Cct)+max(Gct)+max(Tct)] Even a lax criterion (>0.25)
//can avoid clustering phantom insertions (where one is say all A and the another is G+T).
//[min(A1,A2)+min(C1,C2)+min(G1,G2)+min(T1,T2)[/[max...]/
Parameter* Parameter::m_pInstance = NULL;
template<typename T>
void printParameter(std::stringstream & usage, TCLAP::ValueArg<T> & arg) {
usage << " " << arg.longID() << std::endl;
usage << " " << arg.getDescription();
if (!arg.isRequired()) {
usage << " [" << arg.getValue() << "]";
}
usage << std::endl;
}
void printParameter(std::stringstream & usage, TCLAP::SwitchArg & arg) {
usage << " " << arg.longID() << std::endl;
usage << " " << arg.getDescription();
if (!arg.isRequired()) {
usage << " [" << (arg.getValue() ? "true" : "false") << "]";
}
usage << std::endl;
}
/*GrandOmics comment
initialize parameters
especially mention:
- minimum length for SV detection
- maximum segment number
- minimum segment length
- maximum distance to group SV
- maximum distance between alignment
- maximum differece per 100bp window
*/
void read_parameters(int argc, char *argv[]) {
// TCLAP::CmdLine cmd("", ' ', "", true);
TCLAP::CmdLine cmd("Sniffles version ", ' ', Parameter::Instance()->version);
TCLAP::ValueArg<std::string> arg_bamfile("m", "mapped_reads", "Sorted bam File", true, "", "string", cmd);
TCLAP::ValueArg<std::string> arg_vcf("v", "vcf", "VCF output file name", false, "", "string", cmd);
TCLAP::ValueArg<std::string> arg_input_vcf("", "Ivcf", "Input VCF file name. Enable force calling", false, "", "string", cmd);
TCLAP::ValueArg<std::string> arg_bedpe("b", "bedpe", " bedpe output file name", false, "", "string", cmd);
TCLAP::ValueArg<std::string> arg_tmp_file("", "tmp_file", "path to temporary file otherwise Sniffles will use the current directory.", false, "", "string", cmd);
//TCLAP::ValueArg<std::string> arg_chrs("c", "chrs", " comma seperated list of chrs to scan", false, "", "string");
TCLAP::ValueArg<int> arg_support("s", "min_support", "Minimum number of reads that support a SV.", false, 10, "int", cmd);
TCLAP::ValueArg<int> arg_splits("", "max_num_splits", "Maximum number of splits per read to be still taken into account.", false, 7, "int", cmd);
TCLAP::ValueArg<int> arg_dist("d", "max_distance", "Maximum distance to group SV together.", false, 1000, "int", cmd);
TCLAP::ValueArg<int> arg_threads("t", "threads", "Number of threads to use.", false, 3, "int", cmd);
TCLAP::ValueArg<int> arg_minlength("l", "min_length", "Minimum length of SV to be reported.", false, 30, "int", cmd);
TCLAP::ValueArg<int> arg_mq("q", "minmapping_qual", "Minimum Mapping Quality.", false, 20, "int", cmd);
TCLAP::ValueArg<int> arg_numreads("n", "num_reads_report", "Report up to N reads that support the SV in the vcf file. -1: report all.", false, 0, "int", cmd);
TCLAP::ValueArg<int> arg_segsize("r", "min_seq_size", "Discard read if non of its segment is larger then this.", false, 2000, "int", cmd);
TCLAP::ValueArg<int> arg_zmw("z", "min_zmw", "Discard SV that are not supported by at least x zmws. This applies only for PacBio recognizable reads.", false, 0, "int", cmd);
TCLAP::ValueArg<int> arg_cluster_supp("", "cluster_support", "Minimum number of reads supporting clustering of SV.", false, 1, "int", cmd);
TCLAP::ValueArg<int> arg_parameter_maxdist("", "max_dist_aln_events", "Maximum distance between alignment (indel) events.", false, 4, "int", cmd);
TCLAP::ValueArg<int> arg_parameter_maxdiff("", "max_diff_per_window", "Maximum differences per 100bp.", false, 50, "int", cmd);
TCLAP::SwitchArg arg_genotype("", "genotype", "Enables Sniffles to compute the genotypes.", cmd, false);
TCLAP::SwitchArg arg_cluster("", "cluster", "Enables Sniffles to phase SVs that occur on the same reads", cmd, false);
TCLAP::SwitchArg arg_std("", "ignore_sd", "Ignores the sd based filtering. ", cmd, false);
TCLAP::SwitchArg arg_bnd("", "report_BND", "Dont report BND instead use Tra in vcf output. ", cmd, true);
TCLAP::SwitchArg arg_seq("", "report_seq", "Report sequences for indels in vcf output. (Beta version!) ", cmd, false);
TCLAP::SwitchArg arg_coords("", "change_coords", "Adopt coordinates for force calling if finding evidence. ", cmd, false);
TCLAP::SwitchArg arg_parameter("", "skip_parameter_estimation", "Enables the scan if only very few reads are present. ", cmd, false);
TCLAP::SwitchArg arg_cs_string("", "cs_string", "Enables the scan of CS string instead of Cigar and MD. ", cmd, false);
TCLAP::SwitchArg arg_read_strand("", "report_read_strands", "Enables the report of the strand categories per read. (Beta) ", cmd, false);
TCLAP::SwitchArg arg_ccs("", "ccs_reads", "Preset CCS Pacbio setting. (Beta) ", cmd, false);
TCLAP::ValueArg<float> arg_allelefreq("f", "allelefreq", "Threshold on allele frequency (0-1). ", false, 0.0, "float", cmd);
TCLAP::ValueArg<float> arg_hetfreq("", "min_het_af", "Threshold on allele frequency (0-1). ", false, 0.3, "float", cmd);
TCLAP::ValueArg<float> arg_homofreq("", "min_homo_af", "Threshold on allele frequency (0-1). ", false, 0.8, "float", cmd);
TCLAP::ValueArg<float> arg_delratio("", "del_ratio", "Estimated ration of deletions per read (0-1). ", false, 0.0458369, "float", cmd);
TCLAP::ValueArg<float> arg_insratio("", "ins_ratio", "Estimated ratio of insertions per read (0-1). ", false, 0.049379, "float", cmd);
std::stringstream usage;
usage << "" << std::endl;
usage << "Usage: sniffles [options] -m <sorted.bam> -v <output.vcf> " << std::endl;
usage << "Version: "<<Parameter::Instance()->version << std::endl;
usage << "Contact: fritz.sedlazeck@gmail.com" << std::endl;
usage << std::endl;
usage << "Input/Output:" << std::endl;
printParameter<std::string>(usage, arg_bamfile);
printParameter<std::string>(usage, arg_vcf);
printParameter<std::string>(usage, arg_bedpe);
printParameter<std::string>(usage, arg_input_vcf);
printParameter<std::string>(usage, arg_tmp_file);
usage << "" << std::endl;
usage << "General:" << std::endl;
printParameter<int>(usage, arg_support);
printParameter<int>(usage, arg_splits);
printParameter<int>(usage, arg_dist);
printParameter<int>(usage, arg_threads);
printParameter<int>(usage, arg_minlength);
printParameter<int>(usage, arg_mq);
printParameter<int>(usage, arg_numreads);
printParameter<int>(usage, arg_segsize);
printParameter<int>(usage, arg_zmw);
printParameter(usage,arg_cs_string);
usage << "" << std::endl;
usage << "Clustering/phasing and genotyping:" << std::endl;
printParameter(usage, arg_genotype);
printParameter(usage, arg_cluster);
printParameter<int>(usage, arg_cluster_supp);
printParameter<float>(usage, arg_allelefreq);
printParameter<float>(usage, arg_homofreq);
printParameter<float>(usage, arg_hetfreq);
usage << "" << std::endl;
usage << "Advanced:" << std::endl;
printParameter(usage, arg_bnd);
printParameter(usage, arg_seq);
printParameter(usage, arg_std);
printParameter(usage,arg_read_strand);
printParameter(usage,arg_ccs);
usage << "" << std::endl;
usage << "Parameter estimation:" << std::endl;
printParameter(usage, arg_parameter);
printParameter<float>(usage, arg_delratio);
printParameter<float>(usage, arg_insratio);
printParameter<int>(usage, arg_parameter_maxdiff);
printParameter<int>(usage, arg_parameter_maxdist);
cmd.setOutput(new ArgParseOutput(usage.str(), ""));
/* cmd.add(arg_homofreq);
cmd.add(arg_hetfreq);
cmd.add(arg_input_vcf);
cmd.add(arg_cluster_supp);
cmd.add(arg_numreads);
cmd.add(arg_zmw);
cmd.add(arg_segsize);
cmd.add(arg_tmp_file);
cmd.add(arg_dist);
cmd.add(arg_threads);
cmd.add(arg_minlength);
cmd.add(arg_mq);
cmd.add(arg_splits);
cmd.add(arg_bedpe);
cmd.add(arg_vcf);
cmd.add(arg_allelefreq);
cmd.add(arg_support);
cmd.add(arg_bamfile);
// cmd.add(arg_chrs);*/
//parse cmd:
cmd.parse(argc, argv);
Parameter::Instance()->change_coords = arg_coords.getValue();
Parameter::Instance()->debug = true;
Parameter::Instance()->score_treshold = 10;
Parameter::Instance()->read_name = " ";//m54238_180925_225123/56099701/ccs";//m54238_180926_231301/43516780/ccs"; //21_16296949_+";//21_40181680_-";//m151102_123142_42286_c100922632550000001823194205121665_s1_p0/80643/0_20394"; //"22_36746138"; //just for debuging reasons!
Parameter::Instance()->bam_files.push_back(arg_bamfile.getValue());
Parameter::Instance()->min_mq = arg_mq.getValue();
Parameter::Instance()->output_vcf = arg_vcf.getValue();
Parameter::Instance()->report_n_reads = arg_numreads.getValue();
Parameter::Instance()->min_support = arg_support.getValue();
Parameter::Instance()->max_splits = arg_splits.getValue();
Parameter::Instance()->max_dist = arg_dist.getValue();
Parameter::Instance()->min_length = arg_minlength.getValue();
Parameter::Instance()->genotype = arg_genotype.getValue();
Parameter::Instance()->phase = arg_cluster.getValue();
Parameter::Instance()->num_threads = arg_threads.getValue();
Parameter::Instance()->output_bedpe = arg_bedpe.getValue();
Parameter::Instance()->tmp_file = arg_tmp_file.getValue();
Parameter::Instance()->min_grouping_support = arg_cluster_supp.getValue();
Parameter::Instance()->min_allelel_frequency = arg_allelefreq.getValue();
Parameter::Instance()->min_segment_size = arg_segsize.getValue();
Parameter::Instance()->reportBND = arg_bnd.getValue();
Parameter::Instance()->input_vcf = arg_input_vcf.getValue();
Parameter::Instance()->print_seq = true;//arg_seq.getValue();
Parameter::Instance()->ignore_std = arg_std.getValue();
Parameter::Instance()->min_zmw = arg_zmw.getValue();
Parameter::Instance()->homfreq = arg_homofreq.getValue();
Parameter::Instance()->hetfreq = arg_hetfreq.getValue();
Parameter::Instance()->skip_parameter_estimation = arg_parameter.getValue();
Parameter::Instance()->cs_string = arg_cs_string.getValue();
Parameter::Instance()->read_strand=arg_read_strand.getValue();
Parameter::Instance()->ccs_reads=arg_ccs.getValue();
if(Parameter::Instance()->ccs_reads){
Parameter::Instance()->skip_parameter_estimation=true;
Parameter::Instance()->ignore_std=false;
}
if (Parameter::Instance()->skip_parameter_estimation) {
cout<<"\tSkip parameter estimation."<<endl;
Parameter::Instance()->score_treshold = 2;
Parameter::Instance()->window_thresh = arg_parameter_maxdiff.getValue();
Parameter::Instance()->max_dist_alns = arg_parameter_maxdist.getValue();
Parameter::Instance()->avg_del =arg_delratio.getValue();
Parameter::Instance()->avg_ins = arg_insratio.getValue();
}
//Parse IDS:
/*std::string buffer = arg_chrs.getValue();
int count = 0;
std::string name = "";
for (size_t i = 0; i < buffer.size(); i++) {
if (buffer[i] == ',') {
Parameter::Instance()->chr_names[name] = true;
name.clear();
} else {
name += buffer[i];
}
}
if (!name.empty()) {
Parameter::Instance()->chr_names[name] = true;
}
*/
if (Parameter::Instance()->min_allelel_frequency > 0 || !Parameter::Instance()->input_vcf.empty()) {
std::cerr << "Automatically enabling genotype mode" << std::endl;
Parameter::Instance()->genotype = true;
}
if (Parameter::Instance()->tmp_file.empty()) { //TODO change to genotyper file and phasing file!
if (Parameter::Instance()->output_bedpe.empty()) {
Parameter::Instance()->tmp_file = Parameter::Instance()->output_vcf;
} else {
Parameter::Instance()->tmp_file = Parameter::Instance()->output_bedpe;
}
Parameter::Instance()->tmp_file += "_tmp";
}
Parameter::Instance()->tmp_genotyp = Parameter::Instance()->tmp_file;
Parameter::Instance()->tmp_phasing = Parameter::Instance()->tmp_file;
Parameter::Instance()->tmp_genotyp += "_genotype";
Parameter::Instance()->tmp_phasing += "_phase";
//should I check tmp file path??
}
//some toy/test functions:
void parse_binary() {
std::string tmp_name_file = Parameter::Instance()->tmp_file; // this file is created in IPrinter and stores the names and ID of SVS.
tmp_name_file += "Names";
FILE * alt_allel_reads = fopen(tmp_name_file.c_str(), "r");
if (alt_allel_reads == NULL) {
std::cerr << "ClusterParse: could not open tmp file: " << tmp_name_file.c_str() << std::endl;
}
std::cout << "start" << std::endl;
name_str tmp;
size_t nbytes = fread(&tmp, sizeof(struct name_str), 1, alt_allel_reads);
std::cout << tmp.read_name << std::endl;
while (nbytes != 0) {
int max_ID = std::max(max_ID, tmp.svs_id);
if (tmp.svs_id == 34 || tmp.svs_id == 35) {
std::cout << "Cluster: " << tmp.svs_id << " " << tmp.read_name << std::endl;
}
// std::cout << tmp.read_name << std::endl;
nbytes = fread(&tmp, sizeof(struct name_str), 1, alt_allel_reads);
}
fclose(alt_allel_reads);
}
double comp_std(std::vector<int> pos, int start) {
double count = 0;
double std_start = 0;
for (size_t i = 0; i < pos.size(); i++) {
count++;
if (pos[i] != -1) {
long diff = (start - pos[i]);
// std::cout << "DIFF Start: " << diff << std::endl;
std_start += std::pow((double) diff, 2.0);
}
}
return std::sqrt(std_start / count);
}
void test_sort_insert(int pos, std::vector<int> & positions) {
size_t i = 0;
while (i < positions.size() && positions[i] < pos) {
i++;
}
positions.insert(positions.begin() + i, pos);
}
double test_comp_std_quantile(std::vector<int> positions, int position) {
double count = 0;
std::vector<int> std_start_dists;
double std_start = 0;
for (std::vector<int>::iterator i = positions.begin(); i != positions.end(); i++) {
long diff = (position - (*i));
// std::cout << "DIFF Start: " << diff << std::endl;
test_sort_insert(std::pow((double) diff, 2.0), std_start_dists);
//std_start += std::pow((double) diff, 2.0);
}
count = 0;
for (size_t i = 0; i < std_start_dists.size() / 2; i++) {
std_start += std_start_dists[i];
count++;
}
return std::sqrt(std_start / count);
}
void test_std() {
srand(time(NULL));
int start = rand() % 100000; /// sqrt(1/12) for ins. Plot TRA std vs. cov/support.
std::vector<int> positions;
double avg = 0;
double num = 0;
for (int border = 100; border < 9001; border = border * 10) {
for (int t = 0; t < 10; t++) {
for (int cov = 2; cov < 5; cov += 1) {
for (size_t i = 0; i < cov; i++) {
int pos = (rand() % border) + (start - (border / 2));
positions.push_back(pos);
}
avg += comp_std(positions, start) / test_comp_std_quantile(positions, start);
std::cout << "Cov: " << cov + 1 << " border: " << border << " STD: " << comp_std(positions, start) << std::endl; // / test_comp_std_quantile(positions, start) << std::endl;
positions.clear();
num++;
}
}
}
std::cout << "AVG: " << avg / num << std::endl;
}
void get_rand(int mean, int num, vector<int> & positions, int interval) {
//std::cout << "sim " << num << std::endl;
for (size_t i = 0; i < num; i++) {
int pos = (rand() % interval) + (mean - (interval / 2));
positions.push_back(pos);
}
}
#include <stdlib.h>
std::vector<int> sort_distance(std::vector<int> positions, int mean) {
std::vector<int> distances;
for (size_t i = 0; i < positions.size(); i++) {
int dist = std::abs(mean - positions[i]);
size_t j = 0;
while (j < distances.size()) {
if (std::abs(mean - distances[j]) < dist) {
distances.insert(distances.begin() + j, positions[i]);
break;
}
j++;
}
if (j == distances.size()) {
distances.push_back(positions[i]);
}
}
return distances;
}
void test_slimming() {
double fract = 0.2;
srand(time(NULL));
int mean = rand() % 100000; /// sqrt(1/12) for ins. Plot TRA std vs. cov/support.
int intervall = 1000;
std::vector<std::vector<double> > stds;
int key = 0;
int cov = 100;
for (double fract = 0.1; fract < 1; fract += 0.1) {
//std::cout<<fract<<std::endl;
std::vector<int> positions;
get_rand(mean, round(cov * fract), positions, intervall); //random process
get_rand(mean, round(cov * (1 - fract)), positions, 10); //focused calls
// std::cout << "Cov: " << cov << " border: " << intervall << " STD: " << comp_std(positions, mean) << std::endl;
std::vector<int> dists;
dists = sort_distance(positions, mean);
/* for (size_t i = 0; i < dists.size(); i++) {
std::cout << abs(mean - dists[i]) << std::endl;
}
*/
std::vector<double> std_tmp;
for (size_t i = 0; i < dists.size(); i++) {
std::vector<int> tmp;
tmp.assign(dists.rbegin(), dists.rend() - i);
double std = comp_std(tmp, mean);
//std::cout << "Points: " << tmp.size() << " STD: " << std << std::endl;
std_tmp.push_back(std);
}
stds.push_back(std_tmp);
}
for (size_t i = 0; i < stds.size(); i++) {
for (size_t j = 0; j < stds[i].size(); j++) {
std::cout << stds[i][j] << "\t";
}
std::cout << std::endl;
}
}
/*GrandOmics comment
main function:
1. initialize parameters using read_parameters
2. if input is bam file, call strutural variation using detect_breakpoints
3. if input is vcf file, build variation iterval tree and call sv using force_calling
4. cluter sv using Cluster_SVS::update_SVs
5. if setting genotype mode, predict genotype using Genotyper::update_SVs
*/
int main(int argc, char *argv[]) {
try {
//init parameter and reads user defined parameter from command line.
read_parameters(argc, argv);
//init openmp:
omp_set_dynamic(0);
omp_set_num_threads(Parameter::Instance()->num_threads);
if ((!Parameter::Instance()->output_vcf.empty()) && (!Parameter::Instance()->output_bedpe.empty())) {
std::cerr << "Please select only vcf OR bedpe output format!" << std::endl;
exit(EXIT_FAILURE);
}
//init printer:
IPrinter * printer;
if (!Parameter::Instance()->output_vcf.empty()) {
printer = new VCFPrinter();
} else if (!Parameter::Instance()->output_bedpe.empty()) {
printer = new BedpePrinter();
} else {
std::cerr << "Please specify an output file using -v or -b" << std::endl;
return -1;
}
printer->init();
if (Parameter::Instance()->input_vcf.empty()) {
//regular calling
//GrandOmics comment: ref to Detect_Breakpoints.cpp
detect_breakpoints(Parameter::Instance()->bam_files[0], printer); //we could write out all read names for each sVs
} else {
//force calling was selected:
force_calling(Parameter::Instance()->bam_files[0], printer);
}
printer->close_file();
//cluster the SVs together:
if (Parameter::Instance()->phase) {
std::cout << "Start phasing: " << std::endl;
Cluster_SVS *cluster = new Cluster_SVS();
//GrandOmics comment: refer to Cluster_SVs.cpp
cluster->update_SVs();
}
//determine genotypes:
if (Parameter::Instance()->genotype) {
std::cout << "Start genotype calling:" << std::endl;
Genotyper * go = new Genotyper();
//GrandOmics comment: refer to Genotyper.cpp
go->update_SVs();
}
} catch (TCLAP::ArgException &e) // catch any exceptions
{
std::cerr << "Sniffles error: " << e.error() << " for arg " << e.argId() << std::endl;
}
return 0;
}
| 39.746094
| 274
| 0.672432
|
Nextomics
|
c0486d2b611cb75e22dde52f08e3e96bcac2726e
| 4,395
|
cpp
|
C++
|
coap/client/CoapRequest.cpp
|
HaknCo/sming-coap
|
8a20f5708b53df3405805aecaea82c8a683859c2
|
[
"MIT"
] | 10
|
2015-12-15T18:32:04.000Z
|
2020-10-27T15:09:05.000Z
|
coap/client/CoapRequest.cpp
|
HaknCo/sming-coap
|
8a20f5708b53df3405805aecaea82c8a683859c2
|
[
"MIT"
] | 2
|
2016-07-04T20:46:51.000Z
|
2021-05-14T19:12:35.000Z
|
coap/client/CoapRequest.cpp
|
HaknCo/sming-coap
|
8a20f5708b53df3405805aecaea82c8a683859c2
|
[
"MIT"
] | 1
|
2015-12-17T23:50:47.000Z
|
2015-12-17T23:50:47.000Z
|
/*
Copyright (c) 2015 Hakan Coskun, http://www.blueonshop.de
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Coap.h"
#include "CoapRequest.h"
#include "Queue.h"
// SMING includes
#include <Wiring/WMath.h>
#include <SmingCore/SmingCore.h>
void CoapRequest::onSent(void *arg) {
debugf("CoapRequest: onSent is called.\n");
}
CoapRequest::CoapRequest(struct ip_addr remote_ip, int remote_port) : CoapRequest(remote_ip, remote_port, nullptr) {
}
CoapRequest::CoapRequest(struct ip_addr remote_ip, int remote_port, CoapRxDelegate onResponseCb) {
debugf("CoapRequest: ctor is called.\n");
this->remote_ip = remote_ip;
this->remote_port = remote_port;
debugf("CoapRequest: Remote IP: ");
debugf(IPSTR, IP2STR(&this->remote_ip.addr));
debugf("CoapRequest: Remote Port: %d.\n", this->remote_port);
this->onResponseCb = onResponseCb;
}
CoapRequest::~CoapRequest() {
debugf("CoapRequest: destructor is called.\n");
}
int CoapRequest::getTransactionId() {
return this->tid;
}
/**
* called by UDPConnection when a packet arrives
*/
void CoapRequest::onReceive(pbuf *pdata, IPAddress remoteIP, uint16 remotePort) {
debugf("CoapRequest: onReceive.\n");
coap_tid_t id = COAP_INVALID_TID;
CoapPDU *recvPDU = new CoapPDU((uint8*)pdata->payload, pdata->tot_len);
if (recvPDU->validate()!=1) {
LOG_COAP_ERROR("malformed CoAP packet");
// inform client about wrong PDU
onResponseCb(false, this, recvPDU);
return;
}
#ifdef COAP_DEBUG
LOG_COAP_INFO("Valid CoAP PDU received");
recvPDU->printHuman();
#endif
// pass PDU to client
onResponseCb(true, this, recvPDU);
}
coap_tid_t CoapRequest::sendPDU(CoapPDU &pdu) {
if (!connected) {
debugf("CoapRequest: connect to IP: ");
debugf(IPSTR, IP2STR(&(this->remote_ip.addr)));
debugf("Port: %d\n", this->remote_port);
if (connect(this->remote_ip, this->remote_port)) {
connected = true;
createTransactionID((uint32) this->udp->remote_ip.addr, (uint32) this->udp->remote_port, pdu, &tid);
debugf("CoapRequest: request tid=%d, connected to ", tid);
debugf(IPSTR, IP2STR(&(this->udp->remote_ip.addr)));
debugf("Port: %d\n", this->udp->remote_port);
} else {
createTransactionID((uint32) this->remote_ip.addr, (uint32) this->remote_port, pdu, &tid);
}
} else {
createTransactionID((uint32) this->udp->remote_ip.addr, (uint32) this->udp->remote_port, pdu, &tid);
}
debugf("CoapRequest: free memory: %d\n", system_get_free_heap_size());
debugf("CoapRequest: Send PDU with transaction id %d\n", tid);
debugf("CoapRequest: PDU size %d\n", pdu.getPDULength());
// sendTo(this->remote_ip, this->remote_port, (char*) pdu.getPDUPointer(), pdu.getPDULength());
// send packet
send((char*) pdu.getPDUPointer(), pdu.getPDULength());
return tid;
}
void CoapRequest::close() {
debugf("CoapRequest: close request\n");
UdpConnection::close();
}
void CoapRequest::staticDnsResponse(const char *name, struct ip_addr *ip, void *arg) {
// DNS has been resolved
CoapRequest *self = (CoapRequest*) arg;
// TODO get last request and repeat
if (ip != NULL) {
// We do a new request since the last one was never done.
//self->internalRequestTime(*ip);
}
}
| 31.847826
| 116
| 0.736064
|
HaknCo
|
c05063a28ed731ea3ab1d031249896ed5df577ce
| 1,768
|
cpp
|
C++
|
src/nh99/mod_mc1.cpp
|
johnrsibert/admb
|
063ec863a9f23f6c6afbc7d481af0476b8d63645
|
[
"BSD-3-Clause"
] | 79
|
2015-01-16T14:14:22.000Z
|
2022-01-24T06:28:15.000Z
|
src/nh99/mod_mc1.cpp
|
johnrsibert/admb
|
063ec863a9f23f6c6afbc7d481af0476b8d63645
|
[
"BSD-3-Clause"
] | 172
|
2015-01-21T01:53:57.000Z
|
2022-03-29T19:57:31.000Z
|
src/nh99/mod_mc1.cpp
|
johnrsibert/admb
|
063ec863a9f23f6c6afbc7d481af0476b8d63645
|
[
"BSD-3-Clause"
] | 22
|
2015-01-15T18:11:54.000Z
|
2022-01-11T21:47:51.000Z
|
/**
* Author: David Fournier
* Copyright (c) 2008-2012 Regents of the University of California
*/
#include <admodel.h>
void initial_params::add_random_vector(const dvector& x)
{
int ii=1;
for (int i=0;i<num_initial_params;i++)
{
if (withinbound(0,(varsptr[i])->phase_start,current_phase))
{
(varsptr[i])->add_value((const dvector&)(x),ii);
}
}
}
void param_init_number::add_value(const dvector& ndev, const int& _ii)
{
int& ii=(int&) _ii;
(*this)+=ndev(ii);
ii++;
}
void param_init_bounded_number::add_value(const dvector& ndev, const int& _ii)
{
int& ii=(int&) _ii;
(*this)+=ndev(ii);
ii++;
}
void param_init_vector::add_value(const dvector& ndev, const int& _ii)
{
int& ii=(int&) _ii;
int mmin=indexmin();
int mmax=indexmax();
for (int i=mmin;i<=mmax;i++)
{
(*this)(i)+=ndev(ii);
ii++;
}
}
void param_init_bounded_vector::add_value(const dvector& ndev, const int& _ii)
{
int& ii=(int&) _ii;
int mmin=indexmin();
int mmax=indexmax();
for (int i=mmin;i<=mmax;i++)
{
(*this)(i)+=ndev(ii);
ii++;
}
}
void param_init_matrix::add_value(const dvector& ndev, const int& _ii)
{
int& ii=(int&) _ii;
int rmin=rowmin();
int rmax=rowmax();
for (int i=rmin;i<=rmax;i++)
{
int cmin=(*this)(i).indexmin();
int cmax=(*this)(i).indexmax();
for (int j=cmin;j<=cmax;j++)
{
(*this)(i,j)+=ndev(ii);
ii++;
}
}
}
void param_init_bounded_matrix::add_value(const dvector& ndev, const int& _ii)
{
int& ii=(int&) _ii;
int rmin=rowmin();
int rmax=rowmax();
for (int i=rmin;i<=rmax;i++)
{
int cmin=(*this)(i).indexmin();
int cmax=(*this)(i).indexmax();
for (int j=cmin;j<=cmax;j++)
{
(*this)(i,j)+=ndev(ii);
ii++;
}
}
}
| 19.644444
| 78
| 0.593891
|
johnrsibert
|
c052b627264dd19c509d96bb50f5176e6f6bd125
| 80,349
|
cpp
|
C++
|
point_light/app.cpp
|
colintan95/vk_projects
|
0b048455f240c8105848f210be1610980c3c40ac
|
[
"MIT"
] | null | null | null |
point_light/app.cpp
|
colintan95/vk_projects
|
0b048455f240c8105848f210be1610980c3c40ac
|
[
"MIT"
] | null | null | null |
point_light/app.cpp
|
colintan95/vk_projects
|
0b048455f240c8105848f210be1610980c3c40ac
|
[
"MIT"
] | null | null | null |
#include "point_light/app.h"
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
#include "utils/camera.h"
#include "utils/model.h"
#include "utils/vk.h"
namespace {
const char* kRequiredValidationLayers[] = {
"VK_LAYER_KHRONOS_validation"
};
const char* kRequiredDeviceExtensions[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
constexpr int kShadowTextureWidth = 1024;
constexpr int kShadowTextureHeight = 1024;
constexpr float kShadowPassNearPlane = 0.01f;
constexpr float kShadowPassFarPlane = 10.f;
constexpr int kMaxFramesInFlight = 3;
constexpr float kPi = glm::pi<float>();
constexpr float kStrafeSpeed = 3.f;
std::vector<const char*> GetRequiredValidationLayers() {
return std::vector<const char*>(
kRequiredValidationLayers,
kRequiredValidationLayers +
sizeof(kRequiredValidationLayers) / sizeof(const char*));
}
std::vector<const char*> GetRequiredInstanceExtensions() {
uint32_t glfw_ext_count = 0;
const char** glfw_exts = glfwGetRequiredInstanceExtensions(&glfw_ext_count);
std::vector<const char*> extensions(glfw_exts, glfw_exts + glfw_ext_count);
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
return extensions;
}
std::vector<const char*> GetRequiredDeviceExtensions() {
return std::vector<const char*>(
kRequiredDeviceExtensions,
kRequiredDeviceExtensions +
sizeof(kRequiredDeviceExtensions) / sizeof(const char*));
}
VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT severity,
VkDebugUtilsMessageTypeFlagsEXT type,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* user_data) {
std::cerr << "Validation layer: " << callback_data->pMessage << std::endl;
return VK_FALSE;
}
struct QueueIndices {
std::optional<uint32_t> graphics_queue_index;
std::optional<uint32_t> present_queue_index;
};
bool FoundQueueIndices(const QueueIndices& indices) {
return indices.graphics_queue_index.has_value() &&
indices.present_queue_index.has_value();
}
QueueIndices FindQueueIndices(VkPhysicalDevice physical_device,
VkSurfaceKHR surface) {
QueueIndices indices{};
uint32_t count;
vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, nullptr);
std::vector<VkQueueFamilyProperties> families(count);
vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count,
families.data());
for (int i = 0; i < families.size(); ++i) {
VkQueueFamilyProperties family = families[i];
if ((family.queueFlags & VK_QUEUE_GRAPHICS_BIT) == 1)
indices.graphics_queue_index = i;
VkBool32 present_support = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physical_device, i, surface,
&present_support);
if (present_support)
indices.present_queue_index = i;
if (FoundQueueIndices(indices))
return indices;
}
return indices;
}
bool IsPhysicalDeviceSuitable(VkPhysicalDevice physical_device,
VkSurfaceKHR surface) {
QueueIndices queue_indices = FindQueueIndices(physical_device, surface);
if (!FoundQueueIndices(queue_indices))
return false;
if (!utils::vk::SupportsDeviceExtensions(physical_device,
GetRequiredDeviceExtensions())) {
return false;
}
uint32_t surface_formats_count;
vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface,
&surface_formats_count, nullptr);
if (surface_formats_count == 0)
return false;
uint32_t present_modes_count;
vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface,
&present_modes_count, nullptr);
if (present_modes_count == 0)
return false;
VkPhysicalDeviceFeatures features;
vkGetPhysicalDeviceFeatures(physical_device, &features);
if (!features.samplerAnisotropy)
return false;
return true;
}
VkSampleCountFlagBits ChooseMsaaSampleCount(VkPhysicalDevice physical_device) {
VkPhysicalDeviceProperties phys_device_props;
vkGetPhysicalDeviceProperties(physical_device, &phys_device_props);
VkSampleCountFlags sample_count_flags =
phys_device_props.limits.framebufferColorSampleCounts &
phys_device_props.limits.framebufferDepthSampleCounts;
if (sample_count_flags & VK_SAMPLE_COUNT_4_BIT) {
return VK_SAMPLE_COUNT_4_BIT;
} else if (sample_count_flags & VK_SAMPLE_COUNT_2_BIT) {
return VK_SAMPLE_COUNT_2_BIT;
}
return VK_SAMPLE_COUNT_1_BIT;
}
VkSurfaceFormatKHR ChooseSurfaceFormat(VkPhysicalDevice physical_device,
VkSurfaceKHR surface) {
uint32_t formats_count;
vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &formats_count,
nullptr);
std::vector<VkSurfaceFormatKHR> formats(formats_count);
vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &formats_count,
formats.data());
for (const auto& format : formats) {
if (format.format == VK_FORMAT_B8G8R8A8_SRGB &&
format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
return format;
}
return formats[0];
}
VkPresentModeKHR ChoosePresentMode(VkPhysicalDevice physical_device,
VkSurfaceKHR surface) {
uint32_t present_mode_count;
vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface,
&present_mode_count, nullptr);
std::vector<VkPresentModeKHR> present_modes(present_mode_count);
vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface,
&present_mode_count,
present_modes.data());
for (const auto& mode : present_modes) {
if (mode == VK_PRESENT_MODE_MAILBOX_KHR)
return mode;
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D ChooseSwapChainExtent(const VkSurfaceCapabilitiesKHR& capabilities,
GLFWwindow* window) {
if (capabilities.currentExtent.width != UINT32_MAX) {
return capabilities.currentExtent;
} else {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D extent = {
static_cast<uint32_t>(width),
static_cast<uint32_t>(height)
};
extent.width = std::clamp(extent.width, capabilities.minImageExtent.width,
capabilities.maxImageExtent.width);
extent.height = std::clamp(extent.height,
capabilities.minImageExtent.height,
capabilities.maxImageExtent.height);
return extent;
}
}
VkFormat FindDepthFormat(VkPhysicalDevice physical_device) {
std::vector<VkFormat> formats = {
VK_FORMAT_D32_SFLOAT,
VK_FORMAT_D32_SFLOAT_S8_UINT,
VK_FORMAT_D24_UNORM_S8_UINT
};
return utils::vk::FindSupportedFormat(
formats, VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT, physical_device);
}
} // namespace
bool App::Init() {
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_SCALE_TO_MONITOR , GL_TRUE);
window_ = glfwCreateWindow(800, 600, "Vulkan Application", nullptr, nullptr);
glfwSetWindowUserPointer(window_, this);
glfwSetFramebufferSizeCallback(window_, GlfwFramebufferResized);
glfwSetKeyCallback(window_, GlfwKeyCallback);
if (!utils::LoadModel("cornell_box.obj", &model_))
return false;
camera_.SetPosition(glm::vec3(0.f, 1.f, 4.f));
if (!InitInstanceAndSurface())
return false;
if (!ChoosePhysicalDevice())
return false;
if (!CreateDevice())
return false;
if (!CreateSwapChain())
return false;
if (!CreateScenePassResources())
return false;
if (!CreateShadowPassResources())
return false;
if (!CreateCommandPool())
return false;
if (!CreateCommandBuffers())
return false;
if (!CreateDescriptorSets())
return false;
if (!CreateVertexBuffers())
return false;
if (!CreateSyncObjects())
return false;
return true;
}
void App::GlfwFramebufferResized(GLFWwindow* window, int width, int height) {
auto app = reinterpret_cast<App*>(glfwGetWindowUserPointer(window));
app->framebuffer_resized_ = true;
}
void App::GlfwKeyCallback(GLFWwindow* window, int key, int scancode, int action,
int mods) {
auto app = reinterpret_cast<App*>(glfwGetWindowUserPointer(window));
if (key == GLFW_KEY_A) {
if (action == GLFW_PRESS)
app->camera_.StartMovement(utils::Camera::Direction::kNegX, kStrafeSpeed);
else if (action == GLFW_RELEASE)
app->camera_.StopMovement(utils::Camera::Direction::kNegX);
}
if (key == GLFW_KEY_D) {
if (action == GLFW_PRESS)
app->camera_.StartMovement(utils::Camera::Direction::kPosX, kStrafeSpeed);
else if (action == GLFW_RELEASE)
app->camera_.StopMovement(utils::Camera::Direction::kPosX);
}
}
bool App::InitInstanceAndSurface() {
if (!utils::vk::SupportsValidationLayers(GetRequiredValidationLayers())) {
std::cerr << "Does not support required validation layers." << std::endl;
return false;
}
VkApplicationInfo app_info{};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pApplicationName = "Hello Triangle";
app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.pEngineName = "No Engine";
app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.apiVersion = VK_API_VERSION_1_0;
std::vector<const char*> validation_layers =
GetRequiredValidationLayers();
std::vector<const char*> instance_extensions =
GetRequiredInstanceExtensions();
VkDebugUtilsMessengerCreateInfoEXT debug_messenger_info{};
debug_messenger_info.sType =
VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debug_messenger_info.messageSeverity =
VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
debug_messenger_info.messageType =
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
debug_messenger_info.pfnUserCallback = DebugCallback;
VkInstanceCreateInfo instance_info{};
instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instance_info.pApplicationInfo = &app_info;
instance_info.enabledExtensionCount =
static_cast<uint32_t>(instance_extensions.size());
instance_info.ppEnabledExtensionNames = instance_extensions.data();
instance_info.enabledLayerCount =
static_cast<uint32_t>(validation_layers.size());
instance_info.ppEnabledLayerNames = validation_layers.data();
instance_info.pNext = &debug_messenger_info;
if (vkCreateInstance(&instance_info, nullptr, &instance_) != VK_SUCCESS) {
std::cerr << "Could not create instance." << std::endl;
return false;
}
if (utils::vk::CreateDebugUtilsMessenger(instance_, &debug_messenger_info,
nullptr, &debug_messenger_)
!= VK_SUCCESS) {
std::cerr << "Could not create debug messenger." << std::endl;
return false;
}
if (glfwCreateWindowSurface(instance_, window_, nullptr, &surface_)
!= VK_SUCCESS) {
std::cerr << "Could not create surface." << std::endl;
return false;
}
return true;
}
bool App::ChoosePhysicalDevice() {
uint32_t phys_devices_count = 0;
vkEnumeratePhysicalDevices(instance_, &phys_devices_count, nullptr);
if (phys_devices_count == 0) {
std::cerr << "Could not find suitable physical device." << std::endl;
return false;
}
std::vector<VkPhysicalDevice> phys_devices(phys_devices_count);
vkEnumeratePhysicalDevices(instance_, &phys_devices_count,
phys_devices.data());
for (const auto& phys_device : phys_devices) {
if (IsPhysicalDeviceSuitable(phys_device, surface_)) {
physical_device_ = phys_device;
return true;
}
}
std::cerr << "Could not find suitable physical device." << std::endl;
return false;
}
bool App::CreateDevice() {
QueueIndices queue_indices = FindQueueIndices(physical_device_, surface_);
graphics_queue_index_ = queue_indices.graphics_queue_index.value();
present_queue_index_ = queue_indices.present_queue_index.value();
std::set<uint32_t> unique_queue_indices = {
graphics_queue_index_, present_queue_index_
};
std::vector<VkDeviceQueueCreateInfo> queue_infos;
for (uint32_t queue_index : unique_queue_indices) {
float priority = 1.0f;
VkDeviceQueueCreateInfo queue_info{};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.queueFamilyIndex = queue_index;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = &priority;
queue_infos.push_back(queue_info);
}
VkPhysicalDeviceFeatures phys_device_features{};
phys_device_features.samplerAnisotropy = VK_TRUE;
std::vector<const char*> device_extensions = GetRequiredDeviceExtensions();
std::vector<const char*> validation_layers = GetRequiredValidationLayers();
VkDeviceCreateInfo device_info{};
device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_info.queueCreateInfoCount = static_cast<uint32_t>(queue_infos.size());
device_info.pQueueCreateInfos = queue_infos.data();
device_info.pEnabledFeatures = &phys_device_features;
device_info.enabledExtensionCount = static_cast<uint32_t>(
device_extensions.size());
device_info.ppEnabledExtensionNames = device_extensions.data();
device_info.enabledLayerCount = static_cast<uint32_t>(
validation_layers.size());
device_info.ppEnabledLayerNames = validation_layers.data();
if (vkCreateDevice(physical_device_, &device_info, nullptr, &device_)
!= VK_SUCCESS) {
std::cerr << "Could not create device." << std::endl;
return false;
}
vkGetDeviceQueue(device_, graphics_queue_index_, 0, &graphics_queue_);
vkGetDeviceQueue(device_, present_queue_index_, 0, &present_queue_);
msaa_sample_count_ = ChooseMsaaSampleCount(physical_device_);
return true;
}
bool App::CreateSwapChain() {
VkSurfaceCapabilitiesKHR surface_capabilities;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device_, surface_,
&surface_capabilities);
swap_chain_extent_ = ChooseSwapChainExtent(surface_capabilities, window_);
uint32_t swap_chain_image_count = std::min(
surface_capabilities.minImageCount + 1,
surface_capabilities.maxImageCount);
VkSurfaceFormatKHR surface_format = ChooseSurfaceFormat(physical_device_,
surface_);
swap_chain_image_format_ = surface_format.format;
VkPresentModeKHR present_mode = ChoosePresentMode(physical_device_, surface_);
VkSwapchainCreateInfoKHR swap_chain_info{};
swap_chain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swap_chain_info.surface = surface_;
swap_chain_info.minImageCount = swap_chain_image_count;
swap_chain_info.imageFormat = swap_chain_image_format_;
swap_chain_info.imageColorSpace = surface_format.colorSpace;
swap_chain_info.imageExtent = swap_chain_extent_;
swap_chain_info.imageArrayLayers = 1;
swap_chain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swap_chain_info.preTransform = surface_capabilities.currentTransform;
swap_chain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swap_chain_info.presentMode = present_mode;
swap_chain_info.clipped = VK_TRUE;
if (graphics_queue_index_ != present_queue_index_) {
uint32_t indices[] = { graphics_queue_index_, present_queue_index_ };
swap_chain_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swap_chain_info.queueFamilyIndexCount = 2;
swap_chain_info.pQueueFamilyIndices = indices;
} else {
swap_chain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
if (vkCreateSwapchainKHR(device_, &swap_chain_info, nullptr, &swap_chain_)
!= VK_SUCCESS) {
std::cerr << "Could not create swap chain." << std::endl;
return false;
}
vkGetSwapchainImagesKHR(device_, swap_chain_, &swap_chain_image_count,
nullptr);
swap_chain_images_.resize(swap_chain_image_count);
vkGetSwapchainImagesKHR(device_, swap_chain_, &swap_chain_image_count,
swap_chain_images_.data());
swap_chain_image_views_.resize(swap_chain_images_.size());
for (int i = 0; i < swap_chain_images_.size(); ++i) {
VkImageViewCreateInfo image_view_info{};
image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_info.image = swap_chain_images_[i];
image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
image_view_info.format = swap_chain_image_format_;
image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
image_view_info.subresourceRange.baseMipLevel = 0;
image_view_info.subresourceRange.levelCount = 1;
image_view_info.subresourceRange.baseArrayLayer = 0;
image_view_info.subresourceRange.layerCount = 1;
if (vkCreateImageView(device_, &image_view_info, nullptr,
&swap_chain_image_views_[i]) != VK_SUCCESS) {
std::cerr << "Could not create swap chain image view." << std::endl;
return false;
}
}
return true;
}
bool App::CreateScenePassResources() {
if (!CreateRenderPass())
return false;
if (!CreatePipeline())
return false;
if (!CreateFramebuffers())
return false;
return true;
}
bool App::CreateRenderPass() {
VkAttachmentDescription color_attachment{};
color_attachment.format = swap_chain_image_format_;
color_attachment.samples = msaa_sample_count_;
color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkFormat depth_format = FindDepthFormat(physical_device_);
if (depth_format == VK_FORMAT_UNDEFINED) {
std::cerr << "Could not find suitable depth format." << std::endl;
return false;
}
VkAttachmentDescription depth_attachment{};
depth_attachment.format = depth_format;
depth_attachment.samples = msaa_sample_count_;
depth_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depth_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depth_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depth_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depth_attachment.finalLayout =
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentDescription color_resolve_attachment{};
color_resolve_attachment.format = swap_chain_image_format_;
color_resolve_attachment.samples = VK_SAMPLE_COUNT_1_BIT;
color_resolve_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_resolve_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_resolve_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_resolve_attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference color_attachment_ref{};
color_attachment_ref.attachment = 0;
color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_attachment_ref{};
depth_attachment_ref.attachment = 1;
depth_attachment_ref.layout =
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference color_resolve_attachment_ref{};
color_resolve_attachment_ref.attachment = 2;
color_resolve_attachment_ref.layout =
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_attachment_ref;
subpass.pResolveAttachments = &color_resolve_attachment_ref;
subpass.pDepthStencilAttachment = &depth_attachment_ref;
VkSubpassDependency subpass_dep{};
subpass_dep.srcSubpass = VK_SUBPASS_EXTERNAL;
subpass_dep.dstSubpass = 0;
subpass_dep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
subpass_dep.srcAccessMask = 0;
subpass_dep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
subpass_dep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
VkAttachmentDescription attachments[] = {
color_attachment, depth_attachment, color_resolve_attachment
};
VkRenderPassCreateInfo render_pass_info{};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_info.attachmentCount = 3;
render_pass_info.pAttachments = attachments;
render_pass_info.subpassCount = 1;
render_pass_info.pSubpasses = &subpass;
render_pass_info.dependencyCount = 1;
render_pass_info.pDependencies = &subpass_dep;
if (vkCreateRenderPass(device_, &render_pass_info, nullptr, &render_pass_)
!= VK_SUCCESS) {
std::cerr << "Could not create render pass." << std::endl;
return false;
}
return true;
}
bool App::CreatePipeline() {
std::vector<std::string> shader_file_paths = {
"shader_vert.spv", "shader_frag.spv"
};
std::vector<VkShaderModule> shader_modules;
if (!utils::vk::CreateShaderModulesFromFiles(shader_file_paths, device_,
&shader_modules)) {
std::cerr << "Could not create shader modules." << std::endl;
return false;
}
VkPipelineShaderStageCreateInfo vert_shader_info{};
vert_shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vert_shader_info.stage = VK_SHADER_STAGE_VERTEX_BIT;
vert_shader_info.module = shader_modules[0];
vert_shader_info.pName = "main";
VkPipelineShaderStageCreateInfo frag_shader_info{};
frag_shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
frag_shader_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
frag_shader_info.module = shader_modules[1];
frag_shader_info.pName = "main";
VkPipelineShaderStageCreateInfo shader_stages[] = {
vert_shader_info, frag_shader_info
};
VkDescriptorSetLayoutBinding vert_ubo_binding{};
vert_ubo_binding.binding = 0;
vert_ubo_binding.descriptorCount = 1;
vert_ubo_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
vert_ubo_binding.pImmutableSamplers = nullptr;
vert_ubo_binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
VkDescriptorSetLayoutBinding frag_ubo_binding{};
frag_ubo_binding.binding = 1;
frag_ubo_binding.descriptorCount = 1;
frag_ubo_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
frag_ubo_binding.pImmutableSamplers = nullptr;
frag_ubo_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutBinding shadow_tex_sampler_binding{};
shadow_tex_sampler_binding.binding = 2;
shadow_tex_sampler_binding.descriptorCount = 1;
shadow_tex_sampler_binding.descriptorType =
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
shadow_tex_sampler_binding.pImmutableSamplers = nullptr;
shadow_tex_sampler_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
VkDescriptorSetLayoutBinding descriptor_set_bindings[] = {
vert_ubo_binding, frag_ubo_binding, shadow_tex_sampler_binding
};
VkDescriptorSetLayoutCreateInfo descriptor_set_layout_info{};
descriptor_set_layout_info.sType =
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptor_set_layout_info.bindingCount = 3;
descriptor_set_layout_info.pBindings = descriptor_set_bindings;
if (vkCreateDescriptorSetLayout(device_, &descriptor_set_layout_info, nullptr,
&descriptor_set_layout_) != VK_SUCCESS) {
std::cerr << "Could not create descriptor set layout." << std::endl;
return false;
}
VkVertexInputBindingDescription position_binding{};
position_binding.binding = 0;
position_binding.stride = sizeof(glm::vec3);
position_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
VkVertexInputAttributeDescription position_attrib_desc{};
position_attrib_desc.binding = 0;
position_attrib_desc.location = 0;
position_attrib_desc.format = VK_FORMAT_R32G32B32_SFLOAT;
position_attrib_desc.offset = 0;
VkVertexInputBindingDescription normal_binding{};
normal_binding.binding = 1;
normal_binding.stride = sizeof(glm::vec3);
normal_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
VkVertexInputAttributeDescription normal_attrib_desc{};
normal_attrib_desc.binding = 1;
normal_attrib_desc.location = 1;
normal_attrib_desc.format = VK_FORMAT_R32G32B32_SFLOAT;
normal_attrib_desc.offset = 0;
VkVertexInputBindingDescription mtl_idx_binding{};
mtl_idx_binding.binding = 2;
mtl_idx_binding.stride = sizeof(uint32_t);
mtl_idx_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
VkVertexInputAttributeDescription mtl_idx_attrib_desc{};
mtl_idx_attrib_desc.binding = 2;
mtl_idx_attrib_desc.location = 2;
mtl_idx_attrib_desc.format = VK_FORMAT_R32_UINT;
mtl_idx_attrib_desc.offset = 0;
VkVertexInputBindingDescription vertex_bindings[] = {
position_binding, normal_binding, mtl_idx_binding
};
VkVertexInputAttributeDescription vertex_attribs[] = {
position_attrib_desc, normal_attrib_desc, mtl_idx_attrib_desc
};
VkPipelineVertexInputStateCreateInfo vertex_input{};
vertex_input.sType =
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input.vertexBindingDescriptionCount = 3;
vertex_input.pVertexBindingDescriptions = vertex_bindings;
vertex_input.vertexAttributeDescriptionCount = 3;
vertex_input.pVertexAttributeDescriptions = vertex_attribs;
VkPipelineInputAssemblyStateCreateInfo input_assembly{};
input_assembly.sType =
VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
input_assembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<float>(swap_chain_extent_.width);
viewport.height = static_cast<float>(swap_chain_extent_.height);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor{};
scissor.offset = {0, 0};
scissor.extent = swap_chain_extent_;
VkPipelineViewportStateCreateInfo viewport_info{};
viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_info.viewportCount = 1;
viewport_info.pViewports = &viewport;
viewport_info.scissorCount = 1;
viewport_info.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType =
VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = msaa_sample_count_;
VkPipelineDepthStencilStateCreateInfo depth_stencil{};
depth_stencil.sType =
VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depth_stencil.depthTestEnable = VK_TRUE;
depth_stencil.depthWriteEnable = VK_TRUE;
depth_stencil.depthCompareOp = VK_COMPARE_OP_LESS;
depth_stencil.depthBoundsTestEnable = VK_FALSE;
depth_stencil.stencilTestEnable = VK_FALSE;
VkPipelineColorBlendAttachmentState color_blend_attachment{};
color_blend_attachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo color_blend_info{};
color_blend_info.sType =
VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blend_info.logicOpEnable = VK_FALSE;
color_blend_info.logicOp = VK_LOGIC_OP_COPY;
color_blend_info.attachmentCount = 1;
color_blend_info.pAttachments = &color_blend_attachment;
color_blend_info.blendConstants[0] = 0.0f;
color_blend_info.blendConstants[1] = 0.0f;
color_blend_info.blendConstants[2] = 0.0f;
color_blend_info.blendConstants[3] = 0.0f;
VkPipelineLayoutCreateInfo pipeline_layout_info{};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.setLayoutCount = 1;
pipeline_layout_info.pSetLayouts = &descriptor_set_layout_;
if (vkCreatePipelineLayout(device_, &pipeline_layout_info, nullptr,
&pipeline_layout_) != VK_SUCCESS) {
std::cerr << "Could not create pipeline layout." << std::endl;
return false;
}
VkGraphicsPipelineCreateInfo pipeline_info{};
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.stageCount = 2;
pipeline_info.pStages = shader_stages;
pipeline_info.pVertexInputState = &vertex_input;
pipeline_info.pInputAssemblyState = &input_assembly;
pipeline_info.pViewportState = &viewport_info;
pipeline_info.pRasterizationState = &rasterizer;
pipeline_info.pMultisampleState = &multisampling;
pipeline_info.pDepthStencilState = &depth_stencil;
pipeline_info.pColorBlendState = &color_blend_info;
pipeline_info.layout = pipeline_layout_;
pipeline_info.renderPass = render_pass_;
pipeline_info.subpass = 0;
pipeline_info.basePipelineHandle = VK_NULL_HANDLE;
if (vkCreateGraphicsPipelines(device_, VK_NULL_HANDLE, 1, &pipeline_info,
nullptr, &pipeline_) != VK_SUCCESS) {
std::cerr << "Could not create pipeline." << std::endl;
return false;
}
for (VkShaderModule shader_module : shader_modules) {
vkDestroyShaderModule(device_, shader_module, nullptr);
}
return true;
}
bool App::CreateFramebuffers() {
VkImageCreateInfo color_image_info{};
color_image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
color_image_info.imageType = VK_IMAGE_TYPE_2D;
color_image_info.extent.width = swap_chain_extent_.width;
color_image_info.extent.height = swap_chain_extent_.height;
color_image_info.extent.depth = 1;
color_image_info.mipLevels = 1;
color_image_info.arrayLayers = 1;
color_image_info.format = swap_chain_image_format_;
color_image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
color_image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_image_info.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT |
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
color_image_info.samples = msaa_sample_count_;
color_image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (!utils::vk::CreateImage(color_image_info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
physical_device_, device_, color_image_,
color_image_memory_)) {
std::cerr << "Could not create color image." << std::endl;
return false;
}
VkImageViewCreateInfo color_image_view_info{};
color_image_view_info.sType =
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
color_image_view_info.image = color_image_;
color_image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
color_image_view_info.format = swap_chain_image_format_;
color_image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_image_view_info.subresourceRange.baseMipLevel = 0;
color_image_view_info.subresourceRange.levelCount = 1;
color_image_view_info.subresourceRange.baseArrayLayer = 0;
color_image_view_info.subresourceRange.layerCount = 1;
if (vkCreateImageView(device_, &color_image_view_info, nullptr,
&color_image_view_) != VK_SUCCESS) {
std::cerr << "Could not create color image view." << std::endl;
return false;
}
VkFormat depth_format = FindDepthFormat(physical_device_);
if (depth_format == VK_FORMAT_UNDEFINED) {
std::cerr << "Could not find suitable depth format." << std::endl;
return false;
}
VkImageCreateInfo depth_image_info{};
depth_image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
depth_image_info.imageType = VK_IMAGE_TYPE_2D;
depth_image_info.extent.width = swap_chain_extent_.width;
depth_image_info.extent.height = swap_chain_extent_.height;
depth_image_info.extent.depth = 1;
depth_image_info.mipLevels = 1;
depth_image_info.arrayLayers = 1;
depth_image_info.format = depth_format;
depth_image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
depth_image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depth_image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
depth_image_info.samples = msaa_sample_count_;
depth_image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (!utils::vk::CreateImage(depth_image_info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
physical_device_, device_, depth_image_,
depth_image_memory_)) {
std::cerr << "Could not create depth image." << std::endl;
return false;
}
VkImageViewCreateInfo depth_image_view_info{};
depth_image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
depth_image_view_info.image = depth_image_;
depth_image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
depth_image_view_info.format = depth_format;
depth_image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
depth_image_view_info.subresourceRange.baseMipLevel = 0;
depth_image_view_info.subresourceRange.levelCount = 1;
depth_image_view_info.subresourceRange.baseArrayLayer = 0;
depth_image_view_info.subresourceRange.layerCount = 1;
if (vkCreateImageView(device_, &depth_image_view_info, nullptr,
&depth_image_view_) != VK_SUCCESS) {
std::cerr << "Could not create depth image view." << std::endl;
return false;
}
swap_chain_framebuffers_.resize(swap_chain_images_.size());
for (int i = 0; i < swap_chain_images_.size(); ++i) {
VkImageView attachments[] = {
color_image_view_, depth_image_view_, swap_chain_image_views_[i]
};
VkFramebufferCreateInfo framebuffer_info{};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = render_pass_;
framebuffer_info.attachmentCount = 3;
framebuffer_info.pAttachments = attachments;
framebuffer_info.width = swap_chain_extent_.width;
framebuffer_info.height = swap_chain_extent_.height;
framebuffer_info.layers = 1;
if (vkCreateFramebuffer(device_, &framebuffer_info, nullptr,
&swap_chain_framebuffers_[i]) != VK_SUCCESS) {
std::cerr << "Could not create framebuffer." << std::endl;
return false;
}
}
return true;
}
bool App::CreateShadowPassResources() {
if (!CreateShadowRenderPass())
return false;
if (!CreateShadowPipeline())
return false;
if (!CreateShadowFramebuffers())
return false;
return true;
}
bool App::CreateShadowRenderPass() {
VkFormat depth_format = FindDepthFormat(physical_device_);
if (depth_format == VK_FORMAT_UNDEFINED) {
std::cerr << "Could not find suitable depth format." << std::endl;
return false;
}
VkAttachmentDescription depth_attachment{};
depth_attachment.format = depth_format;
depth_attachment.samples = VK_SAMPLE_COUNT_1_BIT;
depth_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depth_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depth_attachment.finalLayout =
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_attachment_ref{};
depth_attachment_ref.attachment = 0;
depth_attachment_ref.layout =
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.pDepthStencilAttachment = &depth_attachment_ref;
VkSubpassDependency subpass_dep{};
subpass_dep.srcSubpass = VK_SUBPASS_EXTERNAL;
subpass_dep.dstSubpass = 0;
subpass_dep.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
subpass_dep.srcAccessMask = 0;
subpass_dep.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
subpass_dep.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo render_pass_info{};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_info.attachmentCount = 1;
render_pass_info.pAttachments = &depth_attachment;
render_pass_info.subpassCount = 1;
render_pass_info.pSubpasses = &subpass;
render_pass_info.dependencyCount = 1;
render_pass_info.pDependencies = &subpass_dep;
if (vkCreateRenderPass(device_, &render_pass_info, nullptr,
&shadow_render_pass_) != VK_SUCCESS) {
std::cerr << "Could not create shadow render pass." << std::endl;
return false;
}
return true;
}
bool App::CreateShadowPipeline() {
std::vector<std::string> shader_file_paths = {
"shadow_vert.spv", "shadow_frag.spv"
};
std::vector<VkShaderModule> shader_modules;
if (!utils::vk::CreateShaderModulesFromFiles(shader_file_paths, device_,
&shader_modules)) {
std::cerr << "Could not create shadow shader modules." << std::endl;
return false;
}
VkPipelineShaderStageCreateInfo vert_shader_info{};
vert_shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vert_shader_info.stage = VK_SHADER_STAGE_VERTEX_BIT;
vert_shader_info.module = shader_modules[0];
vert_shader_info.pName = "main";
VkPipelineShaderStageCreateInfo frag_shader_info{};
frag_shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
frag_shader_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
frag_shader_info.module = shader_modules[1];
frag_shader_info.pName = "main";
VkPipelineShaderStageCreateInfo shader_stages[] = {
vert_shader_info, frag_shader_info
};
VkDescriptorSetLayoutBinding vert_ubo_binding{};
vert_ubo_binding.binding = 0;
vert_ubo_binding.descriptorCount = 1;
vert_ubo_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
vert_ubo_binding.pImmutableSamplers = nullptr;
vert_ubo_binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
VkDescriptorSetLayoutCreateInfo descriptor_layout_info{};
descriptor_layout_info.sType =
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptor_layout_info.bindingCount = 1;
descriptor_layout_info.pBindings = &vert_ubo_binding;
if (vkCreateDescriptorSetLayout(device_, &descriptor_layout_info, nullptr,
&shadow_descriptor_layout_) != VK_SUCCESS) {
std::cerr << "Could not create shadow descriptor set layout." << std::endl;
return false;
}
VkVertexInputBindingDescription vertex_pos_binding{};
vertex_pos_binding.binding = 0;
vertex_pos_binding.stride = sizeof(glm::vec3);
vertex_pos_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
VkVertexInputAttributeDescription vertex_pos_desc{};
vertex_pos_desc.binding = 0;
vertex_pos_desc.location = 0;
vertex_pos_desc.format = VK_FORMAT_R32G32B32_SFLOAT;
vertex_pos_desc.offset = 0;
VkPipelineVertexInputStateCreateInfo vertex_input{};
vertex_input.sType =
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input.vertexBindingDescriptionCount = 1;
vertex_input.pVertexBindingDescriptions = &vertex_pos_binding;
vertex_input.vertexAttributeDescriptionCount = 1;
vertex_input.pVertexAttributeDescriptions = &vertex_pos_desc;
VkPipelineInputAssemblyStateCreateInfo input_assembly{};
input_assembly.sType =
VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
input_assembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = static_cast<float>(kShadowTextureWidth);
viewport.height = static_cast<float>(kShadowTextureHeight);
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
VkRect2D scissor{};
scissor.offset = {0, 0};
scissor.extent = {kShadowTextureWidth, kShadowTextureHeight};
VkPipelineViewportStateCreateInfo viewport_info{};
viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_info.viewportCount = 1;
viewport_info.pViewports = &viewport;
viewport_info.scissorCount = 1;
viewport_info.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType =
VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineDepthStencilStateCreateInfo depth_stencil{};
depth_stencil.sType =
VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depth_stencil.depthTestEnable = VK_TRUE;
depth_stencil.depthWriteEnable = VK_TRUE;
depth_stencil.depthCompareOp = VK_COMPARE_OP_LESS;
depth_stencil.depthBoundsTestEnable = VK_FALSE;
depth_stencil.stencilTestEnable = VK_FALSE;
VkPushConstantRange push_constant_range{};
push_constant_range.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
push_constant_range.offset = 0;
push_constant_range.size = sizeof(glm::mat4);
VkPipelineLayoutCreateInfo pipeline_layout_info{};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.pushConstantRangeCount = 1;
pipeline_layout_info.pPushConstantRanges = &push_constant_range;
if (vkCreatePipelineLayout(device_, &pipeline_layout_info, nullptr,
&shadow_pipeline_layout_) != VK_SUCCESS) {
std::cerr << "Could not create shadow pipeline layout." << std::endl;
return false;
}
VkGraphicsPipelineCreateInfo pipeline_info{};
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.stageCount = 2;
pipeline_info.pStages = shader_stages;
pipeline_info.pVertexInputState = &vertex_input;
pipeline_info.pInputAssemblyState = &input_assembly;
pipeline_info.pViewportState = &viewport_info;
pipeline_info.pRasterizationState = &rasterizer;
pipeline_info.pMultisampleState = &multisampling;
pipeline_info.pDepthStencilState = &depth_stencil;
pipeline_info.layout = shadow_pipeline_layout_;
pipeline_info.renderPass = shadow_render_pass_;
pipeline_info.subpass = 0;
pipeline_info.basePipelineHandle = VK_NULL_HANDLE;
if (vkCreateGraphicsPipelines(device_, VK_NULL_HANDLE, 1, &pipeline_info,
nullptr, &shadow_pipeline_) != VK_SUCCESS) {
std::cerr << "Could not create shadow pipeline." << std::endl;
return false;
}
for (VkShaderModule shader_module : shader_modules) {
vkDestroyShaderModule(device_, shader_module, nullptr);
}
return true;
}
bool App::CreateShadowFramebuffers() {
VkFormat depth_format = FindDepthFormat(physical_device_);
if (depth_format == VK_FORMAT_UNDEFINED) {
std::cerr << "Could not find suitable depth format." << std::endl;
return false;
}
shadow_frame_resources_.resize(swap_chain_images_.size());
for (ShadowPassFrameResource& frame : shadow_frame_resources_) {
VkImageCreateInfo shadow_tex_info{};
shadow_tex_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
shadow_tex_info.imageType = VK_IMAGE_TYPE_2D;
shadow_tex_info.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
shadow_tex_info.extent.width = kShadowTextureWidth;
shadow_tex_info.extent.height = kShadowTextureHeight;
shadow_tex_info.extent.depth = 1;
shadow_tex_info.mipLevels = 1;
shadow_tex_info.arrayLayers = 6;
shadow_tex_info.format = depth_format;
shadow_tex_info.tiling = VK_IMAGE_TILING_OPTIMAL;
shadow_tex_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
shadow_tex_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
VK_IMAGE_USAGE_SAMPLED_BIT;
shadow_tex_info.samples = VK_SAMPLE_COUNT_1_BIT;
shadow_tex_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (!utils::vk::CreateImage(shadow_tex_info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
physical_device_, device_, frame.shadow_texture,
frame.shadow_texture_memory)) {
std::cerr << "Could not create shadow image." << std::endl;
return false;
}
frame.depth_framebuffer_views.resize(6);
frame.depth_framebuffers.resize(6);
for (int i = 0; i < frame.depth_framebuffer_views.size(); ++i) {
VkImageViewCreateInfo image_view_info{};
image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_info.image = frame.shadow_texture;
image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
image_view_info.format = depth_format;
image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
image_view_info.subresourceRange.baseMipLevel = 0;
image_view_info.subresourceRange.levelCount = 1;
image_view_info.subresourceRange.baseArrayLayer = i;
image_view_info.subresourceRange.layerCount = 1;
if (vkCreateImageView(device_, &image_view_info, nullptr,
&frame.depth_framebuffer_views[i]) != VK_SUCCESS) {
std::cerr << "Could not create shadow image framebuffer view."
<< std::endl;
return false;
}
VkFramebufferCreateInfo framebuffer_info{};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = shadow_render_pass_;
framebuffer_info.attachmentCount = 1;
framebuffer_info.pAttachments = &frame.depth_framebuffer_views[i];
framebuffer_info.width = kShadowTextureWidth;
framebuffer_info.height = kShadowTextureHeight;
framebuffer_info.layers = 1;
if (vkCreateFramebuffer(device_, &framebuffer_info, nullptr,
&frame.depth_framebuffers[i]) != VK_SUCCESS) {
std::cerr << "Could not create framebuffer." << std::endl;
return false;
}
}
VkImageViewCreateInfo shadow_tex_view_info{};
shadow_tex_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
shadow_tex_view_info.image = frame.shadow_texture;
shadow_tex_view_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
shadow_tex_view_info.format = depth_format;
shadow_tex_view_info.subresourceRange.aspectMask =
VK_IMAGE_ASPECT_DEPTH_BIT;
shadow_tex_view_info.subresourceRange.baseMipLevel = 0;
shadow_tex_view_info.subresourceRange.levelCount = 1;
shadow_tex_view_info.subresourceRange.baseArrayLayer = 0;
shadow_tex_view_info.subresourceRange.layerCount = 6;
if (vkCreateImageView(device_, &shadow_tex_view_info, nullptr,
&frame.shadow_texture_view) != VK_SUCCESS) {
std::cerr << "Could not create shadow texture view." << std::endl;
return false;
}
}
return true;
}
bool App::CreateCommandPool() {
VkCommandPoolCreateInfo command_pool_info{};
command_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
command_pool_info.queueFamilyIndex = graphics_queue_index_;
command_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
if (vkCreateCommandPool(device_, &command_pool_info, nullptr, &command_pool_)
!= VK_SUCCESS) {
std::cerr << "Could not create command pool." << std::endl;
return false;
}
return true;
}
bool App::CreateCommandBuffers() {
command_buffers_.resize(swap_chain_framebuffers_.size());
VkCommandBufferAllocateInfo command_buffer_info{};
command_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_info.commandPool = command_pool_;
command_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
command_buffer_info.commandBufferCount =
static_cast<uint32_t>(command_buffers_.size());
if (vkAllocateCommandBuffers(device_, &command_buffer_info,
command_buffers_.data()) != VK_SUCCESS) {
std::cerr << "Could not create command buffers." << std::endl;
return false;
}
return true;
}
bool App::CreateDescriptorSets() {
VkDescriptorPoolSize uniform_buffer_pool_size{};
uniform_buffer_pool_size.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uniform_buffer_pool_size.descriptorCount =
static_cast<uint32_t>(swap_chain_images_.size()) * 2;
VkDescriptorPoolSize combined_sampler_pool_size{};
combined_sampler_pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
combined_sampler_pool_size.descriptorCount =
static_cast<uint32_t>(swap_chain_images_.size());
VkDescriptorPoolSize pool_sizes[] = {
uniform_buffer_pool_size, combined_sampler_pool_size
};
VkDescriptorPoolCreateInfo pool_info{};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
pool_info.poolSizeCount = 2;
pool_info.pPoolSizes = pool_sizes;
pool_info.maxSets = static_cast<uint32_t>(swap_chain_images_.size());
if (vkCreateDescriptorPool(device_, &pool_info, nullptr, &descriptor_pool_)
!= VK_SUCCESS) {
std::cerr << "Could not create descriptor pool." << std::endl;
return false;
}
std::vector<VkDescriptorSetLayout> layouts(swap_chain_images_.size(),
descriptor_set_layout_);
VkDescriptorSetAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.descriptorPool = descriptor_pool_;
alloc_info.descriptorSetCount = static_cast<uint32_t>(
swap_chain_images_.size());
alloc_info.pSetLayouts = layouts.data();
descriptor_sets_.resize(swap_chain_images_.size());
if (vkAllocateDescriptorSets(device_, &alloc_info, descriptor_sets_.data())
!= VK_SUCCESS) {
std::cerr << "Could not create descriptor sets." << std::endl;
return false;
}
model_mat_ = glm::mat4(1.f);
glm::vec3 light_pos = glm::vec3(0.f, 1.9f, 0.f);
float shadow_tex_aspect_ratio = static_cast<float>(kShadowTextureWidth) /
static_cast<float>(kShadowTextureHeight);
glm::mat4 pos_z_view_mat =
glm::rotate(glm::mat4(1.f), kPi, glm::vec3(0.f, 1.f, 0.f)) *
glm::translate(glm::mat4(1.f), -light_pos);
glm::mat4 shadow_proj_mat = glm::perspective(glm::radians(90.f),
shadow_tex_aspect_ratio,
kShadowPassNearPlane,
kShadowPassFarPlane);
shadow_proj_mat[1][1] *= -1;
// Cubemap faces are in left-handed coordinates. E.g. +x is to the right
// of +z in a cubemap while +x is to the left of +z in Vulkan.
std::vector<glm::mat4> shadow_view_mats(6);
shadow_view_mats[0] = // Right (+x)
glm::rotate(glm::mat4(1.f), kPi / 2.f, glm::vec3(0.f, 1.f, 0.f)) *
pos_z_view_mat;
shadow_view_mats[1] = // Left (-x)
glm::rotate(glm::mat4(1.f), -kPi / 2.f, glm::vec3(0.f, 1.f, 0.f)) *
pos_z_view_mat;
shadow_view_mats[2] = // Top (+y)
glm::rotate(glm::mat4(1.f), -kPi / 2.f, glm::vec3(1.f, 0.f, 0.f)) *
pos_z_view_mat;
shadow_view_mats[3] = // Bottom (-y)
glm::rotate(glm::mat4(1.f), kPi / 2.f, glm::vec3(1.f, 0.f, 0.f)) *
pos_z_view_mat;
shadow_view_mats[4] = pos_z_view_mat; // Front (+z)
shadow_view_mats[5] = // Back (-z)
glm::rotate(glm::mat4(1.f), kPi, glm::vec3(0.f, 1.f, 0.f)) *
pos_z_view_mat;
shadow_mats_.resize(6);
for (int i = 0; i < shadow_mats_.size(); ++i) {
shadow_mats_[i] = shadow_proj_mat * shadow_view_mats[i] * model_mat_;
}
vert_ubo_buffers_.resize(swap_chain_images_.size());
vert_ubo_buffers_memory_.resize(swap_chain_images_.size());
for (size_t i = 0; i < swap_chain_images_.size(); i++) {
VkBufferCreateInfo vert_ubo_buffer_info{};
vert_ubo_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
vert_ubo_buffer_info.size = sizeof(VertexShaderUbo);
vert_ubo_buffer_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
vert_ubo_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(vert_ubo_buffer_info,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
physical_device_, device_, vert_ubo_buffers_[i],
vert_ubo_buffers_memory_[i]);
}
struct Material {
glm::vec4 ambient_color;
glm::vec4 diffuse_color;
};
struct FragmentShaderUbo {
glm::vec4 light_pos;
float shadow_near_plane;
float shadow_far_plane;
glm::vec2 pad;
Material materials[20];
} frag_ubo_data;
frag_ubo_data.light_pos = glm::vec4(light_pos, 0.f);
frag_ubo_data.shadow_near_plane = kShadowPassNearPlane;
frag_ubo_data.shadow_far_plane = kShadowPassFarPlane;
for (int i = 0; i < model_.materials.size(); ++i) {
frag_ubo_data.materials[i].ambient_color =
glm::vec4(model_.materials[i].ambient_color, 0.f);
frag_ubo_data.materials[i].diffuse_color =
glm::vec4(model_.materials[i].diffuse_color, 0.f);
}
frag_ubo_buffers_.resize(swap_chain_images_.size());
frag_ubo_buffers_memory_.resize(swap_chain_images_.size());
VkDeviceSize frag_ubo_buffer_size = sizeof(FragmentShaderUbo);
for (size_t i = 0; i < swap_chain_images_.size(); i++) {
VkBufferCreateInfo vert_ubo_buffer_info{};
vert_ubo_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
vert_ubo_buffer_info.size = frag_ubo_buffer_size;
vert_ubo_buffer_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
vert_ubo_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(vert_ubo_buffer_info,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
physical_device_, device_, frag_ubo_buffers_[i],
frag_ubo_buffers_memory_[i]);
FragmentShaderUbo* ubo_ptr;
vkMapMemory(device_, frag_ubo_buffers_memory_[i], 0, frag_ubo_buffer_size,
0, reinterpret_cast<void**>(&ubo_ptr));
*ubo_ptr = frag_ubo_data;
vkUnmapMemory(device_, frag_ubo_buffers_memory_[i]);
VkDescriptorBufferInfo descriptor_buffer_info{};
descriptor_buffer_info.buffer = frag_ubo_buffers_[i];
descriptor_buffer_info.offset = 0;
descriptor_buffer_info.range = frag_ubo_buffer_size;
VkWriteDescriptorSet descriptor_write{};
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = descriptor_sets_[i];
descriptor_write.dstBinding = 1;
descriptor_write.dstArrayElement = 0;
descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptor_write.descriptorCount = 1;
descriptor_write.pBufferInfo = &descriptor_buffer_info;
vkUpdateDescriptorSets(device_, 1, &descriptor_write, 0, nullptr);
}
VkPhysicalDeviceProperties phys_device_props{};
vkGetPhysicalDeviceProperties(physical_device_, &phys_device_props);
VkSamplerCreateInfo sampler_info{};
sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
sampler_info.magFilter = VK_FILTER_LINEAR;
sampler_info.minFilter = VK_FILTER_LINEAR;
sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_info.anisotropyEnable = VK_TRUE;
sampler_info.maxAnisotropy = phys_device_props.limits.maxSamplerAnisotropy;
sampler_info.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
sampler_info.unnormalizedCoordinates = VK_FALSE;
sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
if (vkCreateSampler(device_, &sampler_info, nullptr, &shadow_texture_sampler_)
!= VK_SUCCESS) {
std::cerr << "Could not create shadow texture sampler." << std::endl;
return false;
}
for (int i = 0; i < swap_chain_images_.size(); i++) {
VkDescriptorImageInfo image_info{};
image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
image_info.imageView = shadow_frame_resources_[i].shadow_texture_view;
image_info.sampler = shadow_texture_sampler_;
VkWriteDescriptorSet descriptor_write{};
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = descriptor_sets_[i];
descriptor_write.dstBinding = 2;
descriptor_write.dstArrayElement = 0;
descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptor_write.descriptorCount = 1;
descriptor_write.pImageInfo = &image_info;
vkUpdateDescriptorSets(device_, 1, &descriptor_write, 0, nullptr);
}
return true;
}
void App::UpdateScenePassMatrices(int frame_index) {
float aspect_ratio = static_cast<float>(swap_chain_extent_.width) /
static_cast<float>(swap_chain_extent_.height);
glm::mat4 view_mat = camera_.GetViewMat();
glm::mat4 proj_mat = glm::perspective(glm::radians(45.f), aspect_ratio, 0.1f,
100.f);
proj_mat[1][1] *= -1;
VkDeviceSize vert_ubo_buffer_size = sizeof(VertexShaderUbo);
VertexShaderUbo* ubo_ptr;
vkMapMemory(device_, vert_ubo_buffers_memory_[frame_index], 0,
vert_ubo_buffer_size, 0, reinterpret_cast<void**>(&ubo_ptr));
ubo_ptr->model_mat = model_mat_;
ubo_ptr->mvp_mat = proj_mat * view_mat * model_mat_;
vkUnmapMemory(device_, vert_ubo_buffers_memory_[frame_index]);
VkDescriptorBufferInfo descriptor_buffer_info{};
descriptor_buffer_info.buffer = vert_ubo_buffers_[frame_index];
descriptor_buffer_info.offset = 0;
descriptor_buffer_info.range = vert_ubo_buffer_size;
VkWriteDescriptorSet descriptor_write{};
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = descriptor_sets_[frame_index];
descriptor_write.dstBinding = 0;
descriptor_write.dstArrayElement = 0;
descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptor_write.descriptorCount = 1;
descriptor_write.pBufferInfo = &descriptor_buffer_info;
vkUpdateDescriptorSets(device_, 1, &descriptor_write, 0, nullptr);
}
bool App::CreateVertexBuffers() {
VkDeviceSize pos_buffer_size =
sizeof(glm::vec3) * model_.positions.size();
VkBufferCreateInfo pos_buffer_info{};
pos_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
pos_buffer_info.size = pos_buffer_size;
pos_buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
pos_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(pos_buffer_info, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
physical_device_, device_, position_buffer_,
position_buffer_memory_);
UploadDataToBuffer(model_.positions.data(), pos_buffer_size,
position_buffer_);
VkDeviceSize normal_buffer_size =
sizeof(glm::vec3) * model_.normals.size();
VkBufferCreateInfo normal_buffer_info{};
normal_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
normal_buffer_info.size = normal_buffer_size;
normal_buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
normal_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(normal_buffer_info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, physical_device_,
device_, normal_buffer_, normal_buffer_memory_);
UploadDataToBuffer(model_.normals.data(), normal_buffer_size,
normal_buffer_);
VkDeviceSize mtl_idx_buffer_size =
sizeof(uint32_t) * model_.material_indices.size();
VkBufferCreateInfo mtl_idx_buffer_info{};
mtl_idx_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
mtl_idx_buffer_info.size = mtl_idx_buffer_size;
mtl_idx_buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
mtl_idx_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(mtl_idx_buffer_info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, physical_device_,
device_, material_idx_buffer_,
material_idx_buffer_memory_);
UploadDataToBuffer(model_.material_indices.data(), mtl_idx_buffer_size,
material_idx_buffer_);
VkDeviceSize index_buffer_size =
sizeof(uint16_t) * model_.index_buffer.size();
VkBufferCreateInfo index_buffer_info{};
index_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
index_buffer_info.size = index_buffer_size;
index_buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
index_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(index_buffer_info,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, physical_device_,
device_, index_buffer_, index_buffer_memory_);
UploadDataToBuffer(model_.index_buffer.data(), index_buffer_size,
index_buffer_);
return true;
}
void App::UploadDataToBuffer(void* data, VkDeviceSize size, VkBuffer buffer) {
VkCommandBufferAllocateInfo command_buffer_info{};
command_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_info.commandPool = command_pool_;
command_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
command_buffer_info.commandBufferCount = 1;
VkCommandBuffer command_buffer;
vkAllocateCommandBuffers(device_, &command_buffer_info, &command_buffer);
VkCommandBufferBeginInfo commands_begin_info{};
commands_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
commands_begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(command_buffer, &commands_begin_info);
VkBuffer staging_buffer;
VkDeviceMemory staging_buffer_memory;
VkBufferCreateInfo staging_buffer_info{};
staging_buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
staging_buffer_info.size = size;
staging_buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
staging_buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
utils::vk::CreateBuffer(staging_buffer_info,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
physical_device_, device_, staging_buffer,
staging_buffer_memory);
void* staging_ptr;
vkMapMemory(device_, staging_buffer_memory, 0, size, 0, &staging_ptr);
memcpy(staging_ptr, data, static_cast<size_t>(size));
vkUnmapMemory(device_, staging_buffer_memory);
VkBufferCopy copy_info{};
copy_info.size = size;
vkCmdCopyBuffer(command_buffer, staging_buffer, buffer, 1, ©_info);
vkEndCommandBuffer(command_buffer);
VkSubmitInfo commands_submit_info{};
commands_submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
commands_submit_info.commandBufferCount = 1;
commands_submit_info.pCommandBuffers = &command_buffer;
vkQueueSubmit(graphics_queue_, 1, &commands_submit_info, VK_NULL_HANDLE);
vkQueueWaitIdle(graphics_queue_);
vkDestroyBuffer(device_, staging_buffer, nullptr);
vkFreeMemory(device_, staging_buffer_memory, nullptr);
vkFreeCommandBuffers(device_, command_pool_, 1, &command_buffer);
}
bool App::RecordCommandBuffer(int frame_index) {
VkCommandBuffer command_buffer = command_buffers_[frame_index];
vkResetCommandBuffer(command_buffer, 0);
VkCommandBufferBeginInfo begin_info{};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
if (vkBeginCommandBuffer(command_buffer, &begin_info) != VK_SUCCESS) {
std::cerr << "Could not begin command buffer." << std::endl;
return false;
}
TransitionShadowTextureForShadowPass(command_buffer, frame_index);
RecordShadowPassCommands(command_buffer, frame_index);
TransitionShadowTextureForScenePass(command_buffer, frame_index);
RecordScenePassCommands(command_buffer, frame_index);
if (vkEndCommandBuffer(command_buffer) != VK_SUCCESS) {
std::cerr << "Could not end command buffer." << std::endl;
return false;
}
return true;
}
void App::TransitionShadowTextureForShadowPass(VkCommandBuffer command_buffer,
int frame_index) {
ShadowPassFrameResource& frame = shadow_frame_resources_[frame_index];
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = frame.shadow_texture;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 6;
vkCmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, 0, 0,
nullptr, 0, nullptr, 1, &barrier);
}
void App::RecordShadowPassCommands(VkCommandBuffer command_buffer,
int frame_index) {
ShadowPassFrameResource& frame = shadow_frame_resources_[frame_index];
for (int i = 0; i < frame.depth_framebuffers.size(); ++i) {
VkClearValue clear_value{};
clear_value.depthStencil = {1.0f, 0};
VkRenderPassBeginInfo render_pass_begin_info{};
render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_begin_info.renderPass = shadow_render_pass_;
render_pass_begin_info.framebuffer = frame.depth_framebuffers[i];
render_pass_begin_info.renderArea.offset = {0, 0};
render_pass_begin_info.renderArea.extent = {
kShadowTextureWidth, kShadowTextureHeight
};
render_pass_begin_info.clearValueCount = 1;
render_pass_begin_info.pClearValues = &clear_value;
vkCmdBeginRenderPass(command_buffer, &render_pass_begin_info,
VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
shadow_pipeline_);
vkCmdPushConstants(command_buffer, shadow_pipeline_layout_,
VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(glm::mat4),
&shadow_mats_[i]);
VkBuffer vertex_buffers[] = { position_buffer_ };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, offsets);
vkCmdBindIndexBuffer(command_buffer, index_buffer_, 0,
VK_INDEX_TYPE_UINT16);
vkCmdDrawIndexed(command_buffer, model_.index_buffer.size(), 1, 0, 0, 0);
vkCmdEndRenderPass(command_buffer);
}
}
void App::TransitionShadowTextureForScenePass(VkCommandBuffer command_buffer,
int frame_index) {
ShadowPassFrameResource& frame = shadow_frame_resources_[frame_index];
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = frame.shadow_texture;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 6;
vkCmdPipelineBarrier(command_buffer,
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr,
0, nullptr, 1, &barrier);
}
void App::RecordScenePassCommands(VkCommandBuffer command_buffer,
int frame_index) {
VkClearValue clear_values[2]{};
clear_values[0].color = {0.0f, 0.0f, 0.0f, 1.0f};
clear_values[1].depthStencil = {1.0f, 0};
VkRenderPassBeginInfo render_pass_begin_info{};
render_pass_begin_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_begin_info.renderPass = render_pass_;
render_pass_begin_info.framebuffer = swap_chain_framebuffers_[frame_index];
render_pass_begin_info.renderArea.offset = {0, 0};
render_pass_begin_info.renderArea.extent = swap_chain_extent_;
render_pass_begin_info.clearValueCount = 2;
render_pass_begin_info.pClearValues = clear_values;
vkCmdBeginRenderPass(command_buffer, &render_pass_begin_info,
VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
pipeline_);
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
pipeline_layout_, 0, 1,
&descriptor_sets_[frame_index], 0, nullptr);
VkBuffer vertex_buffers[] = {
position_buffer_, normal_buffer_, material_idx_buffer_
};
VkDeviceSize offsets[] = { 0, 0, 0 };
vkCmdBindVertexBuffers(command_buffer, 0, 3, vertex_buffers, offsets);
vkCmdBindIndexBuffer(command_buffer, index_buffer_, 0,
VK_INDEX_TYPE_UINT16);
vkCmdDrawIndexed(command_buffer, model_.index_buffer.size(), 1, 0, 0, 0);
vkCmdEndRenderPass(command_buffer);
}
bool App::CreateSyncObjects() {
image_ready_semaphores_.resize(kMaxFramesInFlight);
render_complete_semaphores_.resize(kMaxFramesInFlight);
frame_ready_fences_.resize(kMaxFramesInFlight);
image_rendered_fences_.resize(swap_chain_images_.size(), VK_NULL_HANDLE);
VkSemaphoreCreateInfo semaphore_info{};
semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fence_info{};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (int i = 0; i < kMaxFramesInFlight; i++) {
if (vkCreateSemaphore(device_, &semaphore_info, nullptr,
&image_ready_semaphores_[i]) != VK_SUCCESS ||
vkCreateSemaphore(device_, &semaphore_info, nullptr,
&render_complete_semaphores_[i]) != VK_SUCCESS ||
vkCreateFence(device_, &fence_info, nullptr,
&frame_ready_fences_[i]) != VK_SUCCESS) {
std::cerr << "Could not create sync objects." << std::endl;
return false;
}
}
return true;
}
void App::Destroy() {
for (int i = 0; i < kMaxFramesInFlight; i++) {
vkDestroySemaphore(device_, image_ready_semaphores_[i], nullptr);
vkDestroySemaphore(device_, render_complete_semaphores_[i], nullptr);
vkDestroyFence(device_, frame_ready_fences_[i], nullptr);
}
DestroyVertexBuffers();
DestroyDescriptorSets();
DestroyCommandBuffers();
DestroyCommandPool();
DestroyShadowPassResources();
DestroyScenePassResources();
DestroySwapChain();
vkDestroyDevice(device_, nullptr);
vkDestroySurfaceKHR(instance_, surface_, nullptr);
utils::vk::DestroyDebugUtilsMessenger(instance_, debug_messenger_, nullptr);
vkDestroyInstance(instance_, nullptr);
glfwDestroyWindow(window_);
glfwTerminate();
}
void App::DestroyVertexBuffers() {
vkDestroyBuffer(device_, index_buffer_, nullptr);
vkFreeMemory(device_, index_buffer_memory_, nullptr);
vkDestroyBuffer(device_, material_idx_buffer_, nullptr);
vkFreeMemory(device_, material_idx_buffer_memory_, nullptr);
vkDestroyBuffer(device_, normal_buffer_, nullptr);
vkFreeMemory(device_, normal_buffer_memory_, nullptr);
vkDestroyBuffer(device_, position_buffer_, nullptr);
vkFreeMemory(device_, position_buffer_memory_, nullptr);
}
void App::DestroyDescriptorSets() {
vkDestroySampler(device_, shadow_texture_sampler_, nullptr);
for (int i = 0; i < swap_chain_images_.size(); ++i) {
vkDestroyBuffer(device_, frag_ubo_buffers_[i], nullptr);
vkFreeMemory(device_, frag_ubo_buffers_memory_[i], nullptr);
}
frag_ubo_buffers_.clear();
frag_ubo_buffers_memory_.clear();
for (int i = 0; i < swap_chain_images_.size(); ++i) {
vkDestroyBuffer(device_, vert_ubo_buffers_[i], nullptr);
vkFreeMemory(device_, vert_ubo_buffers_memory_[i], nullptr);
}
vert_ubo_buffers_.clear();
vert_ubo_buffers_memory_.clear();
vkDestroyDescriptorPool(device_, descriptor_pool_, nullptr);
descriptor_sets_.clear();
}
void App::DestroyCommandBuffers() {
vkFreeCommandBuffers(device_, command_pool_, command_buffers_.size(),
command_buffers_.data());
command_buffers_.clear();
}
void App::DestroyCommandPool() {
vkDestroyCommandPool(device_, command_pool_, nullptr);
}
void App::DestroyShadowPassResources() {
for (ShadowPassFrameResource& frame : shadow_frame_resources_) {
vkDestroyImageView(device_, frame.shadow_texture_view, nullptr);
for (VkFramebuffer framebuffer : frame.depth_framebuffers) {
vkDestroyFramebuffer(device_, framebuffer, nullptr);
}
for (VkImageView image_view : frame.depth_framebuffer_views) {
vkDestroyImageView(device_, image_view, nullptr);
}
vkDestroyImage(device_, frame.shadow_texture, nullptr);
vkFreeMemory(device_, frame.shadow_texture_memory, nullptr);
}
shadow_frame_resources_.clear();
vkDestroyPipeline(device_, shadow_pipeline_, nullptr);
vkDestroyPipelineLayout(device_, shadow_pipeline_layout_, nullptr);
vkDestroyDescriptorSetLayout(device_, shadow_descriptor_layout_, nullptr);
vkDestroyRenderPass(device_, shadow_render_pass_, nullptr);
}
void App::DestroyScenePassResources() {
for (const auto& framebuffer : swap_chain_framebuffers_) {
vkDestroyFramebuffer(device_, framebuffer, nullptr);
}
swap_chain_framebuffers_.clear();
vkDestroyImageView(device_, color_image_view_, nullptr);
vkDestroyImage(device_, color_image_, nullptr);
vkFreeMemory(device_, color_image_memory_, nullptr);
vkDestroyImageView(device_, depth_image_view_, nullptr);
vkDestroyImage(device_, depth_image_, nullptr);
vkFreeMemory(device_, depth_image_memory_, nullptr);
vkDestroyPipeline(device_, pipeline_, nullptr);
vkDestroyPipelineLayout(device_, pipeline_layout_, nullptr);
vkDestroyDescriptorSetLayout(device_, descriptor_set_layout_, nullptr);
vkDestroyRenderPass(device_, render_pass_, nullptr);
}
void App::DestroySwapChain() {
for (const auto& image_view : swap_chain_image_views_) {
vkDestroyImageView(device_, image_view, nullptr);
}
swap_chain_image_views_.clear();
vkDestroySwapchainKHR(device_, swap_chain_, nullptr);
}
void App::MainLoop() {
current_frame_time_ = glfwGetTime();
while (!glfwWindowShouldClose(window_)) {
glfwPollEvents();
if (!DrawFrame())
break;
double previous_frame_time = current_frame_time_;
current_frame_time_ = glfwGetTime();
double time_elapsed = current_frame_time_ - previous_frame_time;
camera_.Tick(static_cast<float>(time_elapsed * 1000.0));
}
vkDeviceWaitIdle(device_);
}
bool App::DrawFrame() {
vkWaitForFences(device_, 1, &frame_ready_fences_[current_frame_], VK_TRUE,
UINT64_MAX);
uint32_t image_index;
VkResult result = vkAcquireNextImageKHR(
device_, swap_chain_, UINT64_MAX,
image_ready_semaphores_[current_frame_], VK_NULL_HANDLE, &image_index);
if (result == VK_ERROR_OUT_OF_DATE_KHR) {
RecreateSwapChain();
return true;
} else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
std::cerr << "Could not acquire image." << std::endl;
return false;
}
if (image_rendered_fences_[image_index] != VK_NULL_HANDLE) {
vkWaitForFences(device_, 1, &image_rendered_fences_[image_index], VK_TRUE,
UINT64_MAX);
}
image_rendered_fences_[image_index] = frame_ready_fences_[current_frame_];
vkResetFences(device_, 1, &frame_ready_fences_[current_frame_]);
UpdateScenePassMatrices(current_frame_);
if (!RecordCommandBuffer(current_frame_))
return false;
VkSemaphore submit_wait_semaphores[] = {
image_ready_semaphores_[current_frame_]
};
VkPipelineStageFlags submit_wait_stages[] = {
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
};
VkSemaphore submit_signal_semaphores[] = {
render_complete_semaphores_[current_frame_]
};
VkSubmitInfo queue_submit_info{};
queue_submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
queue_submit_info.waitSemaphoreCount = 1;
queue_submit_info.pWaitSemaphores = submit_wait_semaphores;
queue_submit_info.pWaitDstStageMask = submit_wait_stages;
queue_submit_info.commandBufferCount = 1;
queue_submit_info.pCommandBuffers = &command_buffers_[image_index];
queue_submit_info.signalSemaphoreCount = 1;
queue_submit_info.pSignalSemaphores = submit_signal_semaphores;
if (vkQueueSubmit(graphics_queue_, 1, &queue_submit_info,
frame_ready_fences_[current_frame_]) != VK_SUCCESS) {
std::cerr << "Could not submit to queue." << std::endl;
return false;
}
VkSemaphore present_wait_semaphores[] = {
render_complete_semaphores_[current_frame_]
};
VkSwapchainKHR swap_chains[] = { swap_chain_ };
VkPresentInfoKHR present_info{};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.waitSemaphoreCount = 1;
present_info.pWaitSemaphores = present_wait_semaphores;
present_info.swapchainCount = 1;
present_info.pSwapchains = &swap_chain_;
present_info.pImageIndices = &image_index;
result = vkQueuePresentKHR(present_queue_, &present_info);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR ||
framebuffer_resized_) {
framebuffer_resized_ = false;
RecreateSwapChain();
return true;
} else if (result != VK_SUCCESS) {
std::cerr << "Could not present to swap chain." << std::endl;
return false;
}
current_frame_ = (current_frame_ + 1) % kMaxFramesInFlight;
return true;
}
bool App::RecreateSwapChain() {
int width = 0;
int height = 0;
glfwGetFramebufferSize(window_, &width, &height);
while (width == 0 || height == 0) {
glfwGetFramebufferSize(window_, &width, &height);
glfwWaitEvents();
}
vkDeviceWaitIdle(device_);
DestroyDescriptorSets();
DestroyCommandBuffers();
DestroyShadowPassResources();
DestroyScenePassResources();
DestroySwapChain();
if (!CreateSwapChain())
return false;
if (!CreateScenePassResources())
return false;
if (!CreateShadowPassResources())
return false;
if (!CreateDescriptorSets())
return false;
if (!CreateCommandBuffers())
return false;
image_rendered_fences_.resize(swap_chain_images_.size(), VK_NULL_HANDLE);
return true;
}
| 37.66948
| 80
| 0.752467
|
colintan95
|
c058a1bd0854d48a90a2080ba554bdbce6f536e8
| 7,605
|
cpp
|
C++
|
IrrlichtOpenCVGlue/ConcurrentBlobDetection.cpp
|
wolfgang1991/CommonLibraries
|
949251019cc8dd532938d16ab85a4e772eb6817e
|
[
"Zlib"
] | null | null | null |
IrrlichtOpenCVGlue/ConcurrentBlobDetection.cpp
|
wolfgang1991/CommonLibraries
|
949251019cc8dd532938d16ab85a4e772eb6817e
|
[
"Zlib"
] | 1
|
2020-07-31T13:20:54.000Z
|
2020-08-06T15:45:39.000Z
|
IrrlichtOpenCVGlue/ConcurrentBlobDetection.cpp
|
wolfgang1991/CommonLibraries
|
949251019cc8dd532938d16ab85a4e772eb6817e
|
[
"Zlib"
] | null | null | null |
#include "ConcurrentBlobDetection.h"
#include "IrrCVImageConversion.h"
#include <timing.h>
#include <Threading.h>
#include <mathUtils.h>
#include <Matrix.h>
#include <opencv2/features2d.hpp>
using namespace cv;
using namespace irr;
using namespace core;
using namespace video;
class ConcurrentBlobDetectionPrivate{
public:
//! input
struct BlobDetectionParameters{
ConcurrentBlobDetection* detection;
irr::video::IImage* img;
cv::SimpleBlobDetector::Params params;
bool whiteOnBlack;//if false black on white
Matrix<2,3,double> homogenousCamTransform;
};
ThreadPool pool;
//may only be changed by the blob thread or if it is idle:
bool isNew;
std::vector<ConcurrentBlobDetection::Blob>* intermediateBlobs;
BlobDetectionParameters* params;
cv::SimpleBlobDetector::Params paramsToCopy;
bool whiteOnBlackToCopy;
double camRotationDegrees;
irr::f32 minArea, maxArea;
std::vector<ConcurrentBlobDetection::Blob>* currentBlobs;
static void* detectBlobs(void* params);
ConcurrentBlobDetectionPrivate():pool(1),isNew(false),intermediateBlobs(new std::vector<ConcurrentBlobDetection::Blob>()),params(NULL),paramsToCopy(),whiteOnBlackToCopy(false),camRotationDegrees(0.0),minArea(3.17891e-05),maxArea(0.0625),currentBlobs(new std::vector<ConcurrentBlobDetection::Blob>()){}
~ConcurrentBlobDetectionPrivate(){
while(pool.hasRunningThreads()){//wait until all is done
delay(10);
}
delete intermediateBlobs;
delete currentBlobs;
delete params;
}
};
ConcurrentBlobDetection::ConcurrentBlobDetection(){
prv = new ConcurrentBlobDetectionPrivate();
}
bool ConcurrentBlobDetection::update(){
bool running = prv->pool.hasRunningThreads();
if(!running){
if(prv->isNew){
auto tmp = prv->intermediateBlobs;
prv->intermediateBlobs = prv->currentBlobs;
prv->currentBlobs = tmp;
prv->isNew = false;
}
if(prv->params!=NULL){
running = prv->pool.startThreadedFunction(prv->detectBlobs, prv->params)!=NULL;
prv->params = NULL;
}
}
return !running;
}
const std::vector<ConcurrentBlobDetection::Blob>& ConcurrentBlobDetection::getCurrentBlobs() const{
return *prv->currentBlobs;
}
void ConcurrentBlobDetection::requestBlobDetection(irr::video::IImage* img){
assert(img->getReferenceCount()==1);
if(prv->params){prv->params->img->drop();}
delete prv->params;//delete old request
u32 totalArea = img->getDimension().getArea();
prv->paramsToCopy.minArea = prv->minArea*totalArea;
prv->paramsToCopy.maxArea = prv->maxArea*totalArea;
double cosPhi = cos(-prv->camRotationDegrees/DEG_RAD);
double sinPhi = sin(-prv->camRotationDegrees/DEG_RAD);
double t_x = -((double)img->getDimension().Width/2.0);
double t_y = -((double)img->getDimension().Height/2.0);
Matrix<2,3,double> homoTransform = {//(1) translation center->origin, (2) rotation, (3) translation origin->center
cosPhi, -sinPhi, -sinPhi*t_y+cosPhi*t_x-t_x,
sinPhi, cosPhi, cosPhi*t_y-t_y+sinPhi*t_x,
};
prv->params = new ConcurrentBlobDetectionPrivate::BlobDetectionParameters{this, img, prv->paramsToCopy, prv->whiteOnBlackToCopy, homoTransform};
}
void ConcurrentBlobDetection::setCameraRotationDegrees(double degrees){
prv->camRotationDegrees = degrees;
}
double ConcurrentBlobDetection::getCameraRotationDegrees() const{
return prv->camRotationDegrees;
}
irr::f32 ConcurrentBlobDetection::getMinAreaProportion() const{
return prv->minArea;
}
irr::f32 ConcurrentBlobDetection::getMaxAreaProportion() const{
return prv->maxArea;
}
void ConcurrentBlobDetection::setAreaProportion(irr::f32 minValue, irr::f32 maxValue){
prv->minArea = minValue;
prv->maxArea = maxValue;
}
bool ConcurrentBlobDetection::isFilterAreaEnabled() const{
return prv->paramsToCopy.filterByArea;
}
void ConcurrentBlobDetection::setFilterAreaEnabled(bool enabled){
prv->paramsToCopy.filterByArea = enabled;
}
void* ConcurrentBlobDetectionPrivate::detectBlobs(void* params){
BlobDetectionParameters* p = (BlobDetectionParameters*)params;
std::vector<ConcurrentBlobDetection::Blob>& blobs = *(p->detection->prv->intermediateBlobs);
blobs.clear();
Mat blobMat = p->whiteOnBlack?convertInverseImageToGrayscaleMat(p->img):convertImageToGrayscaleMat(p->img);
std::vector<KeyPoint> keypoints;// Detect blobs.
cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(p->params);
detector->detect(blobMat, keypoints);
blobs.reserve(keypoints.size());
//std::cout << "found blobs: " << keypoints.size() << std::endl;
for(uint32_t i=0; i<keypoints.size(); i++){
KeyPoint& kp = keypoints[i];
Vector2D<double> transformedBlob = p->homogenousCamTransform * Vector3D<double>(kp.pt.x, kp.pt.y, 1.0);
blobs.push_back(ConcurrentBlobDetection::Blob{vector2d<f32>(transformedBlob[0], transformedBlob[1]), kp.size});
//std::cout << "blob " << i << ": " << kp.pt.x << ", " << kp.pt.y << " angle: " << p.angle << " response: " << p.response << " size: " << p.size << std::endl;
}
p->detection->prv->isNew = true;
p->img->drop();
delete p;
return NULL;
}
ConcurrentBlobDetection::~ConcurrentBlobDetection(){
delete prv;
}
irr::f32 ConcurrentBlobDetection::getIntensity() const{
return ((f32)prv->paramsToCopy.blobColor)/255.f;
}
void ConcurrentBlobDetection::setIntensity(irr::f32 intensity){
prv->paramsToCopy.blobColor = Clamp(rd<f32,int>(intensity*255.f),0,255);
}
void ConcurrentBlobDetection::setFilterIntensityEnabled(bool enabled){
prv->paramsToCopy.filterByColor = enabled;
}
bool ConcurrentBlobDetection::isFilterIntensityEnabled() const{
return prv->paramsToCopy.filterByColor;
}
irr::f32 ConcurrentBlobDetection::getMinCircularity() const{
return prv->paramsToCopy.minCircularity;
}
irr::f32 ConcurrentBlobDetection::getMaxCircularity() const{
return prv->paramsToCopy.maxCircularity;
}
bool ConcurrentBlobDetection::isFilterCircularityEnabled() const{
return prv->paramsToCopy.filterByCircularity;
}
void ConcurrentBlobDetection::setCircularity(irr::f32 minValue, irr::f32 maxValue){
prv->paramsToCopy.minCircularity = minValue;
prv->paramsToCopy.maxCircularity = maxValue;
}
void ConcurrentBlobDetection::setFilterCircularityEnabled(bool enabled){
prv->paramsToCopy.filterByCircularity = enabled;
}
irr::f32 ConcurrentBlobDetection::getMinInertia() const{
return prv->paramsToCopy.minInertiaRatio;
}
irr::f32 ConcurrentBlobDetection::getMaxInertia() const{
return prv->paramsToCopy.maxInertiaRatio;
}
bool ConcurrentBlobDetection::isFilterInertiaEnabled() const{
return prv->paramsToCopy.filterByInertia;
}
void ConcurrentBlobDetection::setInertia(irr::f32 minValue, irr::f32 maxValue){
prv->paramsToCopy.minInertiaRatio = minValue;
prv->paramsToCopy.maxInertiaRatio = maxValue;
}
void ConcurrentBlobDetection::setFilterInertiaEnabled(bool enabled){
prv->paramsToCopy.filterByInertia = enabled;
}
irr::f32 ConcurrentBlobDetection::getMinConvexity() const{
return prv->paramsToCopy.minConvexity;
}
irr::f32 ConcurrentBlobDetection::getMaxConvexity() const{
return prv->paramsToCopy.maxConvexity;
}
bool ConcurrentBlobDetection::isFilterConvexityEnabled() const{
return prv->paramsToCopy.filterByConvexity;
}
void ConcurrentBlobDetection::setConvexity(irr::f32 minValue, irr::f32 maxValue){
prv->paramsToCopy.minConvexity = minValue;
prv->paramsToCopy.maxConvexity = maxValue;
}
void ConcurrentBlobDetection::setFilterConvexityEnabled(bool enabled){
prv->paramsToCopy.filterByConvexity = enabled;
}
void ConcurrentBlobDetection::setWhiteOnBlack(bool whiteOnBlack){
prv->whiteOnBlackToCopy = whiteOnBlack;
}
bool ConcurrentBlobDetection::isWhiteOnBlack() const{
return prv->whiteOnBlackToCopy;
}
| 31.296296
| 302
| 0.767258
|
wolfgang1991
|
c05c39e464ebdda3296cd9a293fcad4675004d27
| 3,977
|
hpp
|
C++
|
water/threads/posix/bits.hpp
|
watercpp/water
|
7a9a292a2513529cf5dabac1bc7a755055dac9b5
|
[
"MIT"
] | 5
|
2017-04-18T18:18:50.000Z
|
2018-08-03T09:13:26.000Z
|
water/threads/posix/bits.hpp
|
watercpp/water
|
7a9a292a2513529cf5dabac1bc7a755055dac9b5
|
[
"MIT"
] | null | null | null |
water/threads/posix/bits.hpp
|
watercpp/water
|
7a9a292a2513529cf5dabac1bc7a755055dac9b5
|
[
"MIT"
] | null | null | null |
// Copyright 2017 Johan Paulsson
// This file is part of the Water C++ Library. It is licensed under the MIT License.
// See the license.txt file in this distribution or https://watercpp.com/license.txt
//\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_
#ifndef WATER_THREADS_POSIX_BITS_HPP
#define WATER_THREADS_POSIX_BITS_HPP
#include <water/threads/bits.hpp>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h> // gettimeofday
//
// posix configuration macros
// they do not seem to work, probably needs some manual defines
//
// single unix version 7 has moved some things into base, like _POSIX_TIMEOUTS
//
// manual configuration:
// - #define WATER_POSIX_SOMETHING to always use
// - #define WATER_POSIX_NO_SOMETHING to never use (for testing)
//
// linux thread priority needs special permissions?
//
#if \
!defined(WATER_POSIX_BARRIERS) && \
!defined(WATER_POSIX_NO_BARRIERS) && \
((defined(_POSIX_BARRIERS) && _POSIX_BARRIERS > 0) || defined(PTHREAD_BARRIER_SERIAL_THREAD))
#define WATER_POSIX_BARRIERS
#endif
#if \
!defined(WATER_POSIX_PRIORITY_SCHEDULING) && \
!defined(WATER_POSIX_NO_PRIORITY_SCHEDULING) && \
(defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0)
#define WATER_POSIX_PRIORITY_SCHEDULING
#endif
#if \
!defined(WATER_POSIX_SEMAPHORES) && \
!defined(WATER_POSIX_NO_SEMAPHORES) && \
((defined(_POSIX_SEMAPHORES) && _POSIX_SEMAPHORES > 0) || defined(WATER_SYSTEM_LINUX))
#define WATER_POSIX_SEMAPHORES
// apple has them, but they are deprecated
#endif
#if \
!defined(WATER_POSIX_TIMEOUTS) && \
!defined(WATER_POSIX_NO_TIMEOUTS) && \
((defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS > 0) || defined(WATER_SYSTEM_LINUX))
#define WATER_POSIX_TIMEOUTS
#endif
#if \
!defined(WATER_POSIX_NANOSLEEP) && \
!defined(WATER_POSIX_NO_NANOSLEEP) && \
((defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0) || defined(WATER_SYSTEM_LINUX) || defined(WATER_SYSTEM_APPLE))
#define WATER_POSIX_NANOSLEEP
#endif
#if \
!defined(WATER_POSIX_CLOCK_NANOSLEEP) && \
!defined(WATER_POSIX_NO_CLOCK_NANOSLEEP) && \
((defined(_POSIX_CLOCK_SELECTION) && _POSIX_CLOCK_SELECTION > 0) || defined(WATER_SYSTEM_LINUX))
#define WATER_POSIX_CLOCK_NANOSLEEP
#endif
#if \
!defined(WATER_POSIX_THREAD_PRIORITY_SCHEDULING) && \
!defined(WATER_POSIX_NO_THREAD_PRIORITY_SCHEDULING) && \
((defined(_POSIX_THREAD_PRIORITY_SCHEDULING) && _POSIX_THREAD_PRIORITY_SCHEDULING > 0) || defined(WATER_SYSTEM_APPLE))
#define WATER_POSIX_THREAD_PRIORITY_SCHEDULING
#endif
#if \
!defined(WATER_POSIX_THREAD_ATTR_STACKSIZE) && \
!defined(WATER_POSIX_NO_THREAD_ATTR_STACKSIZE) && \
((defined(_POSIX_THREAD_ATTR_STACKSIZE) && _POSIX_THREAD_ATTR_STACKSIZE > 0) || defined(WATER_SYSTEM_LINUX) || defined(WATER_SYSTEM_APPLE))
#define WATER_POSIX_THREAD_ATTR_STACKSIZE
#endif
#if \
!defined(WATER_POSIX_MUTEX_RECURSIVE) && \
!defined(WATER_POSIX_NO_MUTEX_RECURSIVE) && \
(defined(_XOPEN_VERSION) || defined(PTHREAD_MUTEX_RECURSIVE))
#define WATER_POSIX_MUTEX_RECURSIVE
#endif
#if \
!defined(WATER_POSIX_CLOCK_REALTIME) && \
!defined(WATER_POSIX_NO_CLOCK_REALTIME) && \
defined(CLOCK_REALTIME)
#define WATER_POSIX_CLOCK_REALTIME
#endif
#if \
!defined(WATER_POSIX_CLOCK_MONOTONIC) && \
!defined(WATER_POSIX_NO_CLOCK_MONOTONIC) && \
defined(CLOCK_MONOTONIC)
#define WATER_POSIX_CLOCK_MONOTONIC
#endif
#ifdef WATER_THREADS_STATISTICS
#include <water/threads/statistics/statistics.hpp>
#endif
namespace water { namespace threads {
inline void timespec_add(timespec& t, double seconds) {
constexpr long nanosecond = 1000000000l;
long
s = static_cast<long>(seconds),
n = static_cast<long>((seconds - s) * 1e9);
if(s < 0) s = 0;
if(n < 0) n = 0;
else if(n >= nanosecond) n = nanosecond - 1;
t.tv_nsec += n;
if(t.tv_nsec >= nanosecond) {
++s;
t.tv_nsec -= nanosecond;
}
t.tv_sec += s;
}
}}
#endif
| 30.829457
| 139
| 0.742268
|
watercpp
|
c05de1ec4158415f333c96db4e70cff1ce3abcf5
| 2,327
|
cpp
|
C++
|
src/lexer.cpp
|
ollelogdahl/Inel
|
e731f57062340f3ab8648df27259ff50c41e8d97
|
[
"MIT"
] | null | null | null |
src/lexer.cpp
|
ollelogdahl/Inel
|
e731f57062340f3ab8648df27259ff50c41e8d97
|
[
"MIT"
] | null | null | null |
src/lexer.cpp
|
ollelogdahl/Inel
|
e731f57062340f3ab8648df27259ff50c41e8d97
|
[
"MIT"
] | null | null | null |
#include "lexer.h"
#include <iostream>
#include <fstream>
#include <map>
#include <regex>
const std::vector<std::pair<std::string, TokenType>> tokenRules {
// Keywords
{R"(if)", t_if},
{R"(while)", t_while},
{R"(return)", t_return},
{R"(new)", t_new},
// Literals and identifiers
{R"(-?[0-9]+)", t_int_literal},
{R"(".*")", t_str_literal},
{R"([a-zA-Z_][a-zA-Z0-9_]*)", t_identifier},
// Parenthesis
{R"(\()", t_lparen},
{R"(\))", t_rparen},
{R"(\[)", t_lbracket},
{R"(])", t_rbracket},
{R"(\{)", t_lcurly},
{R"(})", t_rcurly},
{R"(,)", t_comma},
{R"(;)", t_scolon},
// Modifiers
{R"(\+=)", t_peq},
{R"(-=)", t_meq},
{R"(\+\+)", t_inc},
{R"(--)", t_dec},
// Logical operators
{R"(!)", t_not},
{R"(&&)", t_and},
{R"(\|\|)", t_or},
{R"(==)", t_eq},
{R"(!=)", t_neq},
// Operators and assignment
{R"(=)", t_ass},
{R"(\+)", t_plus},
{R"(-)", t_minus},
{R"(\*)", t_ast},
{R"(&)", t_amp}
};
std::vector<Token> Lexer::tokenize(const std::string &text) {
// Merge all expressions into one
std::string expression;
for(auto const &rule : tokenRules)
expression += "(" + rule.first + ")|";
// remove the last | character
expression.pop_back();
// token vector
std::vector<Token> tokens;
// create regex engine
std::regex regex(expression, std::regex::extended);
auto wordsBegin = std::sregex_iterator(text.begin(), text.end(), regex);
auto wordsEnd = std::sregex_iterator();
for(auto it= wordsBegin; it != wordsEnd; ++it) {
unsigned index = 0;
for(; index < it->size(); ++index) {
if(!it->str(index + 1).empty())
break;
}
Token token = Token(tokenRules[index].second, it->str(), rand()%100, 0);
//std::cout << token.toString() << std::endl;
tokens.push_back(token);
}
return tokens;
}
| 28.036145
| 80
| 0.429738
|
ollelogdahl
|
c05ed29c262947d2d5ccf577e8cde98179d5d58b
| 2,057
|
cpp
|
C++
|
pronto/graphics/pc/d3d12_command_list.cpp
|
MgBag/pronto
|
c10827e094726d8dc285c3da68c9c03be42d9a32
|
[
"MIT"
] | null | null | null |
pronto/graphics/pc/d3d12_command_list.cpp
|
MgBag/pronto
|
c10827e094726d8dc285c3da68c9c03be42d9a32
|
[
"MIT"
] | null | null | null |
pronto/graphics/pc/d3d12_command_list.cpp
|
MgBag/pronto
|
c10827e094726d8dc285c3da68c9c03be42d9a32
|
[
"MIT"
] | null | null | null |
#include "d3d12_command_list.h"
#include "d3d12_dynamic_descriptor_heap.h"
#include "d3d12_upload_buffer.h"
#include "d3d12_constant_buffer_heap.h"
#include <assert.h>
namespace pronto
{
namespace graphics
{
//---------------------------------------------------------------------------------------------
CommandList::CommandList(
ID3D12Device2* device,
D3D12_COMMAND_LIST_TYPE type) :
type_(type),
device_(device)
{
assert(SUCCEEDED(
device_->CreateCommandAllocator(type_, IID_PPV_ARGS(&allocator_))));
assert(SUCCEEDED(
device_->CreateCommandList(
0,
type_,
allocator_,
nullptr,
IID_PPV_ARGS(&command_list_))));
dynamic_descriptor_heap_ = new DynamicDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, device_);
upload_buffer_ = new UploadBuffer(device_);
const_buffer_heap_ = new D3D12ConstantBufferHeap();
const_buffer_heap_->Create(device_);
}
void CommandList::SetGraphicsRootSignature(
ID3D12RootSignature* root_sig,
D3D12_ROOT_SIGNATURE_DESC1 desc,
uint32_t bit_mask,
uint32_t num_desc)
{
dynamic_descriptor_heap_->ParseRootSignature(desc, bit_mask, num_desc);
command_list_->SetGraphicsRootSignature(root_sig);
}
ID3D12GraphicsCommandList* CommandList::command_list()
{
return command_list_;
}
DynamicDescriptorHeap* CommandList::descriptor_heap()
{
return dynamic_descriptor_heap_;
}
UploadBuffer* CommandList::upload_buffer()
{
return upload_buffer_;
}
D3D12ConstantBufferHeap* CommandList::const_buffer_heap()
{
return const_buffer_heap_;
}
ID3D12Device2* CommandList::device()
{
return device_;
}
void CommandList::Reset()
{
assert(SUCCEEDED(allocator_->Reset()));
assert(SUCCEEDED(command_list_->Reset(allocator_, nullptr)));
upload_buffer_->Reset();
dynamic_descriptor_heap_->Reset();
}
}
}
| 24.488095
| 108
| 0.64317
|
MgBag
|
c063e89d5aaa02126820d42a1b320a76ff0b9729
| 1,101
|
cpp
|
C++
|
src_smartcontract_db/schema_table/record/table_record_local/LocalCdbOid.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 6
|
2019-01-06T05:02:39.000Z
|
2020-10-01T11:45:32.000Z
|
src_smartcontract_db/schema_table/record/table_record_local/LocalCdbOid.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 209
|
2018-05-18T03:07:02.000Z
|
2022-03-26T11:42:41.000Z
|
src_smartcontract_db/schema_table/record/table_record_local/LocalCdbOid.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | 3
|
2019-07-06T09:16:36.000Z
|
2020-10-15T08:23:28.000Z
|
/*
* LocalCdbOid.cpp
*
* Created on: 2020/09/25
* Author: iizuka
*/
#include "schema_table/record/table_record_local/LocalCdbOid.h"
#include "schema_table/record/table_record_value/VmInstanceValueConverter.h"
namespace codablecash {
LocalCdbOid::LocalCdbOid(const LocalCdbOid& inst) : CdbOid(inst) {
}
LocalCdbOid::LocalCdbOid(uint64_t oid) : CdbOid(oid) {
}
LocalCdbOid::~LocalCdbOid() {
}
uint8_t LocalCdbOid::getTypeCode() const noexcept {
return CdbOid::CDB_LOCAL_OID;
}
bool LocalCdbOid::isLocal() const noexcept {
return true;
}
CdbOid* LocalCdbOid::copy() const noexcept {
return new LocalCdbOid(*this);
}
int LocalCdbOid::binarySize() const {
return CdbOid::binarySize();
}
void LocalCdbOid::toBinary(ByteBuffer* out) const {
CdbOid::toBinary(out);
}
bool LocalCdbOid::equals(const CdbOid* other) const noexcept {
return CdbOid::equals(other);
}
int LocalCdbOid::ValueCompare::operator()(
const CdbOid* const _this, const CdbOid* const object) const noexcept {
static CdbOid::ValueCompare comp;
return comp(_this, object);
}
} /* namespace codablecash */
| 19.315789
| 76
| 0.73842
|
alinous-core
|
c0653089c46f02d59bb5f645cd9d0818fe0cae63
| 562
|
cpp
|
C++
|
src/model/rayTracer/rayTracer.cpp
|
dalewzm/IceRayTracer
|
ba26e44a88fb6ff37106707ccfd3e73e123d0d60
|
[
"Apache-1.1"
] | null | null | null |
src/model/rayTracer/rayTracer.cpp
|
dalewzm/IceRayTracer
|
ba26e44a88fb6ff37106707ccfd3e73e123d0d60
|
[
"Apache-1.1"
] | null | null | null |
src/model/rayTracer/rayTracer.cpp
|
dalewzm/IceRayTracer
|
ba26e44a88fb6ff37106707ccfd3e73e123d0d60
|
[
"Apache-1.1"
] | null | null | null |
#include "rayTracer.h"
#include <cstdio>
RayTracer::RayTracer()
{
scenePtr = new Scene();
parserPtr = NULL;
}
RayTracer::~RayTracer()
{
if(scenePtr)
delete scenePtr;
if(parserPtr)
delete parserPtr;
}
void RayTracer::run()
{
buildScene();
}
bool RayTracer::buildScene()
{
fprintf(stderr,"thread id is: %x",this->currentThreadId());
for(int i=0; i<300; ++i){
for(int j=0; j<300; ++j){
QColor rgb(Qt::black);
emit calculatedApixel(i,j,rgb);
sleep(1);
}
}
return true;
}
| 14.789474
| 63
| 0.569395
|
dalewzm
|
c06b609ecc365f76e31d514dd073c826d0c454e3
| 3,742
|
cpp
|
C++
|
src/libmotifmm/IconButton.cpp
|
Arquivotheca/OpenCDE
|
4bb0f65dab345790bcf8d8422a05dda495990cd1
|
[
"BSD-2-Clause-FreeBSD"
] | 11
|
2015-05-30T14:58:42.000Z
|
2021-10-12T04:50:00.000Z
|
src/libmotifmm/IconButton.cpp
|
idunham/opencde
|
376f7ba54f8b384a5a0b2104ff2b26f9c8ab3582
|
[
"BSD-2-Clause-FreeBSD"
] | 1
|
2021-11-30T08:11:39.000Z
|
2021-11-30T08:11:39.000Z
|
src/libmotifmm/IconButton.cpp
|
idunham/opencde
|
376f7ba54f8b384a5a0b2104ff2b26f9c8ab3582
|
[
"BSD-2-Clause-FreeBSD"
] | 3
|
2015-05-30T14:58:44.000Z
|
2017-09-28T21:58:50.000Z
|
#include <motifmm.h>
namespace Motif
{
void IconButton::armCallback(Widget widget, XtPointer client_data, XtPointer call_data)
{
IconButton* button = (IconButton*)client_data;
if(button->armFunction.get() != NULL)
{
button->armFunction->execute(button);
}
}
void IconButton::activateCallback(Widget widget, XtPointer client_data, XtPointer call_data)
{
IconButton* button = (IconButton*)client_data;
if(button->activateFunction.get() != NULL)
{
button->activateFunction->execute(button);
}
}
void IconButton::disarmCallback(Widget widget, XtPointer client_data, XtPointer call_data)
{
IconButton* button = (IconButton*)client_data;
if(button->disarmFunction.get() != NULL)
{
button->disarmFunction->execute(button);
}
}
IconButton::IconButton(std::string name, Panel* panel)
{
widget = XmCreateIconButton(panel->getWidget(), (char*)name.c_str(), NULL, 0);
XtAddCallback(widget, XmNactivateCallback, activateCallback, this);
//XtAddCallback(widget, XmNarmCallback, armCallback, this);
//XtAddCallback(widget, XmNdisarmCallback, disarmCallback, this);
XtManageChild(widget);
}
IconButton::IconButton(std::string name, PulldownMenu* pulldownMenu)
{
widget = XmCreatePushButton(pulldownMenu->getWidget(), (char*)name.c_str(), NULL, 0);
XtAddCallback(widget, XmNactivateCallback, activateCallback, this);
//XtAddCallback(widget, XmNarmCallback, armCallback, this);
//XtAddCallback(widget, XmNdisarmCallback, disarmCallback, this);
XtManageChild(widget);
}
IconButton::~IconButton()
{
XtDestroyWidget(widget);
}
void IconButton::setActivateFunction(Function* function)
{
activateFunction.reset(function);
}
void IconButton::setDisarmFunction(Function* function)
{
disarmFunction.reset(function);
}
void IconButton::setArmFunction(Function* function)
{
armFunction.reset(function);
}
void IconButton::setPixmap(std::string path)
{
Arg args[2];
Pixmap p;
Pixmap m;
Pixel back;
XpmAttributes attr;
XtVaGetValues(widget, XmNbackground, &back, NULL);
XpmColorSymbol none_color = { NULL, (char*)"None", (Pixel)0 };
none_color.pixel = back;
attr.valuemask = XpmReturnPixels | XpmColorSymbols | XpmCloseness;
attr.colorsymbols = &none_color;
attr.numsymbols = 1;
attr.closeness = 80000;
XpmReadFileToPixmap(XtDisplay(widget), DefaultRootWindow(XtDisplay(widget)), (char*)path.c_str(), &p, &m, &attr);
XtSetArg(args[0], XmNiconPlacement, XmIconLeft);
XtSetArg(args[1], XmNpixmap, p);
XtSetValues(widget, args, 2);
//XSetClipMask(XtDisplay(widget), XmIconButton_pixmap_fill_gc(widget), m);
}
void IconButton::setLabelPixmap(std::string path, bool transparent)
{
Arg args[1];
Pixmap pixmap;
Pixmap mask;
Pixel back;
Pixel arm;
XpmAttributes attributes;
XpmColorSymbol colorSymbol = { NULL, (char *)"None", (Pixel)0 };
XtVaGetValues(widget, XmNbackground, &back, NULL);
XtVaGetValues(widget, XmNarmColor, &arm, NULL);
colorSymbol.pixel = back;
attributes.valuemask = XpmReturnPixels | XpmColorSymbols | XpmCloseness;
attributes.colorsymbols = &colorSymbol;
attributes.numsymbols = 1;
attributes.closeness = 80000;
XpmReadFileToPixmap(XtDisplay(widget), DefaultRootWindow(XtDisplay(widget)), (char*)path.c_str(), &pixmap, NULL, &attributes);
XtSetArg(args[0], XmNpixmap, pixmap);
XtSetValues(widget, args, 1);
if(transparent == true)
{
colorSymbol.pixel = arm;
XpmReadFileToPixmap(XtDisplay(widget), DefaultRootWindow(XtDisplay(widget)), (char*)path.c_str(), &pixmap, &mask, &attributes);
//XtSetArg(args[0], XmNarmPixmap, mask);
//XtSetValues(widget, args, 1);
XSetClipMask(XtDisplay(widget), XmIconButton_pixmap_fill_gc(widget), mask);
std::cout << path << std::endl;
}
}
}
| 27.718519
| 131
| 0.733832
|
Arquivotheca
|
c071384f0be756381592e46792d4ec0c9953dc30
| 15,404
|
cpp
|
C++
|
src/hssh/global_topological/mapping/lev_mar_optimizer.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 3
|
2020-03-05T23:56:14.000Z
|
2021-02-17T19:06:50.000Z
|
src/hssh/global_topological/mapping/lev_mar_optimizer.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-07T01:23:47.000Z
|
2021-03-07T01:23:47.000Z
|
src/hssh/global_topological/mapping/lev_mar_optimizer.cpp
|
anuranbaka/Vulcan
|
56339f77f6cf64b5fda876445a33e72cd15ce028
|
[
"MIT"
] | 1
|
2021-03-03T07:54:16.000Z
|
2021-03-03T07:54:16.000Z
|
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file lev_mar_optimizer.cpp
* \author Collin Johnson
*
* Definition of LevMarOptimizer.
*/
#include "hssh/global_topological/mapping/lev_mar_optimizer.h"
#include "hssh/global_topological/chi.h"
#include "hssh/global_topological/global_path.h"
#include "hssh/global_topological/global_place.h"
#include "hssh/global_topological/topological_map.h"
#include <boost/range/adaptor/map.hpp>
#include <boost/range/iterator_range.hpp>
#include <cassert>
#include <iostream>
#include <levmar.h>
// #define DEBUG_INITIAL_P
// #define DEBUG_X
// #define DEBUG_JACOBIAN
// #define DEBUG_INCREMENTAL_P
// #define DEBUG_LAMBDA
// #define DEBUG_COVARIANCE
// #define DEBUG_FINAL_P
// #define DEBUG_LEV_MAR
namespace vulcan
{
namespace hssh
{
// Callbacks for talking with levmar
void levmar_func(double* p, double* hx, int m, int n, void* adata);
void levmar_jacobian(double* p, double* j, int m, int n, void* adata);
LevMarOptimizer::LevMarOptimizer(const lev_mar_optimizer_params_t& params) : params_(params)
{
}
Chi LevMarOptimizer::optimizeMap(const TopologicalMap& map)
{
// Clear out any previous results
idToPIndex.clear();
xLambdaIndices.clear();
p.clear();
x.clear();
variance.clear();
xError.clear();
covariance.clear();
countEdges(map);
// Only run the optimization if there are at least as many edges as places. Otherwise,
// the optimization is actually unconstrained and thus won't produce different results
// from just laying out the places using the lambda values.
// The first place is fixed at (0, 0, 0), then all places afterward are relative to this initial place.
if ((numEdges + 1 < map.numPlaces()) || (map.numPlaces() == 0)) {
return Chi(map);
}
// if(numEdges >= map.numPlaces())
// {
setupPVector(map);
setupXVector(map);
// calculateJacobian();
runLevmar();
return createChiFromP();
// }
// else
// {
// return Chi(map);
// }
}
void LevMarOptimizer::setupPVector(const TopologicalMap& map)
{
assert(map.numPlaces() > 0);
numPlaces = map.numPlaces();
p.resize(numPlaces * 3);
covariance.resize(p.size() * p.size());
std::fill(covariance.begin(), covariance.end(), 0.0);
std::fill(p.begin(), p.end(), 0.0);
int pIndex = 0;
// Skip the first place because it is the free parameter that we fix to be (0, 0, 0).
auto beginIt = map.places().begin();
initialId_ = beginIt->first;
++beginIt;
for (auto& place : boost::make_iterator_range(beginIt, map.places().end())) {
pose_t pose = map.referenceFrame(place.second->id());
p[pIndex * 3] = pose.x;
p[pIndex * 3 + 1] = pose.y;
p[pIndex * 3 + 2] = pose.theta;
idToPIndex[place.first] = pIndex;
++pIndex;
}
// Save the initial, fixed at the end of the pVector, so the optimization can safely refer to it without actually
// trying to overwrite it. The value is always 0, so it should work okay.
idToPIndex[initialId_] = pIndex;
p[pIndex * 3] = 0.0;
p[pIndex * 3 + 1] = 0.0;
p[pIndex * 3 + 2] = 0.0;
#ifdef DEBUG_INITIAL_P
std::cout << "DEBUG:LevMar:Initial p-vector (initial mean poses):\n";
for (std::size_t n = 0; n < numPlaces; ++n) {
std::cout << '(' << p[n * 3] << ',' << p[n * 3 + 1] << ',' << p[n * 3 + 2] << ")\n";
}
#endif
}
void LevMarOptimizer::setupXVector(const TopologicalMap& map)
{
const std::size_t kXMinSize = numEdges * 3;
if (x.capacity() < kXMinSize) {
x.reserve(kXMinSize);
variance.reserve(kXMinSize);
xError.reserve(kXMinSize);
}
std::size_t xIndex = 0;
for (auto& segment : boost::adaptors::values(map.segments())) {
// Ignore frontiers the front half of a loop, as the constraint will be added for the end segment
if (segment->isFrontier()) {
continue;
}
// Check the indices to see if this is a well-constrained segment, which means both ends have been visited.
// Don't add lambdas for frontier segments because they aren't actually useful information for constraining
// the Chi value
std::pair<int, int> pIndices(idToPIndex[segment->plusPlace().id()], idToPIndex[segment->minusPlace().id()]);
assert(xIndex == xLambdaIndices.size());
assert(xIndex * 3 == variance.size());
#ifdef DEBUG_X
std::cout << "Segment from " << segment->plusPlace().id() << " to " << segment->minusPlace().id()
<< " idx:" << pIndices.first << " to " << pIndices.second << '\n';
#endif
const std::vector<Lambda>& lambdas = segment->getAllLambdas();
for (auto lambdaIt = lambdas.begin(), lambdaEnd = lambdas.end(); lambdaIt != lambdaEnd; ++lambdaIt) {
const Lambda& segmentLambda = *lambdaIt;
double xVar = segmentLambda.xVariance;
double yVar = segmentLambda.yVariance;
double thetaVar = segmentLambda.thetaVariance;
variance.push_back(xVar);
variance.push_back(yVar);
variance.push_back(thetaVar);
x.push_back(segmentLambda.x / xVar);
x.push_back(segmentLambda.y / yVar);
x.push_back(segmentLambda.theta / thetaVar);
xLambdaIndices.push_back(pIndices);
++xIndex;
#ifdef DEBUG_X
std::cout << '(' << segmentLambda.x << ',' << segmentLambda.y << ',' << segmentLambda.theta << ")\n";
#endif
}
}
#ifdef DEBUG_X
std::cout << "DEBUG:LevMar:x-vector (measurements):\n";
for (std::size_t n = 0; n < numEdges; ++n) {
std::cout << '(' << x[n * 3] << ',' << x[n * 3 + 1] << ',' << x[n * 3 + 2] << ")\n";
}
std::cout << "DEBUG:LevMar:Measurement variance:\n";
for (std::size_t i = 0; i < numEdges; ++i) {
for (std::size_t j = 0; j < 3; ++j) {
std::cout << variance[i * 3 + j] << ' ';
}
std::cout << '\n';
}
#endif
}
void LevMarOptimizer::countEdges(const TopologicalMap& map)
{
numEdges = 0;
for (auto& segment : boost::adaptors::values(map.segments())) {
if (!segment->isFrontier()) {
numEdges += segment->getAllLambdas().size();
}
}
}
void LevMarOptimizer::runLevmar(void)
{
// Need to have at least as many edges as places in order to optimizer, otherwise graph is tree-structured
// if(numEdges < numPlaces)
// {
// return;
// }
assert(xLambdaIndices.size() == numEdges);
if (work.size() < LM_DIF_WORKSZ(p.size(), x.size())) {
work.resize(LM_DIF_WORKSZ(p.size(), x.size()));
std::fill(work.begin(), work.end(), 0.0);
}
double opts[5];
double info[LM_INFO_SZ];
opts[0] = params_.initialMu;
opts[1] = params_.stopThreshold;
opts[2] = params_.stopThreshold;
opts[3] = params_.stopThreshold;
opts[4] = 1.0;
// dlevmar_der(levmar_func, levmar_jacobian, p, x, numPlaces*3, numEdges*3, params_.maxIterations, opts, info,
// work, covariance, this); dlevmar_dif(levmar_func, p, x, numPlaces*3, numEdges*3, params_.maxIterations, opts,
// info, work, covariance, this);
dlevmar_dif(
levmar_func,
p.data(),
x.data(),
// handle the case where there's a single area, so it needs to have the error computed, which will be large
(p.size() > 3) ? p.size() - 3 : p.size(), // ignoring the final place, which will always be (0,0,0)
x.size(),
params_.maxIterations,
opts,
info,
work.data(),
covariance.data(),
this);
finalError = info[1];
#ifdef DEBUG_JACOBIAN
std::vector<double> error(x.size());
dlevmar_chkjac(levmar_func, levmar_jacobian, p.data(), p.size() - 3, x.size(), this, error.data());
std::cout << "DEBUG:LevMar:Jacobian check:\n";
for (std::size_t n = 0; n < error.size(); ++n) {
std::cout << error[n] << '\n';
}
#endif
#ifdef DEBUG_LEV_MAR
std::cout << "DEBUG:LevMar:Optimization info:\n"
<< "Initial error:" << info[0] << '\n'
<< "Final error: " << info[1] << '\n'
<< "Iterations: " << info[5] << '\n'
<< "Termination: " << info[6] << '\n'
<< "Func evals: " << info[7] << '\n'
<< "Jacob evals: " << info[8] << '\n'
<< "Sys solved: " << info[9] << '\n';
#endif
}
Chi LevMarOptimizer::createChiFromP(void)
{
std::unordered_map<Id, pose_distribution_t> finalPoses;
for (auto& index : idToPIndex) {
int idx = index.second * 3;
pose_distribution_t pose;
pose.x = p[idx];
pose.y = p[idx + 1];
pose.theta = wrap_to_pi(p[idx + 2]);
pose.uncertainty[0] = pose.x;
pose.uncertainty[1] = pose.y;
pose.uncertainty[2] = pose.theta;
// Copy out the covariance off the block diagonal -- don't care about the other cross-correlation terms
for (int y = 0; y < 3; ++y) {
for (int x = 0; x < 3; ++x) {
pose.uncertainty(x, y) = covariance[((idx + y) * numPlaces * 3) + idx + x];
}
}
finalPoses[index.first] = pose;
}
#ifdef DEBUG_FINAL_P
std::cout << "DEBUG::LevMar: Mean poses:\n";
for (auto& idToPose : finalPoses) {
std::cout << idToPose.first << ":\n"
<< idToPose.second.uncertainty.getMean() << '\n'
<< idToPose.second.uncertainty.getCovariance();
}
#endif
#ifdef DEBUG_COVARIANCE
// std::cout<<"DEBUG:LevMar:Covariance:\n";
// for(std::size_t i = 0; i < numPlaces*3; ++i)
// {
// for(std::size_t j = 0; j < numPlaces*3; ++j)
// {
// printf("%.2f ", covariance[i*numPlaces*3 + j]);
// // std::cout<<covariance[i*numPlaces*3 + j]<<' ';
// }
// std::cout<<'\n';
// }
std::cout << "DEBUG:LevMar:Covariance diag:\n";
for (std::size_t i = 0; i < numPlaces * 3; ++i) {
printf("%.2f ", dlevmar_stddev(covariance.data(), numPlaces * 3, i)); // covariance[i*numPlaces*3 + i*3]);
std::cout << '\n';
}
#endif
// Error minimizes (lambda_chi - lambda_obs)^T cov_obs^-1 (lambda_chi - lambda_obs)
// To get log-likelihood, just multiply by -0.5, which gives the Gaussian log-likelihood
return Chi(finalPoses, -0.5 * finalError);
}
void LevMarOptimizer::calculateLambdas(double* newP, double* hx, int m, int n)
{
pose_t start;
pose_t end;
for (std::size_t i = 0; i < xLambdaIndices.size(); ++i) {
// Only consider the new poses if they have valid indices. If out of range, that means it should be 0,0,0
// per the design of the p matrix
if (xLambdaIndices[i].first * 3 < m) {
int startIdx = xLambdaIndices[i].first * 3;
start.x = newP[startIdx];
start.y = newP[startIdx + 1];
start.theta = wrap_to_pi(newP[startIdx + 2]);
}
// At the origin
else {
start.x = 0.0f;
start.y = 0.0f;
start.theta = 0.0f;
}
if (xLambdaIndices[i].second * 3 < m) {
int endIdx = xLambdaIndices[i].second * 3;
end.x = newP[endIdx];
end.y = newP[endIdx + 1];
end.theta = wrap_to_pi(newP[endIdx + 2]);
}
// At the origin
else {
end.x = 0.0f;
end.y = 0.0f;
end.theta = 0.0f;
}
auto diff = end.transformToNewFrame(start);
int xIdx = i * 3;
int yIdx = xIdx + 1;
int thetaIdx = xIdx + 2;
hx[xIdx] = diff.x / variance[xIdx];
hx[yIdx] = diff.y / variance[yIdx];
hx[thetaIdx] = diff.theta / variance[thetaIdx];
xError[xIdx] = x[xIdx] - hx[xIdx];
xError[yIdx] = x[yIdx] - hx[yIdx];
xError[thetaIdx] = wrap_to_pi(x[thetaIdx] - hx[thetaIdx]);
}
#ifdef DEBUG_INCREMENTAL_P
std::cout << "DEBUG:LevMar:Incremental p-vector:\n";
for (int i = 0; i * 3 < m; ++i) {
std::cout << '(' << newP[i * 3] << ',' << newP[i * 3 + 1] << ',' << newP[i * 3 + 2] << ")\n";
}
#endif
#ifdef DEBUG_LAMBDA
std::cout << "DEBUG:LevMar:Incremental lambdas (hx-vector):\n";
for (std::size_t i = 0; i < numEdges; ++i) {
std::cout << '(' << hx[i * 3] << ',' << hx[i * 3 + 1] << ',' << hx[i * 3 + 2] << ")\n";
}
std::cout << "DEBUG:LevMar:Residuals (x-hx):\n";
for (std::size_t i = 0; i < numEdges; ++i) {
std::cout << '(' << (x[i * 3] - hx[i * 3]) << ',' << (x[i * 3 + 1] - hx[i * 3 + 1]) << ','
<< (x[i * 3 + 2] - hx[i * 3 + 2]) << ")\n";
}
#endif
}
void LevMarOptimizer::calculateJacobian(double* j, int m, int n)
{
// The residuals are (p_i - p_j - x_n)^2. Thus the Jacobian is +1 for J_n_i and -1 for J_n_j.
std::size_t rowStart = 0;
std::size_t rowStep = numPlaces * 3;
memset(j, 0, m * m * sizeof(double));
// The Jacobian is two diagonal blocks for (x,y,theta). second = end place, first = start place. so lambda = p_end
// - p_start
for (std::size_t i = 0; i < numEdges; ++i) {
if (xLambdaIndices[i].second * 3 < n) {
j[rowStart + xLambdaIndices[i].second * 3] = xError[i * 3];
}
if (xLambdaIndices[i].first * 3 < n) {
j[rowStart + xLambdaIndices[i].first * 3] = -xError[i * 3];
}
rowStart += rowStep;
if (xLambdaIndices[i].second * 3 < n) {
j[rowStart + xLambdaIndices[i].second * 3 + 1] = xError[i * 3 + 1];
}
if (xLambdaIndices[i].first * 3 < n) {
j[rowStart + xLambdaIndices[i].first * 3 + 1] = -xError[i * 3 + 1];
}
rowStart += rowStep;
if (xLambdaIndices[i].second * 3 < n) {
j[rowStart + xLambdaIndices[i].second * 3 + 2] = xError[i * 3 + 2];
}
if (xLambdaIndices[i].first * 3 < n) {
j[rowStart + xLambdaIndices[i].first * 3 + 2] = -xError[i * 3 + 2];
}
rowStart += rowStep;
}
#ifdef DEBUG_JACOBIAN
rowStart = 0;
std::cout << "DEBUG:LevMar:Jacobian:\n";
for (std::size_t n = 0; n < numEdges * 3; ++n) {
for (std::size_t i = 0; i < numPlaces * 3; ++i) {
std::cout << j[rowStart + i] << ' ';
}
std::cout << '\n';
rowStart += rowStep;
}
#endif
}
// Create friend functions to issue as the callbacks used by levmar. The adata will point to this, which will then
// be used to call the
void levmar_func(double* p, double* hx, int m, int n, void* adata)
{
LevMarOptimizer* optimizer = static_cast<LevMarOptimizer*>(adata);
optimizer->calculateLambdas(p, hx, m, n);
}
void levmar_jacobian(double* p, double* j, int m, int n, void* adata)
{
LevMarOptimizer* optimizer = static_cast<LevMarOptimizer*>(adata);
optimizer->calculateJacobian(j, m, n);
}
} // namespace hssh
} // namespace vulcan
| 31.826446
| 120
| 0.566801
|
anuranbaka
|
c0719985811e50f80299395fac2dcb5e6a782f03
| 2,770
|
cxx
|
C++
|
osprey/be/cg/orc_ict/val_prof.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/be/cg/orc_ict/val_prof.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/be/cg/orc_ict/val_prof.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Copyright (c) 2001, Institute of Computing Technology, Chinese Academy of Sciences
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
Neither the name of the owner nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//-*-c++-*-
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <list>
#include <set>
#include "bb.h"
#include "defs.h"
#include "cg_region.h"
#include "label_util.h"
#include "symtab.h"
#include "data_layout.h"
#include "symtab_access.h"
#include "cg_flags.h"
#include "vt_region.h"
#include "tracing.h"
#include "instr_reader.h"
#include "dump_feedback.h"
#include "freq.h"
#include "ipfec_defs.h"
#include "gra_live.h"
#include "region.h"
#include "region_bb_util.h"
#include "region_update.h"
#include "region_verify.h"
#include "ipfec_options.h"
#include "val_prof.h"
#define GEN_NEWBB_FOR_RESTORE___Should_disable_ebo
//#define VALUE_PROFILE_INTERNAL_DEBUG
//#define _maybe_wrong_test
//#define _delete_but_not_fully_tested_yet
#define VALUE_PROFILE_DETAIL
#define My_OP_to_split_entry1 TOP_mov_f_pr
#define My_OP_to_split_entry2 TOP_mov_f_ar
#define My_OP_to_split_entry3 TOP_mov_f_br
#define My_OP_to_split_entry4 TOP_spadjust
#define TNV_N 10
INST2PROFLIST inst2prof_list;
//OP_TNV_MAP op_tnv_map;
OP_MAP op_tnv_map;
OP_MAP op_stride_tnv_map;
/* The FB_Info_Value definition in ORC conflicit with its def
* in current compiler. Turn off val-prof for the time-being.
*/
| 34.197531
| 99
| 0.788087
|
sharugupta
|
c07a909bb7a80af4b7f9b04136aaaff16c2132a1
| 3,404
|
hpp
|
C++
|
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_translation_averaging.hpp
|
Aurelio93/satellite-pose-estimation
|
46957a9bc9f204d468f8fe3150593b3db0f0726a
|
[
"MIT"
] | 90
|
2019-05-19T03:48:23.000Z
|
2022-02-02T15:20:49.000Z
|
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_translation_averaging.hpp
|
Aurelio93/satellite-pose-estimation
|
46957a9bc9f204d468f8fe3150593b3db0f0726a
|
[
"MIT"
] | 11
|
2019-05-22T07:45:46.000Z
|
2021-05-20T01:48:26.000Z
|
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_translation_averaging.hpp
|
Aurelio93/satellite-pose-estimation
|
46957a9bc9f204d468f8fe3150593b3db0f0726a
|
[
"MIT"
] | 18
|
2019-05-19T03:48:32.000Z
|
2021-05-29T18:19:16.000Z
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_TRANSLATION_AVERAGING_HPP
#define OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_TRANSLATION_AVERAGING_HPP
#include <string>
#include <vector>
#include "openMVG/multiview/translation_averaging_common.hpp"
#include "openMVG/tracks/tracks.hpp"
namespace openMVG { namespace graph { struct Triplet; } }
namespace openMVG { namespace matching { struct PairWiseMatches; } }
namespace openMVG { namespace sfm { struct Features_Provider; } }
namespace openMVG { namespace sfm { struct Matches_Provider; } }
namespace openMVG { namespace sfm { struct SfM_Data; } }
namespace openMVG{
namespace sfm{
enum ETranslationAveragingMethod
{
TRANSLATION_AVERAGING_L1 = 1,
TRANSLATION_AVERAGING_L2_DISTANCE_CHORDAL = 2,
TRANSLATION_AVERAGING_SOFTL1 = 3
};
struct SfM_Data;
struct Matches_Provider;
struct Features_Provider;
class GlobalSfM_Translation_AveragingSolver
{
std::vector<RelativeInfo_Vec> vec_relative_motion_;
public:
bool Run(
ETranslationAveragingMethod eTranslationAveragingMethod,
openMVG::sfm::SfM_Data & sfm_data,
const openMVG::sfm::Features_Provider * features_provider,
const openMVG::sfm::Matches_Provider * matches_provider,
const Hash_Map<IndexT, Mat3> & map_globalR,
matching::PairWiseMatches & tripletWise_matches
);
private:
bool Translation_averaging(
ETranslationAveragingMethod eTranslationAveragingMethod,
sfm::SfM_Data & sfm_data,
const Hash_Map<IndexT, Mat3> & map_globalR);
void Compute_translations(
const sfm::SfM_Data & sfm_data,
const sfm::Features_Provider * features_provider,
const sfm::Matches_Provider * matches_provider,
const Hash_Map<IndexT, Mat3> & map_globalR,
matching::PairWiseMatches &tripletWise_matches);
//-- Compute the relative translations on the rotations graph.
// Compute relative translations by using triplets of poses.
// Use an edge coverage algorithm to reduce the graph covering complexity
// Complexity: sub-linear in term of edges count.
void ComputePutativeTranslation_EdgesCoverage(
const sfm::SfM_Data & sfm_data,
const Hash_Map<IndexT, Mat3> & map_globalR,
const sfm::Features_Provider * features_provider,
const sfm::Matches_Provider * matches_provider,
std::vector<RelativeInfo_Vec> & vec_triplet_relative_motion,
matching::PairWiseMatches & newpairMatches);
// Robust estimation and refinement of triplet of translations
bool Estimate_T_triplet(
const sfm::SfM_Data & sfm_data,
const Hash_Map<IndexT, Mat3> & map_globalR,
const sfm::Features_Provider * features_provider,
const sfm::Matches_Provider * matches_provider,
const graph::Triplet & poses_id,
std::vector<Vec3> & vec_tis,
double & dPrecision, // UpperBound of the precision found by the AContrario estimator
std::vector<uint32_t> & vec_inliers,
openMVG::tracks::STLMAPTracks & rig_tracks,
const std::string & sOutDirectory) const;
};
} // namespace sfm
} // namespace openMVG
#endif // OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_TRANSLATION_AVERAGING_HPP
| 35.458333
| 89
| 0.772033
|
Aurelio93
|
c07b1afeec5d624a520cb38891804774fc3523ac
| 467
|
hpp
|
C++
|
Xcode Build/that game engine/that_game_engine/C_InteractableTalking.hpp
|
ThatGamesGuy/that_platform_game
|
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
|
[
"MIT"
] | 55
|
2018-06-19T08:22:47.000Z
|
2022-03-30T01:02:59.000Z
|
Xcode Build/that game engine/that_game_engine/C_InteractableTalking.hpp
|
ThatGamesGuy/that_platform_game
|
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
|
[
"MIT"
] | null | null | null |
Xcode Build/that game engine/that_game_engine/C_InteractableTalking.hpp
|
ThatGamesGuy/that_platform_game
|
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
|
[
"MIT"
] | 21
|
2019-04-19T15:39:08.000Z
|
2022-02-20T11:21:13.000Z
|
#ifndef C_InteractableTalking_hpp
#define C_InteractableTalking_hpp
#include "Component.hpp"
#include "C_Interactable.hpp"
#include "Debug.hpp"
#include "C_UIWorldLabel.hpp"
#include "ObjectCollection.hpp"
class C_InteractableTalking : public Component, public C_Interactable
{
public:
C_InteractableTalking(Object* owner);
void OnInteraction(Object* other) override;
private:
std::string textToSay;
};
#endif /* C_InteractableTalking_hpp */
| 21.227273
| 69
| 0.770878
|
ThatGamesGuy
|
c07b8ccd01937d56fc0ab3f41e6d4a4ded2abefe
| 8,937
|
cpp
|
C++
|
sparse/src/dpcg_merge.cpp
|
klast/magma
|
cfb849621be6f697288e995831ec3c9e84530d9d
|
[
"BSD-3-Clause"
] | 4
|
2020-12-04T13:31:18.000Z
|
2021-12-10T11:41:23.000Z
|
sparse/src/dpcg_merge.cpp
|
klast/magma
|
cfb849621be6f697288e995831ec3c9e84530d9d
|
[
"BSD-3-Clause"
] | 1
|
2021-03-27T20:00:25.000Z
|
2021-03-28T06:19:59.000Z
|
sparse/src/dpcg_merge.cpp
|
klast/magma
|
cfb849621be6f697288e995831ec3c9e84530d9d
|
[
"BSD-3-Clause"
] | 2
|
2020-12-04T13:23:36.000Z
|
2021-03-27T00:50:27.000Z
|
/*
-- MAGMA (version 2.5.4) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date October 2020
@author Hartwig Anzt
@generated from sparse/src/zpcg_merge.cpp, normal z -> d, Thu Oct 8 23:05:52 2020
*/
#include "magmasparse_internal.h"
#define RTOLERANCE lapackf77_dlamch( "E" )
#define ATOLERANCE lapackf77_dlamch( "E" )
/**
Purpose
-------
Solves a system of linear equations
A * X = B
where A is a real matrix A.
This is a GPU implementation of the Conjugate Gradient method in variant,
where multiple operations are merged into one compute kernel.
Arguments
---------
@param[in]
A magma_d_matrix
input matrix A
@param[in]
b magma_d_matrix
RHS b
@param[in,out]
x magma_d_matrix*
solution approximation
@param[in,out]
solver_par magma_d_solver_par*
solver parameters
@param[in]
precond_par magma_d_preconditioner*
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_dposv
********************************************************************/
extern "C" magma_int_t
magma_dpcg_merge(
magma_d_matrix A, magma_d_matrix b, magma_d_matrix *x,
magma_d_solver_par *solver_par,
magma_d_preconditioner *precond_par,
magma_queue_t queue )
{
magma_int_t info = MAGMA_NOTCONVERGED;
// prepare solver feedback
solver_par->solver = Magma_PCGMERGE;
solver_par->numiter = 0;
solver_par->spmv_count = 0;
// solver variables
double alpha, beta, gamma, rho, tmp1, *skp_h={0};
double nom, nom0, r0, res, nomb;
double den;
// some useful variables
double c_zero = MAGMA_D_ZERO, c_one = MAGMA_D_ONE;
magma_int_t dofs = A.num_rows*b.num_cols;
magma_d_matrix r={Magma_CSR}, d={Magma_CSR}, z={Magma_CSR}, h={Magma_CSR},
rt={Magma_CSR};
double *d1=NULL, *d2=NULL, *skp=NULL;
// GPU workspace
CHECK( magma_dvinit( &r, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_dvinit( &d, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_dvinit( &z, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_dvinit( &rt, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_dvinit( &h, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_dmalloc( &d1, dofs*(2) ));
CHECK( magma_dmalloc( &d2, dofs*(2) ));
// array for the parameters
CHECK( magma_dmalloc( &skp, 7 ));
// skp = [alpha|beta|gamma|rho|tmp1|tmp2|res]
// solver setup
CHECK( magma_dresidualvec( A, b, *x, &r, &nom0, queue));
// preconditioner
CHECK( magma_d_applyprecond_left( MagmaNoTrans, A, r, &rt, precond_par, queue ));
CHECK( magma_d_applyprecond_right( MagmaNoTrans, A, rt, &h, precond_par, queue ));
magma_dcopy( dofs, h.dval, 1, d.dval, 1, queue );
nom = MAGMA_D_ABS( magma_ddot( dofs, r.dval, 1, h.dval, 1, queue ));
CHECK( magma_d_spmv( c_one, A, d, c_zero, z, queue )); // z = A d
den = magma_ddot( dofs, d.dval, 1, z.dval, 1, queue ); // den = d'* z
solver_par->init_res = nom0;
nomb = magma_dnrm2( dofs, b.dval, 1, queue );
if ( nomb == 0.0 ){
nomb=1.0;
}
if ( (r0 = nomb * solver_par->rtol) < ATOLERANCE ){
r0 = ATOLERANCE;
}
solver_par->final_res = solver_par->init_res;
solver_par->iter_res = solver_par->init_res;
if ( solver_par->verbose > 0 ) {
solver_par->res_vec[0] = (real_Double_t)nom0;
solver_par->timing[0] = 0.0;
}
if ( nom0 < r0 ) {
info = MAGMA_SUCCESS;
goto cleanup;
}
// check positive definite
if ( MAGMA_D_ABS(den) <= 0.0 ) {
info = MAGMA_NONSPD;
goto cleanup;
}
// array on host for the parameters
CHECK( magma_dmalloc_cpu( &skp_h, 7 ));
alpha = rho = gamma = tmp1 = c_one;
beta = magma_ddot( dofs, h.dval, 1, r.dval, 1, queue );
skp_h[0]=alpha;
skp_h[1]=beta;
skp_h[2]=gamma;
skp_h[3]=rho;
skp_h[4]=tmp1;
skp_h[5]=MAGMA_D_MAKE(nom, 0.0);
skp_h[6]=MAGMA_D_MAKE(nom, 0.0);
magma_dsetvector( 7, skp_h, 1, skp, 1, queue );
//Chronometry
real_Double_t tempo1, tempo2;
tempo1 = magma_sync_wtime( queue );
solver_par->numiter = 0;
solver_par->spmv_count = 0;
// start iteration
do
{
solver_par->numiter++;
// computes SpMV and dot product
CHECK( magma_dcgmerge_spmv1( A, d1, d2, d.dval, z.dval, skp, queue ));
solver_par->spmv_count++;
if( precond_par->solver == Magma_JACOBI ){
CHECK( magma_djcgmerge_xrbeta( dofs, d1, d2, precond_par->d.dval, x->dval, r.dval, d.dval, z.dval, h.dval, skp, queue ));
}
else if( precond_par->solver == Magma_NONE ){
// updates x, r
CHECK( magma_dpcgmerge_xrbeta1( dofs, x->dval, r.dval, d.dval, z.dval, skp, queue ));
// computes scalars and updates d
CHECK( magma_dpcgmerge_xrbeta2( dofs, d1, d2, r.dval, r.dval, d.dval, skp, queue ));
}
else {
// updates x, r
CHECK( magma_dpcgmerge_xrbeta1( dofs, x->dval, r.dval, d.dval, z.dval, skp, queue ));
// preconditioner in between
CHECK( magma_d_applyprecond_left( MagmaNoTrans, A, r, &rt, precond_par, queue ));
CHECK( magma_d_applyprecond_right( MagmaNoTrans, A, rt, &h, precond_par, queue ));
// magma_dcopy( dofs, r.dval, 1, h.dval, 1 );
// computes scalars and updates d
CHECK( magma_dpcgmerge_xrbeta2( dofs, d1, d2, h.dval, r.dval, d.dval, skp, queue ));
}
//if( solver_par->numiter==1){
// magma_dcopy( dofs, h.dval, 1, d.dval, 1 );
//}
// updates x, r, computes scalars and updates d
//CHECK( magma_dcgmerge_xrbeta( dofs, d1, d2, x->dval, r.dval, d.dval, z.dval, skp, queue ));
// check stopping criterion (asynchronous copy)
magma_dgetvector( 1 , skp+6, 1, skp_h+6, 1, queue );
res = sqrt(MAGMA_D_ABS(skp_h[6]));
if ( solver_par->verbose > 0 ) {
tempo2 = magma_sync_wtime( queue );
if ( (solver_par->numiter)%solver_par->verbose==0 ) {
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) res;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) tempo2-tempo1;
}
}
if ( res/nomb <= solver_par->rtol || res <= solver_par->atol ){
break;
}
}
while ( solver_par->numiter+1 <= solver_par->maxiter );
tempo2 = magma_sync_wtime( queue );
solver_par->runtime = (real_Double_t) tempo2-tempo1;
double residual;
CHECK( magma_dresidualvec( A, b, *x, &r, &residual, queue));
solver_par->iter_res = res;
solver_par->final_res = residual;
if ( solver_par->numiter < solver_par->maxiter ) {
info = MAGMA_SUCCESS;
} else if ( solver_par->init_res > solver_par->final_res ) {
if ( solver_par->verbose > 0 ) {
if ( (solver_par->numiter)%solver_par->verbose==0 ) {
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) res;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) tempo2-tempo1;
}
}
info = MAGMA_SLOW_CONVERGENCE;
if( solver_par->iter_res < solver_par->atol ||
solver_par->iter_res/solver_par->init_res < solver_par->rtol ){
info = MAGMA_SUCCESS;
}
}
else {
if ( solver_par->verbose > 0 ) {
if ( (solver_par->numiter)%solver_par->verbose==0 ) {
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) res;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) tempo2-tempo1;
}
}
solver_par->info = MAGMA_DIVERGENCE;
}
cleanup:
magma_dmfree(&r, queue );
magma_dmfree(&z, queue );
magma_dmfree(&d, queue );
magma_dmfree(&rt, queue );
magma_dmfree(&h, queue );
magma_free( d1 );
magma_free( d2 );
magma_free( skp );
magma_free_cpu( skp_h );
solver_par->info = info;
return info;
} /* magma_dpcg_merge */
| 33.47191
| 137
| 0.567081
|
klast
|
c07bc51fa742c4eaca035a502fecbaceec5e37fe
| 2,621
|
cc
|
C++
|
attractor.cc
|
chzchzchz/chaos
|
2b6f8e7a39fe5384146936e49ec2fca2b168cb35
|
[
"BSD-3-Clause"
] | 1
|
2019-01-02T18:38:25.000Z
|
2019-01-02T18:38:25.000Z
|
attractor.cc
|
chzchzchz/chaos
|
2b6f8e7a39fe5384146936e49ec2fca2b168cb35
|
[
"BSD-3-Clause"
] | null | null | null |
attractor.cc
|
chzchzchz/chaos
|
2b6f8e7a39fe5384146936e49ec2fca2b168cb35
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stdlib.h>
#include <math.h>
#include "attractor.h"
static double eval(double x, double y, const std::vector<double>& v)
{
double ret = 0.0;
for (unsigned x_deg = 0; x_deg <= MAP_DEGREE; x_deg++) {
for (unsigned y_deg = 0; y_deg <= x_deg; y_deg++) {
ret += v[x_deg * MAP_DEGREE + y_deg]
* pow(x, x_deg - y_deg)
* pow(y, y_deg);
}
}
return ret;
}
#define maxmin(z) \
do { \
if (z##_new > z##_max) \
z##_max = z##_new; \
else if (z##_new < z##_min) \
z##_min = z##_new; \
} while(0)
Attractor::Attractor()
{
find_vecs();
}
bool Attractor::try_vecs_usage(unsigned iters) const
{
HitMap hm(search_xfm, SEARCH_DIM_X, SEARCH_DIM_Y);
apply(hm, SEARCH_ITERS);
if (hm.get_fill_count() < MIN_FILL * SEARCH_DIM_X * SEARCH_DIM_Y)
return false;
return true;
}
bool Attractor::try_vecs(unsigned iters)
{
if (!try_vec_bounds(iters))
return false;
return try_vecs_usage(iters);
}
bool Attractor::try_vec_bounds(unsigned iters)
{
double x_min, y_min, x_max, y_max, x, y;
int i;
x = 0; y = 0;
x_min = x_max = x;
y_min = y_max = y;
for (i = 0; i < iters; i++) {
double x_new = eval(x, y, a),
y_new = eval(x, y, b);
maxmin(x);
maxmin(y);
x = x_new;
y = y_new;
// test for NaN's
if (x != x || y != y)
return false;
}
if ((x_max - x_max) == x_max || (y_max - y_max) == y_max ||
x_max != x_max || y_max != y_max)
return false;
if ((x_min - x_min) == x_min || (y_min - y_min) == y_min ||
x_min != x_min || y_min != y_min)
return false;
if (x_max - x_min == x_max || x_max - x_min == -x_min ||
y_max - y_min == y_max || y_max - y_min == -y_min)
return false;
search_xfm.xlateX = -x_min;
search_xfm.xlateY = -y_min;
search_xfm.scaleX = ((double)SEARCH_DIM_X - 1) / (x_max - x_min);
search_xfm.scaleY = ((double)SEARCH_DIM_Y - 1) / (y_max - y_min);
return true;
}
static void gen_vec(std::vector<double>& v, double min, double max)
{
v.resize((MAP_DEGREE * (MAP_DEGREE + 1)) / 2);
for (unsigned i = 0; i < v.size(); i++) {
double rval = (double)rand() / (double)RAND_MAX;
v[i] = (rval * (max - min)) + min;
}
}
/* return number of attempts */
unsigned Attractor::find_vecs(void)
{
unsigned attempts = 0;
do {
attempts++;
gen_vec(a, SEARCH_VMIN, SEARCH_VMAX);
gen_vec(b, SEARCH_VMIN, SEARCH_VMAX);
} while (!try_vecs(SEARCH_ITERS));
return attempts;
}
void Attractor::apply(HitMap& hm, unsigned iters) const
{
double x = 0.0,
y = 0.0;
for (unsigned i = 0; i < iters; i++) {
double x_new = eval(x, y, a),
y_new = eval(x, y, b);
hm.inc(x_new, y_new);
x = x_new;
y = y_new;
}
}
| 20.476563
| 68
| 0.606257
|
chzchzchz
|
c07cdce5556f323583b262a25f7f65527d316337
| 3,198
|
cpp
|
C++
|
Source/Storm-Graphics/include/GraphicConstraintSystem.cpp
|
SunlayGGX/Storm
|
83a34c14cc7d936347b6b8193a64cd13ccbf00a8
|
[
"MIT"
] | 3
|
2021-11-27T04:56:12.000Z
|
2022-02-14T04:02:10.000Z
|
Source/Storm-Graphics/include/GraphicConstraintSystem.cpp
|
SunlayGGX/Storm
|
83a34c14cc7d936347b6b8193a64cd13ccbf00a8
|
[
"MIT"
] | null | null | null |
Source/Storm-Graphics/include/GraphicConstraintSystem.cpp
|
SunlayGGX/Storm
|
83a34c14cc7d936347b6b8193a64cd13ccbf00a8
|
[
"MIT"
] | null | null | null |
#include "GraphicConstraintSystem.h"
#include "ConstraintShader.h"
#include "ThrowIfFailed.h"
Storm::GraphicConstraintSystem::GraphicConstraintSystem(const ComPtr<ID3D11Device> &device) :
_shader{ std::make_unique<Storm::ConstraintShader>(device) },
_constraintVertexCount{ 0 }
{
}
Storm::GraphicConstraintSystem::~GraphicConstraintSystem() = default;
void Storm::GraphicConstraintSystem::refreshConstraintsData(const ComPtr<ID3D11Device> &device, const std::vector<Storm::Vector3> &constraintsData)
{
const std::size_t newParticleCount = constraintsData.size();
if (newParticleCount == 0)
{
return;
}
const bool shouldRegenIndexBuffer = static_cast<std::size_t>(_constraintVertexCount) != newParticleCount;
_constraintVertexCount = static_cast<uint32_t>(newParticleCount);
// In case it has a vertex buffer set (most of the time)
_vertexBuffer = nullptr;
// Create Vertex data
D3D11_BUFFER_DESC vertexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData;
vertexBufferDesc.Usage = D3D11_USAGE::D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Storm::Vector3) * static_cast<UINT>(newParticleCount);
vertexBufferDesc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
vertexData.pSysMem = constraintsData.data();
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
Storm::throwIfFailed(device->CreateBuffer(&vertexBufferDesc, &vertexData, &_vertexBuffer));
if (shouldRegenIndexBuffer)
{
std::unique_ptr<uint32_t[]> indexes = std::make_unique<uint32_t[]>(newParticleCount);
for (uint32_t iter = 0; iter < newParticleCount; ++iter)
{
indexes[iter] = iter;
}
// Create Indexes data
D3D11_BUFFER_DESC indexBufferDesc;
D3D11_SUBRESOURCE_DATA indexData;
indexBufferDesc.Usage = D3D11_USAGE::D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = static_cast<UINT>(sizeof(uint32_t) * newParticleCount);
indexBufferDesc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
indexData.pSysMem = indexes.get();
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
Storm::throwIfFailed(device->CreateBuffer(&indexBufferDesc, &indexData, &_indexBuffer));
}
}
void Storm::GraphicConstraintSystem::render(const ComPtr<ID3D11Device> &device, const ComPtr<ID3D11DeviceContext> &deviceContext, const Storm::Camera ¤tCamera)
{
_shader->setup(device, deviceContext, currentCamera);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
this->setupForRender(deviceContext);
_shader->draw(_constraintVertexCount, deviceContext);
}
void Storm::GraphicConstraintSystem::setupForRender(const ComPtr<ID3D11DeviceContext> &deviceContext)
{
constexpr UINT stride = sizeof(Storm::Vector3);
constexpr UINT offset = 0;
deviceContext->IASetIndexBuffer(_indexBuffer.Get(), DXGI_FORMAT::DXGI_FORMAT_R32_UINT, 0);
ID3D11Buffer*const tmpVertexBuffer = _vertexBuffer.Get();
deviceContext->IASetVertexBuffers(0, 1, &tmpVertexBuffer, &stride, &offset);
}
| 33.663158
| 165
| 0.792683
|
SunlayGGX
|
c07dad1a74b81a723ddb921074b5400f48c3f465
| 3,219
|
cc
|
C++
|
src/Output/UserInterface/VerySimpleMessageManager.cc
|
rodrigowerberich/simple-terminal-chess
|
73c62251c4d130a896270c1e27b297da3ab0933f
|
[
"MIT"
] | null | null | null |
src/Output/UserInterface/VerySimpleMessageManager.cc
|
rodrigowerberich/simple-terminal-chess
|
73c62251c4d130a896270c1e27b297da3ab0933f
|
[
"MIT"
] | null | null | null |
src/Output/UserInterface/VerySimpleMessageManager.cc
|
rodrigowerberich/simple-terminal-chess
|
73c62251c4d130a896270c1e27b297da3ab0933f
|
[
"MIT"
] | null | null | null |
#include "Output/UserInterface/VerySimpleMessageManager.hh"
#include "Output/UserInterface/MessageSelector.hh"
namespace Chess{
namespace Output{
namespace UserInterface{
VerySimpleLanguagePackage::VerySimpleLanguagePackage(){
}
VerySimpleLanguagePackage::VerySimpleLanguagePackage(const LanguagePackFormat& languagePack):
m_languagePack{languagePack}{
}
const std::string& VerySimpleLanguagePackage::operator[](const std::string& messageName) const{
if(m_languagePack.count(messageName) > 0){
return m_languagePack.at(messageName);
}
return Chess::Output::UserInterface::ERROR_MESSAGE;
}
const std::vector<std::string> VerySimpleLanguagePackage::filterHeaders(const FilterFunction& filter) const{
std::vector<std::string> result;
for(const auto& pair:m_languagePack){
if(filter(pair.first)){
result.push_back(pair.first);
}
}
return result;
}
VerySimpleMessageManager::VerySimpleMessageManager(){
std::map<std::string, std::string> enLanguagePack;
enLanguagePack[MessageSelector::WELCOME_MESSAGE] = "Hi";
enLanguagePack[MessageSelector::GAME_START_WELCOME_MESSAGE] = "Welcome to Terminal Chess!!";
enLanguagePack[MessageSelector::QUIT_COMMAND_QUIT_WORD_1] = "exit";
enLanguagePack[MessageSelector::QUIT_COMMAND_QUIT_WORD_2] = "quit";
enLanguagePack[MessageSelector::QUIT_COMMAND_HELP_BEFORE_MESSAGE] = "To close the program type any of the following: ";
enLanguagePack[MessageSelector::QUIT_COMMAND_HELP_AFTER_MESSAGE] = ".";
enLanguagePack[MessageSelector::BEFORE_UNRECOGNIZED_INPUT_MESSAGE] = "The command";
enLanguagePack[MessageSelector::AFTER_UNRECOGNIZED_INPUT_MESSAGE] = "is not recognized";
enLanguagePack[MessageSelector::HELP_COMMAND_HELP_WORD_1] = "help";
std::map<std::string, std::string> ptBrLanguagePack;
ptBrLanguagePack[MessageSelector::WELCOME_MESSAGE] = "Oi";
ptBrLanguagePack[MessageSelector::GAME_START_WELCOME_MESSAGE] = "Bem vindo ao Xadrez no terminal!!";
ptBrLanguagePack[MessageSelector::QUIT_COMMAND_QUIT_WORD_1] = "sair";
ptBrLanguagePack[MessageSelector::QUIT_COMMAND_QUIT_WORD_2] = "finalizar";
ptBrLanguagePack["QUIT COMMAND QUIT WORD 3"] = "terminar";
ptBrLanguagePack[MessageSelector::QUIT_COMMAND_HELP_BEFORE_MESSAGE] = "Para sair do programa basta digitar um dos comandos listados a seguir";
ptBrLanguagePack[MessageSelector::QUIT_COMMAND_HELP_AFTER_MESSAGE] = ".";
ptBrLanguagePack[MessageSelector::BEFORE_UNRECOGNIZED_INPUT_MESSAGE] = "O comando";
ptBrLanguagePack[MessageSelector::AFTER_UNRECOGNIZED_INPUT_MESSAGE] = "não é reconhecido";
ptBrLanguagePack[MessageSelector::HELP_COMMAND_HELP_WORD_1] = "ajuda";
std::map<std::string, std::string> emptyLanguagePack;
m_languagePacks[LanguageSelector::EN] = {enLanguagePack};
m_languagePacks[LanguageSelector::PT_BR] = {ptBrLanguagePack};
m_languagePacks[""] = {emptyLanguagePack};
}
const LanguagePackageInterface& VerySimpleMessageManager::operator[](const std::string& languageSelector) const{
if(m_languagePacks.count(languageSelector) > 0){
return m_languagePacks.at(languageSelector);
}
return m_languagePacks.at("");
}
}
}
}
| 41.805195
| 146
| 0.769804
|
rodrigowerberich
|
c07fad4fc3ec50f681cd76c85f6a69d1ac5ad8f5
| 226
|
cpp
|
C++
|
main/HStringDatabase.cpp
|
Cararasu/holodec
|
d716d95a787ab7872a49a5c4fb930dc37be95ac7
|
[
"MIT"
] | 215
|
2017-06-22T16:23:52.000Z
|
2022-01-27T23:33:37.000Z
|
main/HStringDatabase.cpp
|
Cararasu/holodec
|
d716d95a787ab7872a49a5c4fb930dc37be95ac7
|
[
"MIT"
] | 4
|
2017-06-29T16:49:28.000Z
|
2019-02-07T19:58:57.000Z
|
main/HStringDatabase.cpp
|
Cararasu/holodec
|
d716d95a787ab7872a49a5c4fb930dc37be95ac7
|
[
"MIT"
] | 21
|
2017-10-14T02:10:41.000Z
|
2021-07-13T06:08:38.000Z
|
#include "HStringDatabase.h"
const char* holodec::holokey::system = "sys";
const char* holodec::holokey::architecture = "arch";
const char* holodec::holokey::bit = "bits";
const char* holodec::holokey::endianess = "endian";
| 28.25
| 52
| 0.716814
|
Cararasu
|
c083a04257c4ed0eaf1c268c6d15e9f9cac0aac4
| 675
|
cc
|
C++
|
project1/kernels/kernel_case10.cc
|
guoyuqi020/CompilerProject
|
1cd5375120bcdd2a2165d4741e9e987ce44237d5
|
[
"MIT"
] | null | null | null |
project1/kernels/kernel_case10.cc
|
guoyuqi020/CompilerProject
|
1cd5375120bcdd2a2165d4741e9e987ce44237d5
|
[
"MIT"
] | null | null | null |
project1/kernels/kernel_case10.cc
|
guoyuqi020/CompilerProject
|
1cd5375120bcdd2a2165d4741e9e987ce44237d5
|
[
"MIT"
] | null | null | null |
#include "../run.h"
void kernel_case10(float (&B)[10][10], float (&A)[8][8]) {
float temp1[8][8];
for (int i = 0;i < 8;++i){
for (int j = 0;j < 8;++j){
temp1[i][j] = 0;
if (0 <= i && i < 10) {
if (0 <= j && j < 10) {
if (0 <= i + 1 && i + 1 < 10) {
if (0 <= j && j < 10) {
if (0 <= i + 2 && i + 2 < 10) {
if (0 <= j && j < 10) {
temp1[i][j] += (B[i][j] + B[i + 1][j] + B[i + 2][j]) / 3;
}
}
}
}
}
}
}
}
for (int i = 0;i < 8;++i){
for (int j = 0;j < 8;++j){
A[i][j] = temp1[i][j];
}
}
}
| 23.275862
| 75
| 0.274074
|
guoyuqi020
|
c085f71aefcb47e1433a5c2368104a7467ca7291
| 1,933
|
hpp
|
C++
|
AddOns/Parse/Source/wali/UserFactoryHandler.hpp
|
jusito/WALi-OpenNWA
|
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
|
[
"MIT"
] | 15
|
2015-03-07T17:25:57.000Z
|
2022-02-04T20:17:00.000Z
|
src/wpds/AddOns/Parse/Source/wali/UserFactoryHandler.hpp
|
ucd-plse/mpi-error-prop
|
4367df88bcdc4d82c9a65b181d0e639d04962503
|
[
"BSD-3-Clause"
] | 1
|
2018-03-03T05:58:55.000Z
|
2018-03-03T12:26:10.000Z
|
src/wpds/AddOns/Parse/Source/wali/UserFactoryHandler.hpp
|
ucd-plse/mpi-error-prop
|
4367df88bcdc4d82c9a65b181d0e639d04962503
|
[
"BSD-3-Clause"
] | 15
|
2015-09-25T17:44:35.000Z
|
2021-07-18T18:25:38.000Z
|
#ifndef wali_WEIGHT_FACTORY_HANDLER_GUARD
#define wali_WEIGHT_FACTORY_HANDLER_GUARD 1
/**
* @author Nicholas Kidd
*/
#include "wali/IUserHandler.hpp"
namespace wali
{
class WeightFactory;
class MergeFnFactory;
/**
* Class for backwards compatability with WeightFactories.
*/
class UserFactoryHandler : public IUserHandler
{
public:
UserFactoryHandler(WeightFactory* wf,MergeFnFactory* mf);
virtual ~UserFactoryHandler();
/**
* Asserts that this.handlesElement(StrX(localname).get()).
*/
virtual void startElement( const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const Attributes& attributes);
/**
* Override to catch the endElement and
* invoke
*
* WeightFactory.getWeight( getCharactersString() )
*/
virtual void endElement( const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname);
/**
* @return the weight that WeightFactory
* parses out of the character string [str]
* from : "<Weight>str</Weight>"
*/
virtual sem_elem_t getWeight();
/**
* @return true if a MergeFn is specified
*/
virtual bool hasMergeFn();
/**
* @return the merge function that MergeFnFactory
* parses out of the character string [str]
* from : "<MergeFn>str</MergeFn>
*/
virtual merge_fn_t getMergeFn(sem_elem_t se);
protected:
WeightFactory* fWeightFactory;
MergeFnFactory* fMergeFactory;
bool fHasMergeFn; /** True if a Rule was parsed with a MergeFn */
sem_elem_t fWeight; /** Hold the weight returned by WeightFactory for </Weight> */
merge_fn_t fMergeFn; /** Hold the parsed merge_fn_t */
};
} // namespace wali
#endif // wali_WEIGHT_FACTORY_HANDLER_GUARD
| 25.434211
| 88
| 0.629074
|
jusito
|
c08b4efe3256fdc777de959083f9619be199abf4
| 19,274
|
cpp
|
C++
|
src/gtest/tree_internal_node_test.cpp
|
Nanolat/nldb
|
fa6c986c184cbdfa47b68220d30e4358325a274f
|
[
"Apache-2.0"
] | 9
|
2015-01-03T10:38:43.000Z
|
2021-01-04T01:02:36.000Z
|
src/gtest/tree_internal_node_test.cpp
|
Nanolat/nldb
|
fa6c986c184cbdfa47b68220d30e4358325a274f
|
[
"Apache-2.0"
] | null | null | null |
src/gtest/tree_internal_node_test.cpp
|
Nanolat/nldb
|
fa6c986c184cbdfa47b68220d30e4358325a274f
|
[
"Apache-2.0"
] | 2
|
2015-12-07T08:52:00.000Z
|
2021-12-21T17:56:08.000Z
|
/*
* (C) Copyright 2012, 2013 ThankyouSoft (http://ThankyouSoft.com/) and Nanolat(http://Nanolat.com).
* Writen by Kangmo Kim ( kangmo@nanolat.com )
*
* =================
* Apache v2 License
* =================
* http://www.apache.org/licenses/LICENSE-2.0.html
*
* Contributors :
* Kangmo Kim
*/
using namespace std;
#include <gtest/gtest.h>
// for htonl
#include <arpa/inet.h>
#include <nldb/nldb_common.h>
#include <nldb/nldb.h>
#include "tree_test_common.h"
class TreeInternalNodeTest : public testing::Test {
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(TreeInternalNodeTest, is_empty) {
tree_internal_node_t internal(TREE_KEY_LEN);
EXPECT_TRUE( internal.is_empty() );
ASSERT_TRUE( internal.put(KEY_01, NODE_01) == NLDB_OK );
EXPECT_TRUE( ! internal.is_empty() );
tree_node_t * node;
ASSERT_TRUE( internal.del(KEY_01, &node) == NLDB_OK );
EXPECT_TRUE( internal.is_empty() );
}
TEST_F(TreeInternalNodeTest, is_full) {
tree_internal_node_t internal(TREE_KEY_LEN);
ASSERT_TRUE( TREE_KEYS_PER_NODE == 3 );
EXPECT_TRUE( ! internal.is_full() );
ASSERT_TRUE( internal.put(KEY_01, NODE_01) == NLDB_OK );
EXPECT_TRUE( ! internal.is_full() );
ASSERT_TRUE( internal.put(KEY_02, NODE_02) == NLDB_OK );
EXPECT_TRUE( ! internal.is_full() );
ASSERT_TRUE( internal.put(KEY_03, NODE_03) == NLDB_OK );
EXPECT_TRUE( internal.is_full() );
tree_node_t * node = NULL;
ASSERT_TRUE( internal.del(KEY_01, &node) == NLDB_OK );
EXPECT_TRUE( ! internal.is_full() );
ASSERT_TRUE( internal.del(KEY_02, &node) == NLDB_OK );
EXPECT_TRUE( ! internal.is_full() );
ASSERT_TRUE( internal.del(KEY_03, &node) == NLDB_OK );
EXPECT_TRUE( ! internal.is_full() );
}
TEST_F(TreeInternalNodeTest, min_key) {
tree_internal_node_t internal(TREE_KEY_LEN);
ASSERT_TRUE( TREE_KEYS_PER_NODE == 3 );
EXPECT_TRUE( internal.min_key() == NULL );
ASSERT_TRUE( internal.put(KEY_02, NODE_02) == NLDB_OK );
EXPECT_TRUE( KEY_02_MATCHES( internal.min_key() ) );
ASSERT_TRUE( internal.put(KEY_01, NODE_01) == NLDB_OK );
EXPECT_TRUE( KEY_01_MATCHES( internal.min_key() ) );
ASSERT_TRUE( internal.put(KEY_03, NODE_03) == NLDB_OK );
EXPECT_TRUE( KEY_01_MATCHES( internal.min_key() ) );
tree_node_t * node = NULL;
ASSERT_TRUE( internal.del(KEY_01, &node) == NLDB_OK );
EXPECT_TRUE( KEY_02_MATCHES( internal.min_key() ) );
ASSERT_TRUE( internal.del(KEY_02, &node) == NLDB_OK );
EXPECT_TRUE( KEY_03_MATCHES( internal.min_key() ) );
ASSERT_TRUE( internal.del(KEY_03, &node) == NLDB_OK );
EXPECT_TRUE( internal.min_key() == NULL );
}
TEST_F(TreeInternalNodeTest, keys_with_right_children) {
tree_internal_node_t internal(TREE_KEY_LEN);
ASSERT_TRUE( TREE_KEYS_PER_NODE == 3 );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 0 );
ASSERT_TRUE( internal.put(KEY_02, NODE_02) == NLDB_OK );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 1 );
EXPECT_TRUE( KEY_MATCHES( internal.keys_with_right_children().min_key(), KEY_02 ) );
ASSERT_TRUE( internal.put(KEY_01, NODE_01) == NLDB_OK );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 2 );
EXPECT_TRUE( KEY_MATCHES( internal.keys_with_right_children().min_key(), KEY_01 KEY_02 ) );
ASSERT_TRUE( internal.put(KEY_03, NODE_03) == NLDB_OK );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 3 );
EXPECT_TRUE( KEY_MATCHES( internal.keys_with_right_children().min_key(), KEY_01 KEY_02 KEY_03 ) );
tree_node_t * node = NULL;
ASSERT_TRUE( internal.del(KEY_01, &node) == NLDB_OK );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 2 );
EXPECT_TRUE( KEY_MATCHES( internal.keys_with_right_children().min_key(), KEY_02 KEY_03 ) );
ASSERT_TRUE( internal.del(KEY_02, &node) == NLDB_OK );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 1 );
EXPECT_TRUE( KEY_MATCHES( internal.keys_with_right_children().min_key(), KEY_03 ) );
ASSERT_TRUE( internal.del(KEY_03, &node) == NLDB_OK );
EXPECT_TRUE( internal.keys_with_right_children().key_count() == 0 );
EXPECT_TRUE( internal.keys_with_right_children().min_key() == NULL );
}
TEST_F(TreeInternalNodeTest, left_child) {
tree_internal_node_t internal(TREE_KEY_LEN);
tree_internal_node_t left_child(TREE_KEY_LEN);
(void)internal.set_left_child( & left_child );
EXPECT_TRUE( left_child.parent() == & internal);
}
// Test put/del/find_serving_node_by_key where an internal node's child is an internal node.
TEST_F(TreeInternalNodeTest, put_del_find_serving_internal_node) {
tree_internal_node_t internal(TREE_KEY_LEN);
ASSERT_TRUE( TREE_KEYS_PER_NODE == 3 );
tree_internal_node_t left_child(TREE_KEY_LEN);
(void)internal.set_left_child( & left_child );
tree_node_t * node = NULL;
// Finding a serving node without any key in the internal node - should return the left child node.
{
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
}
// put : put a new key
ASSERT_TRUE( internal.put(KEY_02, NODE_02) == NLDB_OK );
// test find_serving_node_by_key
{
// KEY_01 is less than KEY_02. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_02 should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_02) );
// KEY_03 is greater than KEY_02, so it should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_02) );
// KEY_04 is greater than KEY_02, so it should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_02) );
}
// put : put a new key
ASSERT_TRUE( internal.put(KEY_04, NODE_04) == NLDB_OK );
// test find_serving_node_by_key
{
// KEY_01 is less than KEY_02. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_02 should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_02) );
// KEY_03 is greater than KEY_02, so it should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_02) );
// KEY_04 should be served by the NODE_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
// KEY_05 should be served by the NODE_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
}
tree_leaf_node_t new_node_02(TREE_KEY_LEN); tree_leaf_node_t * NEW_NODE_02 = & new_node_02;
// put : replace an existing key
ASSERT_TRUE( internal.put(KEY_02, NEW_NODE_02) == NLDB_OK );
// test find_serving_node_by_key
{
// KEY_01 is less than KEY_02. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_02 should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NEW_NODE_02) );
// KEY_03 is greater than KEY_02, so it should be served by the NODE_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NEW_NODE_02) );
// KEY_04 should be served by the NODE_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
// KEY_05 should be served by the NODE_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
}
// del : del a non-existing key
ASSERT_TRUE( internal.del(KEY_03, &node) == NLDB_OK );
EXPECT_TRUE( node == NULL );
// del : del a existing key.
ASSERT_TRUE( internal.del(KEY_02, &node) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NEW_NODE_02) );
// test find_serving_node_by_key
{
// KEY_01, KEY_02, KEY_03 is less than KEY_04. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_04 should be served by the NODE_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
// KEY_05 should be served by the NODE_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
}
ASSERT_TRUE( internal.del(KEY_04, &node) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NODE_04) );
// find_serving_node_by_key
{
// No key exists in the internal node. All keys should be served by the left_child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
}
}
// Test put/del/find_serving_node_by_key where an internal node's child is a leaf node.
TEST_F(TreeInternalNodeTest, put_del_find_serving_leaf_node) {
tree_internal_node_t internal(TREE_KEY_LEN);
ASSERT_TRUE( TREE_KEYS_PER_NODE == 3 );
tree_leaf_node_t left_child(TREE_KEY_LEN);
tree_leaf_node_t leaf_02(TREE_KEY_LEN); tree_leaf_node_t * LEAF_02 = & leaf_02;
tree_leaf_node_t leaf_04(TREE_KEY_LEN); tree_leaf_node_t * LEAF_04 = & leaf_04;
(void)internal.set_left_child( & left_child );
tree_node_t * node = NULL;
// Finding a serving node without any key in the internal node - should return the left child node.
{
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
}
// put : put a new key
ASSERT_TRUE( internal.put(KEY_02, LEAF_02) == NLDB_OK );
// test find_serving_node_by_key
{
// KEY_01 is less than KEY_02. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_02 should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_02) );
// KEY_03 is greater than KEY_02, so it should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_02) );
// KEY_04 is greater than KEY_02, so it should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_02) );
}
// put : put a new key
ASSERT_TRUE( internal.put(KEY_04, LEAF_04) == NLDB_OK );
// test find_serving_node_by_key
{
// KEY_01 is less than KEY_02. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_02 should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_02) );
// KEY_03 is greater than KEY_02, so it should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_02) );
// KEY_04 should be served by the LEAF_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
// KEY_05 should be served by the LEAF_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
}
tree_leaf_node_t new_leaf_02(TREE_KEY_LEN); tree_leaf_node_t * NEW_LEAF_02 = & new_leaf_02;
// put : replace an existing key
ASSERT_TRUE( internal.put(KEY_02, NEW_LEAF_02) == NLDB_OK );
// test find_serving_node_by_key
{
// KEY_01 is less than KEY_02. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_02 should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NEW_LEAF_02) );
// KEY_03 is greater than KEY_02, so it should be served by the LEAF_02.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NEW_LEAF_02) );
// KEY_04 should be served by the LEAF_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
// KEY_05 should be served by the LEAF_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
}
// del : del a non-existing key
ASSERT_TRUE( internal.del(KEY_03, &node) == NLDB_OK );
EXPECT_TRUE( node == NULL );
// del : del a existing key.
ASSERT_TRUE( internal.del(KEY_02, &node) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, NEW_LEAF_02) );
// test find_serving_node_by_key
{
// KEY_01, KEY_02, KEY_03 is less than KEY_04. So KEY_01 should be served by the left child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
// KEY_04 should be served by the LEAF_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
// KEY_05 should be served by the LEAF_04.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
}
ASSERT_TRUE( internal.del(KEY_04, &node) == NLDB_OK );
EXPECT_TRUE( NODE_MATCHES(node, LEAF_04) );
// find_serving_node_by_key
{
// No key exists in the internal node. All keys should be served by the left_child.
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_01, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_02, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_03, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_04, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
ASSERT_TRUE( internal.find_serving_node_by_key(KEY_05, &node, NULL) == NLDB_OK );
EXPECT_TRUE( node == & left_child);
}
}
TEST_F(TreeInternalNodeTest, merge_with) {
tree_internal_node_t internal1(TREE_KEY_LEN);
tree_internal_node_t internal2(TREE_KEY_LEN);
// merge_with is not supported yet.
ASSERT_TRUE( internal1.merge_with(&internal2) == NLDB_ERROR_UNSUPPORTED_FEATURE );
}
// test split function where the children are internal nodes
TEST_F(TreeInternalNodeTest, split_with_two_keys_where_children_are_internal_nodes) {
tree_internal_node_t org_internal(TREE_KEY_LEN);
tree_internal_node_t left_child(TREE_KEY_LEN);
(void) org_internal.set_left_child( &left_child );
// put three keys
ASSERT_TRUE( org_internal.put(KEY_03, NODE_03) == NLDB_OK );
ASSERT_TRUE( org_internal.put(KEY_01, NODE_01) == NLDB_OK );
ASSERT_TRUE( org_internal.put(KEY_05, NODE_05) == NLDB_OK );
// the original internal node should have KEY_01, KEY_03, KEY_05
EXPECT_TRUE( org_internal.keys_with_right_children().key_count() == 3 );
EXPECT_TRUE( KEY_MATCHES( org_internal.keys_with_right_children().min_key(), KEY_01 KEY_03 KEY_05) );
void * mid_key;
tree_internal_node_t * new_right_internal;
ASSERT_TRUE( org_internal.split( &new_right_internal, &mid_key ) == NLDB_OK );
EXPECT_TRUE( KEY_03_MATCHES( mid_key ) );
// the original internal node should have KEY_01
EXPECT_TRUE( org_internal.keys_with_right_children().key_count() == 1 );
EXPECT_TRUE( KEY_MATCHES( org_internal.keys_with_right_children().min_key(), KEY_01 ) );
// the new right internal node should have KEY_05
EXPECT_TRUE( new_right_internal->keys_with_right_children().key_count() == 1 );
EXPECT_TRUE( KEY_MATCHES( new_right_internal->keys_with_right_children().min_key(), KEY_05 ) );
}
// test split function where the children are leaf nodes
TEST_F(TreeInternalNodeTest, split_with_two_keys_where_children_are_leaf_nodes) {
tree_internal_node_t org_internal(TREE_KEY_LEN);
tree_leaf_node_t left_child(TREE_KEY_LEN);
tree_leaf_node_t leaf_01(TREE_KEY_LEN); tree_leaf_node_t * LEAF_01 = & leaf_01;
tree_leaf_node_t leaf_03(TREE_KEY_LEN); tree_leaf_node_t * LEAF_03 = & leaf_03;
tree_leaf_node_t leaf_05(TREE_KEY_LEN); tree_leaf_node_t * LEAF_05 = & leaf_05;
(void) org_internal.set_left_child( &left_child );
// put three keys
ASSERT_TRUE( org_internal.put(KEY_03, LEAF_03) == NLDB_OK );
ASSERT_TRUE( org_internal.put(KEY_01, LEAF_01) == NLDB_OK );
ASSERT_TRUE( org_internal.put(KEY_05, LEAF_05) == NLDB_OK );
// the original internal node should have KEY_01, KEY_03, KEY_05
EXPECT_TRUE( org_internal.keys_with_right_children().key_count() == 3 );
EXPECT_TRUE( KEY_MATCHES( org_internal.keys_with_right_children().min_key(), KEY_01 KEY_03 KEY_05) );
void * mid_key;
tree_internal_node_t * new_right_internal;
ASSERT_TRUE( org_internal.split( &new_right_internal, &mid_key ) == NLDB_OK );
EXPECT_TRUE( KEY_03_MATCHES( mid_key ) );
// the original internal node should have KEY_01
EXPECT_TRUE( org_internal.keys_with_right_children().key_count() == 1 );
EXPECT_TRUE( KEY_MATCHES( org_internal.keys_with_right_children().min_key(), KEY_01 ) );
// the new right internal node should have KEY_05
EXPECT_TRUE( new_right_internal->keys_with_right_children().key_count() == 1 );
EXPECT_TRUE( KEY_MATCHES( new_right_internal->keys_with_right_children().min_key(), KEY_05 ) );
}
| 36.573055
| 102
| 0.737315
|
Nanolat
|
c08e54a902cfa94f1cc74dbeeeb14ac2004baea0
| 903
|
cpp
|
C++
|
queue_fps.cpp
|
HefnySco/yolov5-opencv-dnn-cpp
|
3d653d49562d6e09c759906372278bd52f8f20e2
|
[
"Apache-2.0"
] | null | null | null |
queue_fps.cpp
|
HefnySco/yolov5-opencv-dnn-cpp
|
3d653d49562d6e09c759906372278bd52f8f20e2
|
[
"Apache-2.0"
] | null | null | null |
queue_fps.cpp
|
HefnySco/yolov5-opencv-dnn-cpp
|
3d653d49562d6e09c759906372278bd52f8f20e2
|
[
"Apache-2.0"
] | null | null | null |
#include "queue_fps.hpp"
// template <typename T>
// void CQueueFPS<T>::push(const T& entry)
// {
// //std::lock_guard<std::mutex> lock(mutex);
// std::queue<T>::push(entry);
// counter += 1;
// if (counter == 1)
// {
// //Start counting from a second frame (warmup).
// tm.reset();
// tm.start();
// }
// }
// template <typename T>
// T CQueueFPS<T>::get()
// {
// std::lock_guard<std::mutex> lock(mutex);
// T entry = this->front();
// this->pop();
// return entry;
// }
// template <typename T>
// float CQueueFPS<T>::getFPS()
// {
// tm.stop();
// double fps = counter; // / tm.getTimeSec();
// tm.start();
// return static_cast<float>(fps);
// }
// template <typename T>
// void CQueueFPS<T>::clear()
// {
// std::lock_guard<std::mutex> lock(mutex);
// while (!this->empty())
// this->pop();
// }
| 21
| 57
| 0.51495
|
HefnySco
|
c08f1f57ccf010e93eee81e6806f696ec66148ef
| 2,690
|
hpp
|
C++
|
libraries/chain/include/graphene/chain/hardfork.hpp
|
siwelo/bitshares-2
|
03561bfcf97801b44863bd51c400aae3ba51e3b0
|
[
"MIT"
] | null | null | null |
libraries/chain/include/graphene/chain/hardfork.hpp
|
siwelo/bitshares-2
|
03561bfcf97801b44863bd51c400aae3ba51e3b0
|
[
"MIT"
] | null | null | null |
libraries/chain/include/graphene/chain/hardfork.hpp
|
siwelo/bitshares-2
|
03561bfcf97801b44863bd51c400aae3ba51e3b0
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Any modified source or binaries are used only with the BitShares network.
*
* 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
#define HARDFORK_357_TIME (fc::time_point_sec( 1444416300 ))
#define HARDFORK_359_TIME (fc::time_point_sec( 1444416300 ))
#define HARDFORK_385_TIME (fc::time_point_sec( 1445558400 )) // October 23 enforce PARENT.CHILD and allow short names
#define HARDFORK_393_TIME (fc::time_point_sec( 2445558400 )) // Refund order creation fee on cancel
#define HARDFORK_409_TIME (fc::time_point_sec( 1446652800 ))
#define HARDFORK_413_TIME (fc::time_point_sec( 1446652800 ))
#define HARDFORK_415_TIME (fc::time_point_sec( 1446652800 ))
#define HARDFORK_416_TIME (fc::time_point_sec( 1446652800 ))
#define HARDFORK_419_TIME (fc::time_point_sec( 1446652800 ))
// #436 Prevent margin call from being triggered unless feed < call price
#define HARDFORK_436_TIME (fc::time_point_sec( 1450288800 ))
// #445 Refund create order fees on cancel
#define HARDFORK_445_TIME (fc::time_point_sec( 1450288800 ))
// #453 Hardfork to retroactively correct referral percentages
#define HARDFORK_453_TIME (fc::time_point_sec( 1450288800 ))
// #480 Fix non-CORE MIA core_exchange_rate check
#define HARDFORK_480_TIME (fc::time_point_sec( 1450378800 ))
// #483 Operation history numbering change
#define HARDFORK_483_TIME (fc::time_point_sec( 1450378800 ))
| 57.234043
| 208
| 0.787732
|
siwelo
|
c08fc8783da592a19b84761b63d415b615e81e3a
| 1,672
|
hpp
|
C++
|
inc/motoro/http_request_parser.hpp
|
ztgreat/cpp
|
0cd0643c47ec6c252968d7bb71d62f3e14c1996a
|
[
"Apache-2.0"
] | null | null | null |
inc/motoro/http_request_parser.hpp
|
ztgreat/cpp
|
0cd0643c47ec6c252968d7bb71d62f3e14c1996a
|
[
"Apache-2.0"
] | null | null | null |
inc/motoro/http_request_parser.hpp
|
ztgreat/cpp
|
0cd0643c47ec6c252968d7bb71d62f3e14c1996a
|
[
"Apache-2.0"
] | null | null | null |
#ifndef AB62B027_AAFD_4611_8EF3_19FF408D5F97
#define AB62B027_AAFD_4611_8EF3_19FF408D5F97
#include <string>
#include "lib/http_parser.h"
#include "request.hpp"
namespace motoro {
class http_request_parser {
public:
http_request_parser() = delete;
http_request_parser(motoro::request &req);
virtual ~http_request_parser() = default;
bool parse(const std::string &str);
bool parse(const char *, size_t);
const std::string &get_body() const;
std::string &get_body();
bool keep_alive() const;
bool upgrade() const;
bool message_complete();
private:
struct tmp_ {
std::pair<std::string, std::string> pair;
http_request_parser *parser;
};
private:
tmp_ tmp;
http_parser parser;
http_parser_settings settings;
motoro::request &req;
std::string body;
private:
static int on_message_begin(http_parser *p);
static int on_message_complete(http_parser *p);
static int on_header_field(http_parser *p, const char *buf, size_t len);
static int on_header_value(http_parser *p, const char *buf, size_t len);
static int on_url(http_parser *p, const char *buf, size_t len);
static int on_status(http_parser *p, const char *at, size_t length);
static int on_body(http_parser *p, const char *buf, size_t len);
static int on_headers_complete(http_parser *p);
static int on_chunk_header(http_parser *p);
static int on_chunk_complete(http_parser *p);
};
}
#endif /* AB62B027_AAFD_4611_8EF3_19FF408D5F97 */
| 23.885714
| 80
| 0.648923
|
ztgreat
|
c0902aee5c38de2f8bee77ff27681024f51f75bc
| 2,070
|
cpp
|
C++
|
tests/greedy/mates.cpp
|
gcp/verbose-parakeet
|
6f5e2bba614f2704d225da75704e8af3b0e124e7
|
[
"MIT"
] | 1
|
2021-04-16T00:00:28.000Z
|
2021-04-16T00:00:28.000Z
|
tests/greedy/mates.cpp
|
gcp/verbose-parakeet
|
6f5e2bba614f2704d225da75704e8af3b0e124e7
|
[
"MIT"
] | null | null | null |
tests/greedy/mates.cpp
|
gcp/verbose-parakeet
|
6f5e2bba614f2704d225da75704e8af3b0e124e7
|
[
"MIT"
] | null | null | null |
#include <catch2/catch.hpp>
#include <libchess/position.hpp>
#include <string>
#include "../../src/search/controller.hpp"
#include "../../src/search/greedy/search.hpp"
auto info_handler = [](int depth, int score, std::uint64_t nodes, int time, const PV &pv) {};
TEST_CASE("Greedy - Checkmate") {
const std::pair<std::string, std::string> tests[] = {
{"3k4/8/3K4/8/5R2/8/8/8 w - - 0 1", "f4f8"},
{"8/8/8/5r2/8/3k4/8/3K4 b - - 0 1", "f5f1"},
{"1k1r2R1/8/1K6/8/8/8/8/8 w - - 0 1", "g8d8"},
{"8/8/8/8/8/1k6/8/1K1R2r1 b - - 0 1", "g1d1"},
};
for (const auto &[fen, movestr] : tests) {
INFO(fen);
controller.reset();
controller.set_depth(2);
auto pos = libchess::Position{fen};
const auto [bestmove, _] = greedy::search(pos, info_handler);
REQUIRE(static_cast<std::string>(bestmove) == movestr);
}
}
TEST_CASE("Greedy - Checkmate with castling") {
const std::pair<std::string, std::string> tests[] = {
{"8/8/8/8/8/8/7R/1k2K2R w K - 0 1", "e1g1"},
{"1K2k2r/7r/8/8/8/8/8/8 b k - 0 1", "e8g8"},
{"8/8/8/8/8/8/R7/R3K2k w Q - 0 1", "e1c1"},
{"r3k2K/r7/8/8/8/8/8/8 b q - 0 1", "e8c8"},
};
for (const auto &[fen, movestr] : tests) {
INFO(fen);
controller.reset();
controller.set_depth(2);
auto pos = libchess::Position{fen};
const auto [bestmove, _] = greedy::search(pos, info_handler);
REQUIRE(static_cast<std::string>(bestmove) == movestr);
}
}
TEST_CASE("Greedy - Checkmate 50moves priority") {
const std::pair<std::string, std::string> tests[] = {
{"7k/1R6/R7/8/8/8/8/4K3 w - - 99 1", "a6a8"},
{"4k3/8/8/8/8/r7/1r6/7K b - - 99 1", "a3a1"},
};
for (const auto &[fen, movestr] : tests) {
INFO(fen);
controller.reset();
controller.set_depth(2);
auto pos = libchess::Position{fen};
const auto [bestmove, _] = greedy::search(pos, info_handler);
REQUIRE(static_cast<std::string>(bestmove) == movestr);
}
}
| 34.5
| 93
| 0.556522
|
gcp
|
6a53bbf62d3887d57d03a7b14c77e8887376b668
| 2,842
|
cpp
|
C++
|
00004_median-of-two-sorted-arrays/191003-2.cpp
|
yanlinlin82/leetcode
|
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
|
[
"MIT"
] | 6
|
2019-10-23T01:07:29.000Z
|
2021-12-05T01:51:16.000Z
|
00004_median-of-two-sorted-arrays/191003-2.cpp
|
yanlinlin82/leetcode
|
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
|
[
"MIT"
] | null | null | null |
00004_median-of-two-sorted-arrays/191003-2.cpp
|
yanlinlin82/leetcode
|
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
|
[
"MIT"
] | 1
|
2021-12-03T06:54:57.000Z
|
2021-12-03T06:54:57.000Z
|
// https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
#include <cstdio>
#include <vector>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size();
int n2 = nums2.size();
int p1 = 0, q1 = n1, k1 = n1 / 2;
int p2 = 0, q2 = n2, k2 = (n1 + n2) / 2 - k1;
for (;;) {
if (k1 > 0 && k2 < n2 && nums1[k1 - 1] > nums2[k2]) {
int s = (q2 - k2) / 2;
if (s > k1 - p1) s = k1 - p1;
if (s == 0) s = 1;
q1 = k1 - 1; p2 = k2 + 1;
k1 -= s; k2 += s;
continue;
} else if (k2 > 0 && k1 < n1 && nums2[k2 - 1] > nums1[k1]) {
int s = (q1 - k1) / 2;
if (s > k2 - p2) s = k2 - p2;
if (s == 0) s = 1;
p1 = k1 + 1; q2 = k2 - 1;
k1 += s; k2 -= s;
continue;
}
break;
}
double v;
if (k1 < n1 && k2 < n2) {
v = (nums1[k1] <= nums2[k2] ? nums1[k1] : nums2[k2]);
} else if (k1 < n1) {
v = nums1[k1];
} else if (k2 < n2) {
v = nums2[k2];
} else {
v = 0;
}
if ((n1 + n2) % 2 == 0) {
double v2;
if (k1 > 0 && k2 > 0) {
v2 = (nums1[k1 - 1] >= nums2[k2 - 1] ? nums1[k1 - 1] : nums2[k2 - 1]);
} else if (k1 > 0) {
v2 = nums1[k1 - 1];
} else if (k2 > 0) {
v2 = nums2[k2 - 1];
} else {
v2 = 0;
}
v = (v + v2) / 2;
}
return v;
}
};
int main()
{
Solution s;
{
vector<int> nums1 = { 1, 3 };
vector<int> nums2 = { 2 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 2.0
}
{
vector<int> nums1 = { 1, 2 };
vector<int> nums2 = { 3, 4 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 2.5
}
{
vector<int> nums1 = { 1, 2, 3 };
vector<int> nums2 = { 1, 2 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 2
}
{
vector<int> nums1 = { 2, 3, 4 };
vector<int> nums2 = { 1 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 2.5
}
{
vector<int> nums1 = { 2, 3, 4 };
vector<int> nums2 = { };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 3
}
{
vector<int> nums1 = { 1, 3, 5 };
vector<int> nums2 = { 2, 4, 6 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 3.5
}
{
vector<int> nums1 = { 100000 };
vector<int> nums2 = { 100001 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 100000.5
}
{
vector<int> nums1 = { 1, 2, 4 };
vector<int> nums2 = { 3, 5, 6, 7 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 4
}
{
vector<int> nums1 = { 4, 5, 6, 7 };
vector<int> nums2 = { 1 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 5
}
{
vector<int> nums1 = { 1, 5, 6, 7 };
vector<int> nums2 = { 1, 6 };
printf("%f\n", s.findMedianSortedArrays(nums1, nums2)); // answer: 5.5
}
return 0;
}
| 22.919355
| 77
| 0.507741
|
yanlinlin82
|
6a573296bb9d824cd29ab79b4ee957e6cf5fcf31
| 947
|
cpp
|
C++
|
src/widgets/treewidgetitem.cpp
|
tamlok/vnote
|
1318427bb742b77eb2f2e3da3c5796f159f2c2ed
|
[
"MIT"
] | 8,054
|
2016-10-19T14:59:52.000Z
|
2020-10-11T06:21:15.000Z
|
src/widgets/treewidgetitem.cpp
|
tamlok/vnote
|
1318427bb742b77eb2f2e3da3c5796f159f2c2ed
|
[
"MIT"
] | 1,491
|
2017-03-06T02:31:32.000Z
|
2020-10-11T02:14:32.000Z
|
src/widgets/treewidgetitem.cpp
|
tamlok/vnote
|
1318427bb742b77eb2f2e3da3c5796f159f2c2ed
|
[
"MIT"
] | 986
|
2017-02-14T05:45:13.000Z
|
2020-10-10T07:42:31.000Z
|
#include "treewidgetitem.h"
#include <QTreeWidget>
#include <QVariant>
#include <core/global.h>
using namespace vnotex;
TreeWidgetItem::TreeWidgetItem(QTreeWidget *p_parent, const QStringList &p_strings, int p_type)
: QTreeWidgetItem(p_parent, p_strings, p_type)
{
}
bool TreeWidgetItem::operator<(const QTreeWidgetItem &p_other) const
{
int column = treeWidget() ? treeWidget()->sortColumn() : 0;
// Check ComparisonRole first.
QVariant v1 = data(column, Role::ComparisonRole);
QVariant v2 = p_other.data(column, Role::ComparisonRole);
if (v1.isNull() || v2.isNull()) {
v1 = data(column, Qt::DisplayRole);
v2 = p_other.data(column, Qt::DisplayRole);
}
if (v1.canConvert<QString>() && v2.canConvert<QString>()) {
const auto s1 = v1.toString().toLower();
const auto s2 = v2.toString().toLower();
return s1 < s2;
}
return QTreeWidgetItem::operator<(p_other);
}
| 27.057143
| 95
| 0.669483
|
tamlok
|
6a584bc0ece1e2582dff3e74cd4358468d55c914
| 2,358
|
cpp
|
C++
|
iceoryx_posh/source/roudi_environment/roudi_environment.cpp
|
Karsten1987/iceoryx
|
e5c23eaf5c351ef0095e43673282867b8d060026
|
[
"Apache-2.0"
] | 2
|
2019-11-04T05:02:53.000Z
|
2019-11-04T05:19:20.000Z
|
iceoryx_posh/source/roudi_environment/roudi_environment.cpp
|
Karsten1987/iceoryx
|
e5c23eaf5c351ef0095e43673282867b8d060026
|
[
"Apache-2.0"
] | null | null | null |
iceoryx_posh/source/roudi_environment/roudi_environment.cpp
|
Karsten1987/iceoryx
|
e5c23eaf5c351ef0095e43673282867b8d060026
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "iceoryx_posh/internal/roudi/roudi_multi_process.hpp"
#include "iceoryx_utils/log/logmanager.hpp"
#include "iceoryx_utils/cxx/helplets.hpp"
#include "iceoryx_utils/internal/posix_wrapper/shared_memory_object/memory_map.hpp"
namespace iox
{
namespace roudi
{
RouDiEnvironment::RouDiEnvironment(RouDiMultiProcess* roudiApp)
{
iox::log::LogManager::GetLogManager().SetDefaultLogLevel(iox::log::LogLevel::kWarn);
m_roudiApp = roudiApp;
}
RouDiEnvironment::RouDiEnvironment(const RouDiConfig_t& roudiConfig, RouDiApp::MonitoringMode monitoringMode)
: RouDiEnvironment(new RouDiMultiProcess(monitoringMode, false, roudiConfig))
{
}
RouDiEnvironment::~RouDiEnvironment()
{
m_runtimes.cleanupRuntimes();
delete m_roudiApp;
}
RouDiEnvironment::RouDiEnvironment(RouDiEnvironment&& rhs)
: m_runtimes(std::move(rhs.m_runtimes))
{
this->m_roudiApp = rhs.m_roudiApp;
rhs.m_roudiApp = nullptr;
this->m_interOpWaitingTime = rhs.m_interOpWaitingTime;
}
RouDiEnvironment& RouDiEnvironment::operator=(RouDiEnvironment&& rhs)
{
m_runtimes = std::move(rhs.m_runtimes);
this->m_roudiApp = rhs.m_roudiApp;
rhs.m_roudiApp = nullptr;
this->m_interOpWaitingTime = rhs.m_interOpWaitingTime;
return *this;
}
void RouDiEnvironment::SetInterOpWaitingTime(const std::chrono::milliseconds& v)
{
m_interOpWaitingTime = v;
}
void RouDiEnvironment::InterOpWait()
{
std::this_thread::sleep_for(m_interOpWaitingTime);
}
void RouDiEnvironment::CleanupAppResources(const std::string& name)
{
m_runtimes.eraseRuntime(name);
}
} // namespace roudi
} // namespace iox
| 30.623377
| 109
| 0.7676
|
Karsten1987
|
6a5b74f4d106edf9a39a1b7f487d20212b307c68
| 2,986
|
cpp
|
C++
|
source/third_party/pevents/sample.cpp
|
GPUOpen-Tools/radeon_memory_visualizer
|
309ac5b04b870aef408603eaac4bd727d5d3e698
|
[
"MIT"
] | 86
|
2020-05-14T17:20:22.000Z
|
2022-01-21T22:53:24.000Z
|
source/third_party/pevents/sample.cpp
|
GPUOpen-Tools/radeon_memory_visualizer
|
309ac5b04b870aef408603eaac4bd727d5d3e698
|
[
"MIT"
] | 6
|
2020-05-16T18:50:00.000Z
|
2022-01-21T15:30:16.000Z
|
source/third_party/pevents/sample.cpp
|
GPUOpen-Tools/radeon_memory_visualizer
|
309ac5b04b870aef408603eaac4bd727d5d3e698
|
[
"MIT"
] | 11
|
2020-10-15T15:55:56.000Z
|
2022-03-16T20:38:29.000Z
|
/*
* WIN32 Events for POSIX
* Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net>
* Copyright (C) 2011 - 2015 by NeoSmart Technologies
* This code is released under the terms of the MIT License
*/
#include <iostream>
#include <assert.h>
#include <thread>
#include <chrono>
#include <atomic>
#include <signal.h>
#include <random>
//On Windows, you must include Winbase.h/Synchapi.h/Windows.h before pevents.h
#ifdef _WIN32
#include <Windows.h>
#endif
#include "pevents.h"
using namespace neosmart;
using namespace std;
neosmart_event_t events[3]; //letters, numbers, abort
std::atomic<bool> interrupted { false };
char letter = '?';
int number = -1;
char lastChar = '\0';
int lastNum = -1;
void intHandler(int sig) {
interrupted = true;
//unfortunately you can't use SetEvent here because posix signal handlers
//shouldn't use any non-reentrant code (like printf)
//on x86/x64, std::atomic<bool> is just a fancy way of doing a memory
//barrier and nothing more, so it is safe
}
void letters()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(0, 3000);
for (uint32_t i = 0; WaitForEvent(events[2], dis(gen)) == WAIT_TIMEOUT; ++i)
{
letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i%26];
SetEvent(events[0]);
}
}
void numbers()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(0, 3000);
for (uint32_t i = 0; WaitForEvent(events[2], dis(gen)) == WAIT_TIMEOUT; ++i)
{
number = i;
SetEvent(events[1]);
}
}
int main()
{
events[0] = CreateEvent(); //letters auto-reset event
events[1] = CreateEvent(); //numbers auto-reset event
events[2] = CreateEvent(true); //abort manual-reset event
//after the abort event has been created
struct sigaction act = {0};
act.sa_handler = intHandler; //trigger abort on ctrl+c
sigaction(SIGINT, &act, NULL);
std::thread thread1(letters);
std::thread thread2(numbers);
for (uint32_t i = 0; lastChar != 'Z'; ++i)
{
if (interrupted)
{
printf("Interrupt triggered.. Aborting!\n");
break;
}
int index = -1;
int result = WaitForMultipleEvents(events, 2, false, -1, index);
if (result == WAIT_TIMEOUT)
{
cout << "Timeout!" << endl;
}
else if (result != 0)
{
cout << "Error in wait!" << endl;
}
else if (index == 0)
{
assert(lastChar != letter);
cout << letter << endl;
lastChar = letter;
}
else if (index == 1)
{
assert(lastNum != number);
cout << number << endl;
lastNum = number;
}
else
{
cout << "ERROR! Unexpected index: " << index << endl;
exit(-1);
}
}
//You can't just DestroyEvent() and exit - it'll segfault
//That's because letters() and numbers() will call SetEvent on a destroyed event
//You must *never* call SetEvent/ResetEvent on a destroyed event!
//So we set an abort event and wait for the helper threads to exit
//Set the abort
SetEvent(events[2]);
thread1.join();
thread2.join();
for (auto event : events)
{
DestroyEvent(event);
}
}
| 22.621212
| 81
| 0.666443
|
GPUOpen-Tools
|
6a5bc37a5a78ee392bcf47fafb2eae1bc2dad1d4
| 537
|
cpp
|
C++
|
Mya/Sound/Music.cpp
|
Wolchy/Uno
|
3ebb485b7e71b801cdd08d2cf97bbbb9579f44b5
|
[
"MIT"
] | null | null | null |
Mya/Sound/Music.cpp
|
Wolchy/Uno
|
3ebb485b7e71b801cdd08d2cf97bbbb9579f44b5
|
[
"MIT"
] | null | null | null |
Mya/Sound/Music.cpp
|
Wolchy/Uno
|
3ebb485b7e71b801cdd08d2cf97bbbb9579f44b5
|
[
"MIT"
] | null | null | null |
#include "Music.h"
Music::Music(std::string path){
music = Mix_LoadMUS(path.c_str());
if(music)
std::cout << "Loaded music: " << path.c_str() << "!" << std::endl;
else
std::cout << "Error Loading music: " << path.c_str() << ", with error: " << Mix_GetError() << "!" << std::endl;
}
void Music::destroy() {
Mix_FreeMusic(music);
music = NULL;
}
void Music::play() {
Mix_PlayMusic(music, 0);
}
void Music::pause() {
Mix_PauseMusic();
}
void Music::resume() {
Mix_ResumeMusic();
}
void Music::stop() {
Mix_HaltMusic();
}
| 17.322581
| 113
| 0.607076
|
Wolchy
|
6a5cc849d8b781408339aefae2fbcdfaec77f6eb
| 3,176
|
hpp
|
C++
|
src/main/cpp/Balau/Network/Http/Server/HttpWebApps/CannedHttpWebApp.hpp
|
borasoftware/balau
|
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
|
[
"Apache-2.0"
] | 6
|
2018-12-30T15:09:26.000Z
|
2020-04-20T09:27:59.000Z
|
src/main/cpp/Balau/Network/Http/Server/HttpWebApps/CannedHttpWebApp.hpp
|
borasoftware/balau
|
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
|
[
"Apache-2.0"
] | null | null | null |
src/main/cpp/Balau/Network/Http/Server/HttpWebApps/CannedHttpWebApp.hpp
|
borasoftware/balau
|
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
|
[
"Apache-2.0"
] | 2
|
2019-11-12T08:07:16.000Z
|
2019-11-29T11:19:47.000Z
|
// @formatter:off
//
// Balau core C++ library
//
// Copyright (C) 2017 Bora Software (contact@borasoftware.com)
//
// 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 CannedHttpWebApp.hpp
///
/// An HTTP web application handler that serves a fixed response for each request method.
///
#ifndef COM_BORA_SOFTWARE__BALAU_NETWORK_HTTP_SERVER_HTTP_WEB_APPS__CANNED_HTTP_WEB_APP
#define COM_BORA_SOFTWARE__BALAU_NETWORK_HTTP_SERVER_HTTP_WEB_APPS__CANNED_HTTP_WEB_APP
#include <Balau/Network/Http/Server/HttpWebApp.hpp>
namespace Balau {
class BalauLogger;
class EnvironmentProperties;
namespace Network::Http::HttpWebApps {
///
/// An HTTP web application handler that serves a fixed response for each request method.
///
class CannedHttpWebApp : public HttpWebApp {
///
/// Create a canned handler that has get and post method bodies.
///
/// If a get only or post only canned handler is required, pass the empty string to the
/// get or post response body string.
///
/// Any empty bodied get/post body strings will result in bad requests for the respective methods.
///
/// @param mimeType_ the mime type to be returned in responses
/// @param getResponseBody_ the response body to send or get requests
/// @param postResponseBody_ the response body to send or post requests
///
public: CannedHttpWebApp(std::string mimeType_, std::string getResponseBody_, std::string postResponseBody_);
///
/// Constructor used by the HTTP server.
///
public: CannedHttpWebApp(const EnvironmentProperties & configuration, const BalauLogger & logger);
public: void handleGetRequest(HttpSession & session,
const StringRequest & request,
std::map<std::string, std::string> & variables) override;
public: void handleHeadRequest(HttpSession & session,
const StringRequest & request,
std::map<std::string, std::string> & variables) override;
public: void handlePostRequest(HttpSession & session,
const StringRequest & request,
std::map<std::string, std::string> & variables) override;
///////////////////////// Private implementation //////////////////////////
private: void handle(HttpSession & session, const StringRequest & request, const std::string & body);
private: const std::string mimeType;
private: const std::string getResponseBody;
private: const std::string postResponseBody;
};
} // namespace Network::Http::HttpWebApps
} // namespace Balau
#endif // COM_BORA_SOFTWARE__BALAU_NETWORK_HTTP_SERVER_HTTP_WEB_APPS__CANNED_HTTP_WEB_APP
| 36.505747
| 110
| 0.70529
|
borasoftware
|
6a5f3c18c2d141042edf09d8c9032f08a0a63434
| 2,294
|
cpp
|
C++
|
src/budget/UpdateContributorCommand.cpp
|
vimofthevine/UnderBudget
|
5711be8e5da3cb7a78da007fe43cf1ce1b796493
|
[
"Apache-2.0"
] | 2
|
2016-07-17T02:12:44.000Z
|
2016-11-22T14:04:55.000Z
|
src/budget/UpdateContributorCommand.cpp
|
vimofthevine/UnderBudget
|
5711be8e5da3cb7a78da007fe43cf1ce1b796493
|
[
"Apache-2.0"
] | null | null | null |
src/budget/UpdateContributorCommand.cpp
|
vimofthevine/UnderBudget
|
5711be8e5da3cb7a78da007fe43cf1ce1b796493
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2013 Kyle Treubig
*
* 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.
*/
// Qt include(s)
#include <QtCore>
// UnderBudget include(s)
#include "budget/Balance.hpp"
#include "budget/UpdateContributorCommand.hpp"
namespace ub {
//------------------------------------------------------------------------------
const int UpdateContributorCommand::ID = 8723464;
//------------------------------------------------------------------------------
UpdateContributorCommand::UpdateContributorCommand(Balance* balance, int index,
const Balance::Contributor& contributor, QUndoCommand* parent)
: QUndoCommand(parent), balance(balance),
index(index), newContributor(contributor)
{
oldContributor = balance->contributorAt(index);
}
//------------------------------------------------------------------------------
int UpdateContributorCommand::id() const
{
return ID;
}
//------------------------------------------------------------------------------
bool UpdateContributorCommand::mergeWith(const QUndoCommand* command)
{
if (command->id() != id())
return false;
// Only merge if change is for the same contributor index
int otherIndex =
static_cast<const UpdateContributorCommand*>(command)->index;
if (otherIndex != index)
return false;
// Use new contributor parameters from the merged command
newContributor = static_cast<const UpdateContributorCommand*>(command)->newContributor;
return true;
}
//------------------------------------------------------------------------------
void UpdateContributorCommand::redo()
{
balance->updateContributor(newContributor, index);
}
//------------------------------------------------------------------------------
void UpdateContributorCommand::undo()
{
balance->updateContributor(oldContributor, index);
}
}
| 30.586667
| 88
| 0.598082
|
vimofthevine
|
6a60c57a19b759d99fb651024d551b2265a281d1
| 8,010
|
cpp
|
C++
|
src/modules/processes/contrib/gviehoever/GradientDomain/GradientsHdrProcess.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
src/modules/processes/contrib/gviehoever/GradientDomain/GradientsHdrProcess.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
src/modules/processes/contrib/gviehoever/GradientDomain/GradientsHdrProcess.cpp
|
fmeschia/pixinsight-class-library
|
11b956e27d6eee3e119a7b1c337d090d7a03f436
|
[
"JasPer-2.0",
"libtiff"
] | null | null | null |
// ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 2.4.9
// ----------------------------------------------------------------------------
// Standard GradientDomain Process Module Version 0.6.4
// ----------------------------------------------------------------------------
// GradientsHdrProcess.cpp - Released 2021-04-09T19:41:49Z
// ----------------------------------------------------------------------------
// This file is part of the standard GradientDomain PixInsight module.
//
// Copyright (c) Georg Viehoever, 2011-2020. Licensed under LGPL 2.1
// Copyright (c) 2003-2020 Pleiades Astrophoto S.L.
//
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
// ----------------------------------------------------------------------------
#include "GradientsHdrProcess.h"
#include "GradientsHdrInstance.h"
#include "GradientsHdrInterface.h"
#include "GradientsHdrParameters.h"
#include <pcl/Arguments.h>
#include <pcl/Console.h>
#include <pcl/Exception.h>
#include <pcl/View.h>
namespace pcl
{
// ----------------------------------------------------------------------------
GradientsHdrProcess* TheGradientsHdrProcess = nullptr;
// ----------------------------------------------------------------------------
GradientsHdrProcess::GradientsHdrProcess()
{
TheGradientsHdrProcess = this;
new GradientsHdrParameterLogMaxGradient( this );
new GradientsHdrParameterLogMinGradient( this );
new GradientsHdrParameterExpGradient( this );
new GradientsHdrParameterRescale01( this );
new GradientsHdrParameterPreserveColor( this );
}
// ----------------------------------------------------------------------------
IsoString GradientsHdrProcess::Id() const
{
return "GradientHDRCompression";
}
// ----------------------------------------------------------------------------
IsoString GradientsHdrProcess::Aliases() const
{
return "GradientsHdrCompression";
}
// ----------------------------------------------------------------------------
IsoString GradientsHdrProcess::Category() const
{
return "GradientDomain";
}
// ----------------------------------------------------------------------------
uint32 GradientsHdrProcess::Version() const
{
return 0x102;
}
// ----------------------------------------------------------------------------
String GradientsHdrProcess::Description() const
{
return
"<html>"
"<p>GradientsHDRCompression supports creation of HDR images, such as M42, M33 etc. "
"It reduces steep gradients, thus revealing faint detail. Should be applied to linear image. "
"May consume considerable amounts of CPU time</p>"
"</html>";
}
// ----------------------------------------------------------------------------
String GradientsHdrProcess::IconImageSVGFile() const
{
return String(); //"@module_icons_dir/GradientsHdr.svg";
}
// ----------------------------------------------------------------------------
ProcessInterface* GradientsHdrProcess::DefaultInterface() const
{
return TheGradientsHdrInterface;
}
// ----------------------------------------------------------------------------
ProcessImplementation* GradientsHdrProcess::Create() const
{
return new GradientsHdrInstance( this );
}
// ----------------------------------------------------------------------------
ProcessImplementation* GradientsHdrProcess::Clone( const ProcessImplementation& p ) const
{
const GradientsHdrInstance* instPtr = dynamic_cast<const GradientsHdrInstance*>( &p );
return (instPtr != nullptr) ? new GradientsHdrInstance( *instPtr ) : nullptr;
}
// ----------------------------------------------------------------------------
bool GradientsHdrProcess::CanProcessCommandLines() const
{
return true;
}
// ----------------------------------------------------------------------------
static void ShowHelp()
{
Console().Write(
"<raw>"
"Usage: GradientsHdrCompression exp_gradient [log_max_gradient [log_min_gradient [bRescale01 [bPreserveColor]]]"
"\n"
"\n exp_gradient is a double in [0,1.1]. Gradient is transformed via sign(gradient)*pow(gradient,exp_gradient). Small values enhance small gradients. Neutral is 1.0"
"\n log_max_gradient is a double in [-7,0] abs(gradients)>pow(10,value) are clipped to sign(gradient)*pow(10,value), thus reducing the influence of large gradients. Default 0.0 is neutral."
"\n log_min_gradient is a double in ]-7,0]. abs(gradients)<pow(10,value) are clipped to zero. -7 is neutral."
"\n bRescale01 is a boolean. If true (default), the result is rescaled to range [0,1], otherwise to the range of the original image"
"\n bPreserveColor is a boolean. If true (default), the relative proportions of R:G:B are preserved for RGB images"
"\n"
"\n--interface"
"\n Launches the interface of this process."
"\n--help"
"\n Displays this help and exits."
"</raw>" );
}
int GradientsHdrProcess::ProcessCommandLine( const StringList& argv ) const
{
ArgumentList arguments =
ExtractArguments( argv, ArgumentItemMode::Ignore );
GradientsHdrInstance instance( this );
bool launchInterface = false;
for ( ArgumentList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
{
const Argument& arg = *i;
if ( arg.IsItemList() )
{
StringList const& rItemsList = arg.Items();
if ( rItemsList.Length() == 0 || rItemsList.Length() > 5 )
{
throw Error( "expecting exp_gradient [log_max_gradient [log_min_gradient [bRescale01 [bPreserveColor]]]] as argument" );
}
if ( rItemsList.Length() >= 1 )
{
instance.expGradient = rItemsList[0].ToDouble();
if ( rItemsList.Length() >= 2 )
{
instance.logMaxGradient = rItemsList[1].ToDouble();
}
if ( rItemsList.Length() >= 3 )
{
instance.logMinGradient = rItemsList[2].ToDouble();
}
if ( rItemsList.Length() >= 4 )
{
instance.bRescale01 = rItemsList[3].ToBool();
}
if ( rItemsList.Length() >= 5 )
{
instance.bPreserveColor = rItemsList[4].ToBool();
}
}
}
else if ( arg.IsLiteral() )
{
// These are standard parameters that all processes should provide.
if ( arg.Id() == "-interface" )
launchInterface = true;
else if ( arg.Id() == "-help" )
{
ShowHelp();
return 0;
}
else
throw Error( "Unknown literal argument: " + arg.Token() );
}
else
{
throw Error( "Unknown type of argument: " + arg.Token() );
}
}
if ( launchInterface )
instance.LaunchInterface();
else if ( ImageWindow::ActiveWindow().IsNull() )
throw Error( "There is no active image window." );
instance.LaunchOnCurrentView();
return 0;
}
// ----------------------------------------------------------------------------
} // namespace pcl
// ----------------------------------------------------------------------------
// EOF GradientsHdrProcess.cpp - Released 2021-04-09T19:41:49Z
| 34.377682
| 195
| 0.534707
|
fmeschia
|
6a64ba75a0ee791d46a0e01144bfd41ae7f8ea21
| 2,861
|
hpp
|
C++
|
src/tilemap.hpp
|
Turtwiggy/Dwarf-and-Blade
|
2e3bd3eb169bf3b62665d74437f806d52c415fb5
|
[
"MIT"
] | null | null | null |
src/tilemap.hpp
|
Turtwiggy/Dwarf-and-Blade
|
2e3bd3eb169bf3b62665d74437f806d52c415fb5
|
[
"MIT"
] | null | null | null |
src/tilemap.hpp
|
Turtwiggy/Dwarf-and-Blade
|
2e3bd3eb169bf3b62665d74437f806d52c415fb5
|
[
"MIT"
] | null | null | null |
#ifndef TILEMAP_HPP_INCLUDED
#define TILEMAP_HPP_INCLUDED
#include <vector>
#include <vec/vec.hpp>
#include <map>
#include <optional>
#include "sprite_renderer.hpp"
#include "random.hpp"
#include <networking/serialisable_fwd.hpp>
namespace ai_info
{
enum type
{
ACTIVE,
NONE,
};
}
namespace tiles
{
enum type
{
BASE,
WATER,
DIRT,
GRASS,
TREE_1,
TREE_2,
TREE_DENSE,
TREE_ROUND,
CACTUS,
DENSE_CACTUS,
VINE,
SHRUB,
ROCKS,
BRAMBLE,
CIVILIAN,
SOLDIER,
SOLDIER_BASIC,
SOLDIER_SPEAR,
SOLDIER_BASIC_SHIELD,
SOLDIER_ADVANCED,
SOLDIER_ADVANCED_SPEAR,
SOLDIER_TOUGH,
SOLDIER_BEST,
GROUND_BUG,
FLYING_BUG,
ARMOURED_BUG,
SCORPION,
SMALL_PINCHY,
LAND_ANIMAL,
SEA_ANIMAL,
CROCODILE,
FACE_MALE,
FACE_WOMAN,
THIN_DOOR_CLOSED,
THIN_DOOR_OPEN,
DOOR_CLOSED,
DOOR_OPEN,
GRAVE,
WOOD_FENCE_FULL,
WOOD_FENCE_HALF,
TILING_WALL,
CULTIVATION,
//effects
EFFECT_1, //swipe
EFFECT_2, //curved swipe
EFFECT_3, //slash claws
EFFECT_4,
EFFECT_5, //fire
EFFECT_6, //fireball
EFFECT_7, //
EFFECT_8, //stationary fire
EFFECT_9,
EFFECT_10, //snow?
EFFECT_11, //snow?
EFFECT_12, //snow?
EFFECT_13, //snow?
//medieval houses in increasing height
HOUSE_1,
HOUSE_2,
HOUSE_3,
HOUSE_4,
TENT,
FANCY_TENT,
CAPITAL_TENT, //not sure, big fancy thing
TOWER_THIN,
TOWER_MEDIUM,
TOWER_THICK,
//variations on the same style
CASTLE_1,
CASTLE_2,
PYRAMID,
CHURCH,
};
}
namespace level_info
{
enum types
{
BARREN, ///dirt, some grass
DESERT,
GRASS
};
}
std::map<tiles::type, std::vector<vec2i>>& get_locations();
sprite_handle get_sprite_handle_of(random_state& rng, tiles::type type);
vec4f get_colour_of(tiles::type type, level_info::types level_type);
struct tilemap : serialisable, free_function
{
std::optional<entt::entity> selected;
vec2i dim;
// x * y, back to front rendering
std::vector<std::vector<entt::entity>> all_entities;
void create(vec2i dim);
void add(entt::entity en, vec2i pos);
void remove(entt::entity en, vec2i pos);
void move(entt::entity en, vec2i from, vec2i to);
void render(entt::registry& reg, render_window& win, camera& cam, sprite_renderer& renderer, vec2f mpos);
int entities_at_position(vec2i pos);
};
#endif
| 20.435714
| 109
| 0.565537
|
Turtwiggy
|
6a6575b6e07405c581c9d1b327ca1c94c408cb28
| 11,550
|
cpp
|
C++
|
moveit_plugins/moveit_simple_controller_manager/src/moveit_simple_controller_manager.cpp
|
predystopic-dev/moveit2
|
42afeea561949b1af197655c1cbb63b851e7dd8d
|
[
"BSD-3-Clause"
] | 1
|
2020-10-11T17:40:28.000Z
|
2020-10-11T17:40:28.000Z
|
moveit_plugins/moveit_simple_controller_manager/src/moveit_simple_controller_manager.cpp
|
predystopic-dev/moveit2
|
42afeea561949b1af197655c1cbb63b851e7dd8d
|
[
"BSD-3-Clause"
] | 1
|
2021-11-08T04:05:16.000Z
|
2021-11-08T04:05:16.000Z
|
moveit_plugins/moveit_simple_controller_manager/src/moveit_simple_controller_manager.cpp
|
predystopic-dev/moveit2
|
42afeea561949b1af197655c1cbb63b851e7dd8d
|
[
"BSD-3-Clause"
] | null | null | null |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Unbounded Robotics Inc.
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Michael Ferguson, Ioan Sucan, E. Gil Jones */
#include <rclcpp/rclcpp.hpp>
#include <moveit_simple_controller_manager/action_based_controller_handle.h>
#include <moveit_simple_controller_manager/gripper_controller_handle.h>
#include <moveit_simple_controller_manager/follow_joint_trajectory_controller_handle.h>
#include <boost/algorithm/string/join.hpp>
#include <pluginlib/class_list_macros.hpp>
#include <algorithm>
#include <map>
namespace
{
/**
* @brief Create a string by adding a provided separator character between each of a variable number of input arguments.
* @param separator Char to use as the separator.
* @param content Variable number of input arguments to concatentate.
* @return Concatenated result string.
*/
template <typename... T>
std::string concatenateWithSeparator(char separator, T... content)
{
std::string result;
(result.append(content).append({ separator }), ...);
result.erase(result.end() - 1); // delete trailing separator
return result;
}
/**
* @brief Compose a parameter name used to load controller configuration from a ROS parameter by concatenating strings
* separated by the `.` character.
* @param strings One or more strings, each corresponding to a part of the full parameter name.
* @return std::string concatenating the input parameters separated by the `.` character. For example:
* base_namespace.controller_name.param_name
*/
template <typename... T>
std::string makeParameterName(T... strings)
{
return concatenateWithSeparator<T...>('.', strings...);
}
} // namespace
namespace moveit_simple_controller_manager
{
static const rclcpp::Logger LOGGER = rclcpp::get_logger("moveit.plugins.moveit_simple_controller_manager");
static const std::string PARAM_BASE_NAME = "moveit_simple_controller_manager";
class MoveItSimpleControllerManager : public moveit_controller_manager::MoveItControllerManager
{
public:
MoveItSimpleControllerManager() = default;
~MoveItSimpleControllerManager() override = default;
void initialize(const rclcpp::Node::SharedPtr& node) override
{
node_ = node;
if (!node_->has_parameter(makeParameterName(PARAM_BASE_NAME, "controller_names")))
{
RCLCPP_ERROR_STREAM(LOGGER, "No controller_names specified.");
return;
}
rclcpp::Parameter controller_names_param;
node_->get_parameter(makeParameterName(PARAM_BASE_NAME, "controller_names"), controller_names_param);
if (controller_names_param.get_type() != rclcpp::ParameterType::PARAMETER_STRING_ARRAY)
{
RCLCPP_ERROR(LOGGER, "Parameter controller_names should be specified as a string array");
return;
}
std::vector<std::string> controller_names = controller_names_param.as_string_array();
/* actually create each controller */
for (const std::string& controller_name : controller_names)
{
try
{
std::string action_ns;
const std::string& action_ns_param = makeParameterName(PARAM_BASE_NAME, controller_name, "action_ns");
if (!node_->get_parameter(action_ns_param, action_ns))
{
RCLCPP_ERROR_STREAM(LOGGER, "No action namespace specified for controller `"
<< controller_name << "` through parameter `" << action_ns_param << "`");
continue;
}
std::string type;
if (!node_->get_parameter(makeParameterName(PARAM_BASE_NAME, controller_name, "type"), type))
{
RCLCPP_ERROR_STREAM(LOGGER, "No type specified for controller " << controller_name);
continue;
}
std::vector<std::string> controller_joints;
if (!node_->get_parameter(makeParameterName(PARAM_BASE_NAME, controller_name, "joints"), controller_joints) ||
controller_joints.empty())
{
RCLCPP_ERROR_STREAM(LOGGER, "No joints specified for controller " << controller_name);
continue;
}
ActionBasedControllerHandleBasePtr new_handle;
if (type == "GripperCommand")
{
new_handle = std::make_shared<GripperControllerHandle>(node_, controller_name, action_ns);
bool parallel_gripper = false;
if (node_->get_parameter(makeParameterName(PARAM_BASE_NAME, "parallel"), parallel_gripper) && parallel_gripper)
{
if (controller_joints.size() != 2)
{
RCLCPP_ERROR_STREAM(LOGGER, "Parallel Gripper requires exactly two joints, " << controller_joints.size()
<< " are specified");
continue;
}
static_cast<GripperControllerHandle*>(new_handle.get())
->setParallelJawGripper(controller_joints[0], controller_joints[1]);
}
else
{
std::string command_joint;
if (!node_->get_parameter(makeParameterName(PARAM_BASE_NAME, "command_joint"), command_joint))
command_joint = controller_joints[0];
static_cast<GripperControllerHandle*>(new_handle.get())->setCommandJoint(command_joint);
}
bool allow_failure;
node_->get_parameter_or(makeParameterName(PARAM_BASE_NAME, "allow_failure"), allow_failure, false);
static_cast<GripperControllerHandle*>(new_handle.get())->allowFailure(allow_failure);
RCLCPP_INFO_STREAM(LOGGER, "Added GripperCommand controller for " << controller_name);
controllers_[controller_name] = new_handle;
}
else if (type == "FollowJointTrajectory")
{
new_handle = std::make_shared<FollowJointTrajectoryControllerHandle>(node_, controller_name, action_ns);
RCLCPP_INFO_STREAM(LOGGER, "Added FollowJointTrajectory controller for " << controller_name);
controllers_[controller_name] = new_handle;
}
else
{
RCLCPP_ERROR_STREAM(LOGGER, "Unknown controller type: " << type);
continue;
}
if (!controllers_[controller_name])
{
controllers_.erase(controller_name);
continue;
}
moveit_controller_manager::MoveItControllerManager::ControllerState state;
node_->get_parameter_or(makeParameterName(PARAM_BASE_NAME, controller_name, "default"), state.default_, false);
state.active_ = true;
controller_states_[controller_name] = state;
/* add list of joints, used by controller manager and MoveIt */
for (const std::string& controller_joint : controller_joints)
new_handle->addJoint(controller_joint);
}
catch (...)
{
RCLCPP_ERROR_STREAM(LOGGER, "Caught unknown exception while parsing controller information");
}
}
}
/*
* Get a controller, by controller name (which was specified in the controllers.yaml
*/
moveit_controller_manager::MoveItControllerHandlePtr getControllerHandle(const std::string& name) override
{
std::map<std::string, ActionBasedControllerHandleBasePtr>::const_iterator it = controllers_.find(name);
if (it != controllers_.end())
return static_cast<moveit_controller_manager::MoveItControllerHandlePtr>(it->second);
else
RCLCPP_FATAL_STREAM(LOGGER, "No such controller: " << name);
return moveit_controller_manager::MoveItControllerHandlePtr();
}
/*
* Get the list of controller names.
*/
void getControllersList(std::vector<std::string>& names) override
{
for (std::map<std::string, ActionBasedControllerHandleBasePtr>::const_iterator it = controllers_.begin();
it != controllers_.end(); ++it)
names.push_back(it->first);
RCLCPP_INFO_STREAM(LOGGER, "Returned " << names.size() << " controllers in list");
}
/*
* This plugin assumes that all controllers are already active -- and if they are not, well, it has no way to deal
* with it anyways!
*/
void getActiveControllers(std::vector<std::string>& names) override
{
getControllersList(names);
}
/*
* Controller must be loaded to be active, see comment above about active controllers...
*/
virtual void getLoadedControllers(std::vector<std::string>& names)
{
getControllersList(names);
}
/*
* Get the list of joints that a controller can control.
*/
void getControllerJoints(const std::string& name, std::vector<std::string>& joints) override
{
std::map<std::string, ActionBasedControllerHandleBasePtr>::const_iterator it = controllers_.find(name);
if (it != controllers_.end())
{
it->second->getJoints(joints);
}
else
{
RCLCPP_WARN(LOGGER,
"The joints for controller '%s' are not known. Perhaps the controller configuration is "
"not loaded on the param server?",
name.c_str());
joints.clear();
}
}
moveit_controller_manager::MoveItControllerManager::ControllerState
getControllerState(const std::string& name) override
{
return controller_states_[name];
}
/* Cannot switch our controllers */
bool switchControllers(const std::vector<std::string>& /* activate */,
const std::vector<std::string>& /* deactivate */) override
{
return false;
}
protected:
rclcpp::Node::SharedPtr node_;
std::map<std::string, ActionBasedControllerHandleBasePtr> controllers_;
std::map<std::string, moveit_controller_manager::MoveItControllerManager::ControllerState> controller_states_;
};
} // end namespace moveit_simple_controller_manager
PLUGINLIB_EXPORT_CLASS(moveit_simple_controller_manager::MoveItSimpleControllerManager,
moveit_controller_manager::MoveItControllerManager);
| 40.669014
| 121
| 0.686061
|
predystopic-dev
|
6a670252f09cfb9d43601565ce7fc5a81b0ad268
| 32,482
|
cpp
|
C++
|
lib/AST/RequirementMachine/RewriteLoop.cpp
|
tshortli/swift
|
3e739f62fcb14f9f72d5da81168953cfd54e3ee0
|
[
"Apache-2.0"
] | 2
|
2022-01-23T20:41:02.000Z
|
2022-01-23T20:41:12.000Z
|
lib/AST/RequirementMachine/RewriteLoop.cpp
|
blanche37/swift
|
c3c9b1bf56ce76715ff7e547f68cc354be4cdad8
|
[
"Apache-2.0"
] | 1
|
2018-08-23T19:35:25.000Z
|
2018-08-23T19:35:25.000Z
|
lib/AST/RequirementMachine/RewriteLoop.cpp
|
blanche37/swift
|
c3c9b1bf56ce76715ff7e547f68cc354be4cdad8
|
[
"Apache-2.0"
] | null | null | null |
//===--- RewriteLoop.cpp - Identities between rewrite rules ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines data types used for representing redundancies among
// rewrite rules. The information encoded in these types is ultimately used
// for generic signature minimization.
//
// A RewriteStep is a single primitive transformation; the canonical example is
// the application of a rewrite rule, possibly to a subterm.
//
// A RewritePath is a composition of RewriteSteps describing the transformation
// of a term into another term. One place where a RewritePath originates is
// RewriteSystem::simplify(); that method takes an optional RewritePath argument
// to which the series of RewriteSteps performed during simplification are
// appended. If the term was already canonical, the resulting path is empty,
// otherwise it will consist of at least one RewriteStep.
//
// Simplification always applies rules by replacing a subterm equal to the LHS
// with the RHS where LHS > RHS, so the RewriteSteps constructed there always
// make the term shorter. However, more generally, RewriteSteps can also
// express the inverse rewrite, where RHS is replaced with LHS, making the term
// longer.
//
// Inverted RewriteSteps are constructed in the Knuth-Bendix completion
// algorithm. A simple example is where two rules (U.V => X) and (V.W => Y)
// overlap on the term U.V.W. Then the induced rule (X.W => U.Y) (assuming that
// X.W > U.Y) can be described by a RewritePath which begins at X.W, applies
// the inverted rule (X => U.V) to the subterm X to obtain U.V.W, then applies
// the rule (V.W => Y) to the subterm V.W to obtain U.Y.
//
// A RewriteLoop is a path that begins and ends at the same term. A RewriteLoop
// describes a _redundancy_. For example, when completion adds a new rule to
// resolve an overlap, it constructs a RewritePath describing this new rule in
// terms of existing rules; by adding an additional rewrite step corresponding
// to the new rule, we get a loop that begins and ends at the same point, or in
// other words, a RewriteLoop.
//
// In the above example, we have a RewritePath from X.W to U.Y via the two
// existing rewrite rules with the overlap term U.V.W in the middle. If we then
// add a third rewrite step for the new rule inverted, (U.Y => X.W), we get a
// loop that begins and ends at X.W. This loop encodes that the new rule
// (X.W => U.Y) is redundant because it can be expresed in terms of other rules.
//
// The homotopy reduction algorithm in HomotopyReduction.cpp uses rewrite loops
// to find a minimal set of rewrite rules, which are then used to construct a
// minimal generic signature.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Type.h"
#include "swift/Basic/Range.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include "RewriteSystem.h"
using namespace swift;
using namespace rewriting;
/// Dumps the rewrite step that was applied to \p term. Mutates \p term to
/// reflect the application of the rule.
void RewriteStep::dump(llvm::raw_ostream &out,
RewritePathEvaluator &evaluator,
const RewriteSystem &system) const {
switch (Kind) {
case Rule: {
auto result = evaluator.applyRewriteRule(*this, system);
if (!result.prefix.empty()) {
out << result.prefix;
out << ".";
}
out << "(" << result.lhs << " => " << result.rhs << ")";
if (!result.suffix.empty()) {
out << ".";
out << result.suffix;
}
break;
}
case PrefixSubstitutions: {
auto pair = evaluator.applyPrefixSubstitutions(*this, system);
out << "(σ";
out << (Inverse ? " - " : " + ");
out << pair.first << ")";
if (!pair.second.empty())
out << "." << pair.second;
break;
}
case Shift: {
evaluator.applyShift(*this, system);
out << (Inverse ? "B>A" : "A>B");
break;
}
case Decompose: {
evaluator.applyDecompose(*this, system);
out << (Inverse ? "Compose(" : "Decompose(");
out << Arg << ")";
break;
}
case Relation: {
auto result = evaluator.applyRelation(*this, system);
if (!result.prefix.empty()) {
out << result.prefix;
out << ".";
}
out << "(" << result.lhs << " =>> " << result.rhs << ")";
if (!result.suffix.empty()) {
out << ".";
out << result.suffix;
}
break;
}
case DecomposeConcrete: {
evaluator.applyDecomposeConcrete(*this, system);
out << (Inverse ? "ComposeConcrete(" : "DecomposeConcrete(");
const auto &difference = system.getTypeDifference(Arg);
out << difference.LHS << " : " << difference.RHS << ")";
break;
}
case LeftConcreteProjection: {
evaluator.applyLeftConcreteProjection(*this, system);
out << "LeftConcrete" << (Inverse ? "In" : "Pro") << "jection(";
const auto &difference = system.getTypeDifference(
getTypeDifferenceID());
out << difference.LHS << " : " << difference.RHS << ")";
break;
}
case RightConcreteProjection: {
evaluator.applyRightConcreteProjection(*this, system);
out << "RightConcrete" << (Inverse ? "In" : "Pro") << "jection(";
const auto &difference = system.getTypeDifference(
getTypeDifferenceID());
out << difference.LHS << " : " << difference.RHS << ")";
break;
}
}
}
/// Invert a rewrite path, producing a path that rewrites the original path's
/// destination back to the original path's source.
void RewritePath::invert() {
std::reverse(Steps.begin(), Steps.end());
for (auto &step : Steps)
step.invert();
}
/// Given a rewrite rule which appears exactly once in a loop
/// without context, return a new definition for this rewrite rule.
/// The new definition is the path obtained by deleting the
/// rewrite rule from the loop.
RewritePath RewritePath::splitCycleAtRule(unsigned ruleID) const {
// A cycle is a path from the basepoint to the basepoint.
// Somewhere in this path, an application of \p ruleID
// appears in an empty context.
// First, we split the cycle into two paths:
//
// (1) A path from the basepoint to the rule's
// left hand side,
RewritePath basepointToLhs;
// (2) And a path from the rule's right hand side
// to the basepoint.
RewritePath rhsToBasepoint;
// Because the rule only appears once, we know that basepointToLhs
// and rhsToBasepoint do not involve the rule itself.
// If the rule is inverted, we have to invert the whole thing
// again at the end.
bool ruleWasInverted = false;
bool sawRule = false;
for (auto step : Steps) {
switch (step.Kind) {
case RewriteStep::Rule: {
if (step.getRuleID() != ruleID)
break;
assert(!sawRule && "Rule appears more than once?");
assert(!step.isInContext() && "Rule appears in context?");
ruleWasInverted = step.Inverse;
sawRule = true;
continue;
}
case RewriteStep::PrefixSubstitutions:
case RewriteStep::Shift:
case RewriteStep::Decompose:
case RewriteStep::Relation:
case RewriteStep::DecomposeConcrete:
case RewriteStep::LeftConcreteProjection:
case RewriteStep::RightConcreteProjection:
break;
}
if (sawRule)
rhsToBasepoint.add(step);
else
basepointToLhs.add(step);
}
// Build a path from the rule's lhs to the rule's rhs via the
// basepoint.
RewritePath result = rhsToBasepoint;
result.append(basepointToLhs);
// We want a path from the lhs to the rhs, so invert it unless
// the rewrite step was also inverted.
if (!ruleWasInverted)
result.invert();
return result;
}
/// Replace every rewrite step involving the given rewrite rule with
/// either the replacement path (or its inverse, if the step was
/// inverted).
///
/// The replacement path is re-contextualized at each occurrence of a
/// rewrite step involving the given rule.
///
/// Returns true if any rewrite steps were replaced; false means the
/// rule did not appear in this path.
bool RewritePath::replaceRulesWithPaths(
llvm::function_ref<const RewritePath *(unsigned)> fn) {
bool foundAny = false;
for (const auto &step : Steps) {
if (step.Kind == RewriteStep::Rule &&
fn(step.getRuleID()) != nullptr) {
foundAny = true;
break;
}
}
if (!foundAny)
return false;
SmallVector<RewriteStep, 4> newSteps;
for (const auto &step : Steps) {
switch (step.Kind) {
case RewriteStep::Rule: {
auto *replacementPath = fn(step.getRuleID());
if (replacementPath == nullptr) {
newSteps.push_back(step);
break;
}
// Ok, we found a rewrite step referencing a redundant rule.
// Replace this step with the provided path. If this rewrite step has
// context, the path's own steps must be re-contextualized.
// Keep track of rewrite step pairs which push and pop the stack. Any
// rewrite steps enclosed with a push/pop are not re-contextualized.
unsigned pushCount = 0;
auto recontextualizeStep = [&](RewriteStep newStep) {
bool inverse = newStep.Inverse ^ step.Inverse;
if (newStep.pushesTermsOnStack() && inverse) {
assert(pushCount > 0);
--pushCount;
}
if (pushCount == 0) {
newStep.StartOffset += step.StartOffset;
newStep.EndOffset += step.EndOffset;
}
newStep.Inverse = inverse;
newSteps.push_back(newStep);
if (newStep.pushesTermsOnStack() && !inverse) {
++pushCount;
}
};
// If this rewrite step is inverted, invert the entire path.
if (step.Inverse) {
for (auto newStep : llvm::reverse(*replacementPath))
recontextualizeStep(newStep);
} else {
for (auto newStep : *replacementPath)
recontextualizeStep(newStep);
}
// Rewrite steps which push and pop the stack must come in balanced pairs.
assert(pushCount == 0);
break;
}
case RewriteStep::PrefixSubstitutions:
case RewriteStep::Shift:
case RewriteStep::Decompose:
case RewriteStep::Relation:
case RewriteStep::DecomposeConcrete:
case RewriteStep::LeftConcreteProjection:
case RewriteStep::RightConcreteProjection:
newSteps.push_back(step);
break;
}
}
std::swap(newSteps, Steps);
return true;
}
bool RewritePath::replaceRuleWithPath(unsigned ruleID,
const RewritePath &path) {
return replaceRulesWithPaths(
[&](unsigned otherRuleID) -> const RewritePath * {
if (ruleID == otherRuleID)
return &path;
return nullptr;
});
}
SmallVector<unsigned, 1>
RewritePath::getRulesInEmptyContext(const MutableTerm &term,
const RewriteSystem &system) {
// Rules appearing in empty context (possibly more than once).
llvm::SmallDenseSet<unsigned, 2> rulesInEmptyContext;
// The number of times each rule appears (with or without context).
llvm::SmallDenseMap<unsigned, unsigned, 2> ruleFrequency;
RewritePathEvaluator evaluator(term);
for (auto step : Steps) {
switch (step.Kind) {
case RewriteStep::Rule: {
if (!step.isInContext() && !evaluator.isInContext())
rulesInEmptyContext.insert(step.getRuleID());
++ruleFrequency[step.getRuleID()];
break;
}
case RewriteStep::LeftConcreteProjection:
case RewriteStep::Decompose:
case RewriteStep::PrefixSubstitutions:
case RewriteStep::Shift:
case RewriteStep::Relation:
case RewriteStep::DecomposeConcrete:
case RewriteStep::RightConcreteProjection:
break;
}
evaluator.apply(step, system);
}
// Collect all rules that we saw exactly once in empty context.
SmallVector<unsigned, 1> rulesOnceInEmptyContext;
for (auto rule : rulesInEmptyContext) {
auto found = ruleFrequency.find(rule);
assert(found != ruleFrequency.end());
if (found->second == 1)
rulesOnceInEmptyContext.push_back(rule);
}
return rulesOnceInEmptyContext;
}
/// Dumps a series of rewrite steps applied to \p term.
void RewritePath::dump(llvm::raw_ostream &out,
MutableTerm term,
const RewriteSystem &system) const {
RewritePathEvaluator evaluator(term);
bool first = true;
for (const auto &step : Steps) {
if (!first) {
out << " ⊗ ";
} else {
first = false;
}
step.dump(out, evaluator, system);
}
}
void RewritePath::dumpLong(llvm::raw_ostream &out,
MutableTerm term,
const RewriteSystem &system) const {
RewritePathEvaluator evaluator(term);
for (const auto &step : Steps) {
evaluator.dump(out);
evaluator.apply(step, system);
out << "\n";
}
evaluator.dump(out);
}
void RewriteLoop::verify(const RewriteSystem &system) const {
RewritePathEvaluator evaluator(Basepoint);
for (const auto &step : Path) {
evaluator.apply(step, system);
}
if (evaluator.getCurrentTerm() != Basepoint) {
llvm::errs() << "Not a loop: ";
dump(llvm::errs(), system);
llvm::errs() << "\n";
abort();
}
if (evaluator.isInContext()) {
llvm::errs() << "Leftover terms on evaluator stack\n";
evaluator.dump(llvm::errs());
abort();
}
}
/// Recompute various cached values if needed.
void RewriteLoop::recompute(const RewriteSystem &system) {
if (!Dirty)
return;
Dirty = 0;
Useful = 0;
ProjectionCount = 0;
DecomposeCount = 0;
HasConcreteTypeAliasRule = 0;
RewritePathEvaluator evaluator(Basepoint);
for (auto step : Path) {
switch (step.Kind) {
case RewriteStep::Rule: {
Useful |= (!step.isInContext() && !evaluator.isInContext());
const auto &rule = system.getRule(step.getRuleID());
if (rule.isDerivedFromConcreteProtocolTypeAliasRule())
HasConcreteTypeAliasRule = 1;
break;
}
case RewriteStep::LeftConcreteProjection:
++ProjectionCount;
break;
case RewriteStep::Decompose:
++DecomposeCount;
break;
case RewriteStep::PrefixSubstitutions:
case RewriteStep::Shift:
case RewriteStep::Relation:
case RewriteStep::DecomposeConcrete:
case RewriteStep::RightConcreteProjection:
break;
}
evaluator.apply(step, system);
}
RulesInEmptyContext = Path.getRulesInEmptyContext(Basepoint, system);
}
/// A rewrite rule is redundant if it appears exactly once in a loop
/// without context.
ArrayRef<unsigned>
RewriteLoop::findRulesAppearingOnceInEmptyContext(
const RewriteSystem &system) const {
const_cast<RewriteLoop *>(this)->recompute(system);
return RulesInEmptyContext;
}
/// The number of LeftConcreteProjection steps, used by the elimination order to
/// prioritize loops that are not concrete unification projections.
unsigned RewriteLoop::getProjectionCount(
const RewriteSystem &system) const {
const_cast<RewriteLoop *>(this)->recompute(system);
return ProjectionCount;
}
/// The number of Decompose steps, used by the elimination order to prioritize
/// loops that are not concrete simplifications.
unsigned RewriteLoop::getDecomposeCount(
const RewriteSystem &system) const {
const_cast<RewriteLoop *>(this)->recompute(system);
return DecomposeCount;
}
/// Returns true if the loop contains at least one concrete protocol typealias rule,
/// which have the form ([P].A.[concrete: C] => [P].A).
bool RewriteLoop::hasConcreteTypeAliasRule(
const RewriteSystem &system) const {
const_cast<RewriteLoop *>(this)->recompute(system);
return HasConcreteTypeAliasRule;
}
/// The number of Decompose steps, used by the elimination order to prioritize
/// loops that are not concrete simplifications.
bool RewriteLoop::isUseful(
const RewriteSystem &system) const {
const_cast<RewriteLoop *>(this)->recompute(system);
return Useful;
}
void RewriteLoop::dump(llvm::raw_ostream &out,
const RewriteSystem &system) const {
out << Basepoint << ": ";
Path.dump(out, Basepoint, system);
if (isDeleted())
out << " [deleted]";
}
void RewritePathEvaluator::dump(llvm::raw_ostream &out) const {
for (unsigned i = 0, e = Primary.size(); i < e; ++i) {
if (i == Primary.size() - 1)
out << "-> ";
else
out << " ";
out << Primary[i] << "\n";
}
for (unsigned i = 0, e = Secondary.size(); i < e; ++i) {
out << " " << Secondary[Secondary.size() - i - 1] << "\n";
}
}
void RewritePathEvaluator::checkPrimary() const {
if (Primary.empty()) {
llvm::errs() << "Empty primary stack\n";
dump(llvm::errs());
abort();
}
}
void RewritePathEvaluator::checkSecondary() const {
if (Secondary.empty()) {
llvm::errs() << "Empty secondary stack\n";
dump(llvm::errs());
abort();
}
}
MutableTerm &RewritePathEvaluator::getCurrentTerm() {
checkPrimary();
return Primary.back();
}
AppliedRewriteStep
RewritePathEvaluator::applyRewriteRule(const RewriteStep &step,
const RewriteSystem &system) {
auto &term = getCurrentTerm();
assert(step.Kind == RewriteStep::Rule);
const auto &rule = system.getRule(step.getRuleID());
auto lhs = (step.Inverse ? rule.getRHS() : rule.getLHS());
auto rhs = (step.Inverse ? rule.getLHS() : rule.getRHS());
auto bug = [&](StringRef msg) {
llvm::errs() << msg << "\n";
llvm::errs() << "- Term: " << term << "\n";
llvm::errs() << "- StartOffset: " << step.StartOffset << "\n";
llvm::errs() << "- EndOffset: " << step.EndOffset << "\n";
llvm::errs() << "- Expected subterm: " << lhs << "\n";
abort();
};
if (term.size() != step.StartOffset + lhs.size() + step.EndOffset) {
bug("Invalid whiskering");
}
if (!std::equal(term.begin() + step.StartOffset,
term.begin() + step.StartOffset + lhs.size(),
lhs.begin())) {
bug("Invalid subterm");
}
MutableTerm prefix(term.begin(), term.begin() + step.StartOffset);
MutableTerm suffix(term.end() - step.EndOffset, term.end());
term = prefix;
term.append(rhs);
term.append(suffix);
return {lhs, rhs, prefix, suffix};
}
std::pair<MutableTerm, MutableTerm>
RewritePathEvaluator::applyPrefixSubstitutions(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Arg != 0);
auto &term = getCurrentTerm();
assert(step.Kind == RewriteStep::PrefixSubstitutions);
auto &ctx = system.getRewriteContext();
MutableTerm prefix(term.begin() + step.StartOffset,
term.begin() + step.StartOffset + step.Arg);
MutableTerm suffix(term.end() - step.EndOffset - 1, term.end());
// We're either adding or removing the prefix to each concrete substitution.
Symbol &last = *(term.end() - step.EndOffset - 1);
if (!last.hasSubstitutions()) {
llvm::errs() << "Invalid rewrite path\n";
llvm::errs() << "- Term: " << term << "\n";
llvm::errs() << "- Start offset: " << step.StartOffset << "\n";
llvm::errs() << "- End offset: " << step.EndOffset << "\n";
abort();
}
last = last.transformConcreteSubstitutions(
[&](Term t) -> Term {
if (step.Inverse) {
if (!std::equal(t.begin(),
t.begin() + step.Arg,
prefix.begin())) {
llvm::errs() << "Invalid rewrite path\n";
llvm::errs() << "- Term: " << term << "\n";
llvm::errs() << "- Substitution: " << t << "\n";
llvm::errs() << "- Start offset: " << step.StartOffset << "\n";
llvm::errs() << "- End offset: " << step.EndOffset << "\n";
llvm::errs() << "- Expected subterm: " << prefix << "\n";
abort();
}
MutableTerm mutTerm(t.begin() + step.Arg, t.end());
return Term::get(mutTerm, ctx);
} else {
MutableTerm mutTerm(prefix);
mutTerm.append(t);
return Term::get(mutTerm, ctx);
}
}, ctx);
return std::make_pair(prefix, suffix);
}
void RewritePathEvaluator::applyShift(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Kind == RewriteStep::Shift);
assert(step.StartOffset == 0);
assert(step.EndOffset == 0);
assert(step.Arg == 0);
if (!step.Inverse) {
// Move top of primary stack to secondary stack.
checkPrimary();
Secondary.push_back(Primary.back());
Primary.pop_back();
} else {
// Move top of secondary stack to primary stack.
checkSecondary();
Primary.push_back(Secondary.back());
Secondary.pop_back();
}
}
void RewritePathEvaluator::applyDecompose(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Kind == RewriteStep::Decompose);
unsigned numSubstitutions = step.Arg;
if (!step.Inverse) {
// The input term takes the form U.[concrete: C].V or U.[superclass: C].V,
// where |V| == EndOffset.
const auto &term = getCurrentTerm();
auto symbol = *(term.end() - step.EndOffset - 1);
if (!symbol.hasSubstitutions()) {
llvm::errs() << "Expected term with superclass or concrete type symbol"
<< " on primary stack\n";
dump(llvm::errs());
abort();
}
// The symbol must have the expected number of substitutions.
if (symbol.getSubstitutions().size() != numSubstitutions) {
llvm::errs() << "Expected " << numSubstitutions << " substitutions\n";
dump(llvm::errs());
abort();
}
// Push each substitution on the primary stack.
for (auto substitution : symbol.getSubstitutions()) {
Primary.push_back(MutableTerm(substitution));
}
} else {
// The primary stack must store the number of substitutions, together with
// a term that takes the form U.[concrete: C].V or U.[superclass: C].V,
// where |V| == EndOffset.
if (Primary.size() < numSubstitutions + 1) {
llvm::errs() << "Not enough terms on primary stack\n";
dump(llvm::errs());
abort();
}
// The term immediately underneath the substitutions is the one we're
// updating with new substitutions.
const auto &term = *(Primary.end() - numSubstitutions - 1);
auto symbol = *(term.end() - step.EndOffset - 1);
// The symbol at the end of this term must have the expected number of
// substitutions.
if (symbol.getSubstitutions().size() != numSubstitutions) {
llvm::errs() << "Expected " << numSubstitutions << " substitutions\n";
dump(llvm::errs());
abort();
}
for (unsigned i = 0; i < numSubstitutions; ++i) {
const auto &substitution = *(Primary.end() - numSubstitutions + i);
if (MutableTerm(symbol.getSubstitutions()[i]) != substitution) {
llvm::errs() << "Expected " << symbol.getSubstitutions()[i] << "\n";
llvm::errs() << "Got " << substitution << "\n";
dump(llvm::errs());
abort();
}
}
// Pop the substitutions from the primary stack.
Primary.resize(Primary.size() - numSubstitutions);
}
}
AppliedRewriteStep
RewritePathEvaluator::applyRelation(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Kind == RewriteStep::Relation);
auto relation = system.getRelation(step.Arg);
auto &term = getCurrentTerm();
auto lhs = (step.Inverse ? relation.second : relation.first);
auto rhs = (step.Inverse ? relation.first : relation.second);
auto bug = [&](StringRef msg) {
llvm::errs() << msg << "\n";
llvm::errs() << "- Term: " << term << "\n";
llvm::errs() << "- StartOffset: " << step.StartOffset << "\n";
llvm::errs() << "- EndOffset: " << step.EndOffset << "\n";
llvm::errs() << "- Expected subterm: " << lhs << "\n";
abort();
};
if (term.size() != step.StartOffset + lhs.size() + step.EndOffset) {
bug("Invalid whiskering");
}
if (!std::equal(term.begin() + step.StartOffset,
term.begin() + step.StartOffset + lhs.size(),
lhs.begin())) {
bug("Invalid subterm");
}
MutableTerm prefix(term.begin(), term.begin() + step.StartOffset);
MutableTerm suffix(term.end() - step.EndOffset, term.end());
term = prefix;
term.append(rhs);
term.append(suffix);
return {lhs, rhs, prefix, suffix};
}
void RewritePathEvaluator::applyDecomposeConcrete(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Kind == RewriteStep::DecomposeConcrete);
const auto &difference = system.getTypeDifference(step.Arg);
auto bug = [&](StringRef msg) {
llvm::errs() << msg << "\n";
llvm::errs() << "- StartOffset: " << step.StartOffset << "\n";
llvm::errs() << "- EndOffset: " << step.EndOffset << "\n";
llvm::errs() << "- DifferenceID: " << step.Arg << "\n";
llvm::errs() << "\nType difference:\n";
difference.dump(llvm::errs());
llvm::errs() << "\nEvaluator state:\n";
dump(llvm::errs());
abort();
};
auto substitutions = difference.LHS.getSubstitutions();
if (!step.Inverse) {
auto &term = getCurrentTerm();
auto concreteSymbol = *(term.end() - step.EndOffset - 1);
if (concreteSymbol != difference.RHS)
bug("Concrete symbol not equal to expected RHS");
MutableTerm newTerm(term.begin(), term.end() - step.EndOffset - 1);
newTerm.add(difference.LHS);
newTerm.append(term.end() - step.EndOffset, term.end());
term = newTerm;
for (unsigned n : indices(substitutions))
Primary.push_back(difference.getReplacementSubstitution(n));
} else {
unsigned numSubstitutions = substitutions.size();
if (Primary.size() < numSubstitutions + 1)
bug("Not enough terms on the stack");
for (unsigned n : indices(substitutions)) {
const auto &otherSubstitution = *(Primary.end() - numSubstitutions + n);
auto expectedSubstitution = difference.getReplacementSubstitution(n);
if (otherSubstitution != expectedSubstitution) {
llvm::errs() << "Got: " << otherSubstitution << "\n";
llvm::errs() << "Expected: " << expectedSubstitution << "\n";
bug("Unexpected substitution term on the stack");
}
}
Primary.resize(Primary.size() - numSubstitutions);
auto &term = getCurrentTerm();
auto concreteSymbol = *(term.end() - step.EndOffset - 1);
if (concreteSymbol != difference.LHS)
bug("Concrete symbol not equal to expected LHS");
MutableTerm newTerm(term.begin(), term.end() - step.EndOffset - 1);
newTerm.add(difference.RHS);
newTerm.append(term.end() - step.EndOffset, term.end());
term = newTerm;
}
}
void
RewritePathEvaluator::applyLeftConcreteProjection(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Kind == RewriteStep::LeftConcreteProjection);
const auto &difference = system.getTypeDifference(step.getTypeDifferenceID());
unsigned index = step.getSubstitutionIndex();
auto leftProjection = difference.getOriginalSubstitution(index);
MutableTerm leftBaseTerm(difference.BaseTerm);
leftBaseTerm.add(difference.LHS);
auto bug = [&](StringRef msg) {
llvm::errs() << msg << "\n";
llvm::errs() << "- StartOffset: " << step.StartOffset << "\n";
llvm::errs() << "- EndOffset: " << step.EndOffset << "\n";
llvm::errs() << "- SubstitutionIndex: " << index << "\n";
llvm::errs() << "- LeftProjection: " << leftProjection << "\n";
llvm::errs() << "- LeftBaseTerm: " << leftBaseTerm << "\n";
llvm::errs() << "- DifferenceID: " << step.getTypeDifferenceID() << "\n";
llvm::errs() << "\nType difference:\n";
difference.dump(llvm::errs());
llvm::errs() << ":\n";
difference.dump(llvm::errs());
llvm::errs() << "\nEvaluator state:\n";
dump(llvm::errs());
abort();
};
if (!step.Inverse) {
const auto &term = getCurrentTerm();
MutableTerm subTerm(term.begin() + step.StartOffset,
term.end() - step.EndOffset);
if (subTerm != MutableTerm(leftProjection))
bug("Incorrect left projection term");
Primary.push_back(leftBaseTerm);
} else {
if (Primary.size() < 2)
bug("Too few elements on the primary stack");
if (Primary.back() != leftBaseTerm)
bug("Incorrect left base term");
Primary.pop_back();
const auto &term = getCurrentTerm();
MutableTerm subTerm(term.begin() + step.StartOffset,
term.end() - step.EndOffset);
if (subTerm != leftProjection)
bug("Incorrect left projection term");
}
}
void
RewritePathEvaluator::applyRightConcreteProjection(const RewriteStep &step,
const RewriteSystem &system) {
assert(step.Kind == RewriteStep::RightConcreteProjection);
const auto &difference = system.getTypeDifference(step.getTypeDifferenceID());
unsigned index = step.getSubstitutionIndex();
auto leftProjection = difference.getOriginalSubstitution(index);
auto rightProjection = difference.getReplacementSubstitution(index);
MutableTerm leftBaseTerm(difference.BaseTerm);
leftBaseTerm.add(difference.LHS);
MutableTerm rightBaseTerm(difference.BaseTerm);
rightBaseTerm.add(difference.RHS);
auto bug = [&](StringRef msg) {
llvm::errs() << msg << "\n";
llvm::errs() << "- StartOffset: " << step.StartOffset << "\n";
llvm::errs() << "- EndOffset: " << step.EndOffset << "\n";
llvm::errs() << "- SubstitutionIndex: " << index << "\n";
llvm::errs() << "- LeftProjection: " << leftProjection << "\n";
llvm::errs() << "- RightProjection: " << rightProjection << "\n";
llvm::errs() << "- LeftBaseTerm: " << leftBaseTerm << "\n";
llvm::errs() << "- RightBaseTerm: " << rightBaseTerm << "\n";
llvm::errs() << "- DifferenceID: " << step.getTypeDifferenceID() << "\n";
llvm::errs() << "\nType difference:\n";
difference.dump(llvm::errs());
llvm::errs() << "\nEvaluator state:\n";
dump(llvm::errs());
abort();
};
if (!step.Inverse) {
auto &term = getCurrentTerm();
MutableTerm subTerm(term.begin() + step.StartOffset,
term.end() - step.EndOffset);
if (subTerm != rightProjection)
bug("Incorrect right projection term");
MutableTerm newTerm(term.begin(), term.begin() + step.StartOffset);
newTerm.append(leftProjection);
newTerm.append(term.end() - step.EndOffset, term.end());
term = newTerm;
Primary.push_back(rightBaseTerm);
} else {
if (Primary.size() < 2)
bug("Too few elements on the primary stack");
if (Primary.back() != rightBaseTerm)
bug("Incorrect right base term");
Primary.pop_back();
auto &term = getCurrentTerm();
MutableTerm subTerm(term.begin() + step.StartOffset,
term.end() - step.EndOffset);
if (subTerm != leftProjection)
bug("Incorrect left projection term");
MutableTerm newTerm(term.begin(), term.begin() + step.StartOffset);
newTerm.append(rightProjection);
newTerm.append(term.end() - step.EndOffset, term.end());
term = newTerm;
}
}
void RewritePathEvaluator::apply(const RewriteStep &step,
const RewriteSystem &system) {
switch (step.Kind) {
case RewriteStep::Rule:
(void) applyRewriteRule(step, system);
break;
case RewriteStep::PrefixSubstitutions:
(void) applyPrefixSubstitutions(step, system);
break;
case RewriteStep::Shift:
applyShift(step, system);
break;
case RewriteStep::Decompose:
applyDecompose(step, system);
break;
case RewriteStep::Relation:
applyRelation(step, system);
break;
case RewriteStep::DecomposeConcrete:
applyDecomposeConcrete(step, system);
break;
case RewriteStep::LeftConcreteProjection:
applyLeftConcreteProjection(step, system);
break;
case RewriteStep::RightConcreteProjection:
applyRightConcreteProjection(step, system);
break;
}
}
| 31.628043
| 84
| 0.632227
|
tshortli
|
6a67e6851474a0db95c6602b46c6f35411fddf69
| 11,633
|
cpp
|
C++
|
source/common/2d/v_drawtext.cpp
|
madame-rachelle/Raze
|
67c8187d620e6cf9e99543cab5c5746dd31007af
|
[
"RSA-MD"
] | null | null | null |
source/common/2d/v_drawtext.cpp
|
madame-rachelle/Raze
|
67c8187d620e6cf9e99543cab5c5746dd31007af
|
[
"RSA-MD"
] | null | null | null |
source/common/2d/v_drawtext.cpp
|
madame-rachelle/Raze
|
67c8187d620e6cf9e99543cab5c5746dd31007af
|
[
"RSA-MD"
] | null | null | null |
/*
** v_text.cpp
** Draws text to a canvas. Also has a text line-breaker thingy.
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <wctype.h>
#include "v_text.h"
#include "utf8.h"
#include "v_draw.h"
#include "gstrings.h"
#include "vm.h"
#include "printf.h"
int ListGetInt(VMVa_List &tags);
//==========================================================================
//
// Create a texture from a text in a given font.
//
//==========================================================================
#if 0
FGameTexture * BuildTextTexture(FFont *font, const char *string, int textcolor)
{
int w;
const uint8_t *ch;
int cx;
int cy;
int trans = -1;
int kerning;
FGameTexture *pic;
kerning = font->GetDefaultKerning();
ch = (const uint8_t *)string;
cx = 0;
cy = 0;
IntRect box;
while (auto c = GetCharFromString(ch))
{
if (c == TEXTCOLOR_ESCAPE)
{
// Here we only want to measure the texture so just parse over the color.
V_ParseFontColor(ch, 0, 0);
continue;
}
if (c == '\n')
{
cx = 0;
cy += font->GetHeight();
continue;
}
if (nullptr != (pic = font->GetChar(c, CR_UNTRANSLATED, &w, nullptr)))
{
auto img = pic->GetImage();
auto offsets = img->GetOffsets();
int x = cx - offsets.first;
int y = cy - offsets.second;
int ww = img->GetWidth();
int h = img->GetHeight();
box.AddToRect(x, y);
box.AddToRect(x + ww, y + h);
}
cx += (w + kerning);
}
cx = -box.left;
cy = -box.top;
TArray<TexPart> part(strlen(string));
while (auto c = GetCharFromString(ch))
{
if (c == TEXTCOLOR_ESCAPE)
{
EColorRange newcolor = V_ParseFontColor(ch, textcolor, textcolor);
if (newcolor != CR_UNDEFINED)
{
trans = font->GetColorTranslation(newcolor);
textcolor = newcolor;
}
continue;
}
if (c == '\n')
{
cx = 0;
cy += font->GetHeight();
continue;
}
if (nullptr != (pic = font->GetChar(c, textcolor, &w, nullptr)))
{
auto img = pic->GetImage();
auto offsets = img->GetOffsets();
int x = cx - offsets.first;
int y = cy - offsets.second;
auto &tp = part[part.Reserve(1)];
tp.OriginX = x;
tp.OriginY = y;
tp.Image = img;
tp.Translation = range;
}
cx += (w + kerning);
}
FMultiPatchTexture *image = new FMultiPatchTexture(box.width, box.height, part, false, false);
image->SetOffsets(-box.left, -box.top);
FImageTexture *tex = new FImageTexture(image, "");
tex->SetUseType(ETextureType::MiscPatch);
TexMan.AddTexture(tex);
return tex;
}
#endif
//==========================================================================
//
// DrawChar
//
// Write a single character using the given font
//
//==========================================================================
void DrawChar(F2DDrawer *drawer, FFont* font, int normalcolor, double x, double y, int character, int tag_first, ...)
{
if (font == NULL)
return;
if (normalcolor >= NumTextColors)
normalcolor = CR_UNTRANSLATED;
FGameTexture* pic;
int dummy;
bool redirected;
if (NULL != (pic = font->GetChar(character, normalcolor, &dummy, &redirected)))
{
DrawParms parms;
Va_List tags;
va_start(tags.list, tag_first);
bool res = ParseDrawTextureTags(drawer, pic, x, y, tag_first, tags, &parms, false);
va_end(tags.list);
if (!res)
{
return;
}
PalEntry color = 0xffffffff;
parms.TranslationId = redirected ? -1 : font->GetColorTranslation((EColorRange)normalcolor, &color);
parms.color = PalEntry((color.a * parms.color.a) / 255, (color.r * parms.color.r) / 255, (color.g * parms.color.g) / 255, (color.b * parms.color.b) / 255);
drawer->AddTexture(pic, parms);
}
}
void DrawChar(F2DDrawer *drawer, FFont *font, int normalcolor, double x, double y, int character, VMVa_List &args)
{
if (font == NULL)
return;
if (normalcolor >= NumTextColors)
normalcolor = CR_UNTRANSLATED;
FGameTexture *pic;
int dummy;
bool redirected;
if (NULL != (pic = font->GetChar(character, normalcolor, &dummy, &redirected)))
{
DrawParms parms;
uint32_t tag = ListGetInt(args);
bool res = ParseDrawTextureTags(drawer, pic, x, y, tag, args, &parms, false);
if (!res) return;
PalEntry color = 0xffffffff;
parms.TranslationId = redirected ? -1 : font->GetColorTranslation((EColorRange)normalcolor, &color);
parms.color = PalEntry((color.a * parms.color.a) / 255, (color.r * parms.color.r) / 255, (color.g * parms.color.g) / 255, (color.b * parms.color.b) / 255);
drawer->AddTexture(pic, parms);
}
}
DEFINE_ACTION_FUNCTION(_Screen, DrawChar)
{
PARAM_PROLOGUE;
PARAM_POINTER(font, FFont);
PARAM_INT(cr);
PARAM_FLOAT(x);
PARAM_FLOAT(y);
PARAM_INT(chr);
PARAM_VA_POINTER(va_reginfo) // Get the hidden type information array
if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function");
VMVa_List args = { param + 5, 0, numparam - 6, va_reginfo + 5 };
DrawChar(twod, font, cr, x, y, chr, args);
return 0;
}
//==========================================================================
//
// DrawText
//
// Write a string using the given font
//
//==========================================================================
// This is only needed as a dummy. The code using wide strings does not need color control.
EColorRange V_ParseFontColor(const char32_t *&color_value, int normalcolor, int boldcolor) { return CR_UNTRANSLATED; }
template<class chartype>
void DrawTextCommon(F2DDrawer *drawer, FFont *font, int normalcolor, double x, double y, const chartype *string, DrawParms &parms)
{
int w;
const chartype *ch;
int c;
double cx;
double cy;
int boldcolor;
int trans = -1;
int kerning;
FGameTexture *pic;
double scalex = parms.scalex * parms.patchscalex;
double scaley = parms.scaley * parms.patchscaley;
if (parms.celly == 0) parms.celly = font->GetHeight() + 1;
parms.celly *= scaley;
bool palettetrans = (normalcolor == CR_UNDEFINED && parms.TranslationId != 0);
if (normalcolor >= NumTextColors)
normalcolor = CR_UNTRANSLATED;
boldcolor = normalcolor ? normalcolor - 1 : NumTextColors - 1;
PalEntry colorparm = parms.color;
PalEntry color = 0xffffffff;
trans = palettetrans? -1 : font->GetColorTranslation((EColorRange)normalcolor, &color);
parms.color = PalEntry(colorparm.a, (color.r * colorparm.r) / 255, (color.g * colorparm.g) / 255, (color.b * colorparm.b) / 255);
kerning = font->GetDefaultKerning();
ch = string;
cx = x;
cy = y;
if (parms.monospace == EMonospacing::CellCenter)
cx += parms.spacing / 2;
else if (parms.monospace == EMonospacing::CellRight)
cx += parms.spacing;
auto currentcolor = normalcolor;
while (ch - string < parms.maxstrlen)
{
c = GetCharFromString(ch);
if (!c)
break;
if (c == TEXTCOLOR_ESCAPE)
{
EColorRange newcolor = V_ParseFontColor(ch, normalcolor, boldcolor);
if (newcolor != CR_UNDEFINED)
{
trans = font->GetColorTranslation(newcolor, &color);
parms.color = PalEntry(colorparm.a, (color.r * colorparm.r) / 255, (color.g * colorparm.g) / 255, (color.b * colorparm.b) / 255);
currentcolor = newcolor;
}
continue;
}
if (c == '\n')
{
cx = x;
cy += parms.celly;
continue;
}
bool redirected = false;
if (NULL != (pic = font->GetChar(c, currentcolor, &w, &redirected)))
{
// if palette translation is used, font colors will be ignored.
if (!palettetrans) parms.TranslationId = redirected? -1 : trans;
SetTextureParms(drawer, &parms, pic, cx, cy);
if (parms.cellx)
{
w = parms.cellx;
parms.destwidth = parms.cellx;
parms.destheight = parms.celly;
}
if (parms.monospace == EMonospacing::CellLeft)
parms.left = 0;
else if (parms.monospace == EMonospacing::CellCenter)
parms.left = w / 2.;
else if (parms.monospace == EMonospacing::CellRight)
parms.left = w;
drawer->AddTexture(pic, parms);
}
if (parms.monospace == EMonospacing::Off)
{
cx += (w + kerning + parms.spacing) * scalex;
}
else
{
cx += (parms.spacing) * scalex;
}
}
}
// For now the 'drawer' parameter is a placeholder - this should be the way to handle it later to allow different drawers.
void DrawText(F2DDrawer *drawer, FFont* font, int normalcolor, double x, double y, const char* string, int tag_first, ...)
{
Va_List tags;
DrawParms parms;
if (font == NULL || string == NULL)
return;
va_start(tags.list, tag_first);
bool res = ParseDrawTextureTags(drawer, nullptr, 0, 0, tag_first, tags, &parms, true);
va_end(tags.list);
if (!res)
{
return;
}
DrawTextCommon(drawer, font, normalcolor, x, y, (const uint8_t*)string, parms);
}
void DrawText(F2DDrawer *drawer, FFont* font, int normalcolor, double x, double y, const char32_t* string, int tag_first, ...)
{
Va_List tags;
DrawParms parms;
if (font == NULL || string == NULL)
return;
va_start(tags.list, tag_first);
bool res = ParseDrawTextureTags(drawer, nullptr, 0, 0, tag_first, tags, &parms, true);
va_end(tags.list);
if (!res)
{
return;
}
DrawTextCommon(drawer, font, normalcolor, x, y, string, parms);
}
void DrawText(F2DDrawer *drawer, FFont *font, int normalcolor, double x, double y, const char *string, VMVa_List &args)
{
DrawParms parms;
if (font == NULL || string == NULL)
return;
uint32_t tag = ListGetInt(args);
bool res = ParseDrawTextureTags(drawer, nullptr, 0, 0, tag, args, &parms, true);
if (!res)
{
return;
}
DrawTextCommon(drawer, font, normalcolor, x, y, (const uint8_t*)string, parms);
}
DEFINE_ACTION_FUNCTION(_Screen, DrawText)
{
PARAM_PROLOGUE;
PARAM_POINTER_NOT_NULL(font, FFont);
PARAM_INT(cr);
PARAM_FLOAT(x);
PARAM_FLOAT(y);
PARAM_STRING(chr);
PARAM_VA_POINTER(va_reginfo) // Get the hidden type information array
if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function");
VMVa_List args = { param + 5, 0, numparam - 6, va_reginfo + 5 };
const char *txt = chr[0] == '$' ? GStrings(&chr[1]) : chr.GetChars();
DrawText(twod, font, cr, x, y, txt, args);
return 0;
}
| 27.501182
| 157
| 0.644116
|
madame-rachelle
|
6a6c2bd3082c445842795cea2f01d6e4b8678308
| 311
|
cc
|
C++
|
packages/operator/Null_Operator.cc
|
brbass/ibex
|
5a4cc5b4d6d46430d9667970f8a34f37177953d4
|
[
"MIT"
] | 2
|
2020-04-13T20:06:41.000Z
|
2021-02-12T17:55:54.000Z
|
packages/operator/Null_Operator.cc
|
brbass/ibex
|
5a4cc5b4d6d46430d9667970f8a34f37177953d4
|
[
"MIT"
] | 1
|
2018-10-22T21:03:35.000Z
|
2018-10-22T21:03:35.000Z
|
packages/operator/Null_Operator.cc
|
brbass/ibex
|
5a4cc5b4d6d46430d9667970f8a34f37177953d4
|
[
"MIT"
] | 3
|
2019-04-03T02:15:37.000Z
|
2022-01-04T05:50:23.000Z
|
#include "Null_Operator.hh"
using std::vector;
Null_Operator::
Null_Operator(int size):
Square_Vector_Operator(),
size_(size)
{
check_class_invariants();
}
void Null_Operator::
apply(vector<double> &x) const
{
x.assign(x.size(), 0);
}
void Null_Operator::
check_class_invariants() const
{
}
| 13.521739
| 30
| 0.70418
|
brbass
|
6a6dcb89a1bfe4b43b2415b2428011ef89f0ac79
| 3,537
|
hpp
|
C++
|
modules/core/src/MetaObject/logging/logging_macros.hpp
|
dtmoodie/MetaObject
|
8238d143d578ff9c0c6506e7e627eca15e42369e
|
[
"MIT"
] | 2
|
2017-10-26T04:41:49.000Z
|
2018-02-09T05:12:19.000Z
|
modules/core/src/MetaObject/logging/logging_macros.hpp
|
dtmoodie/MetaObject
|
8238d143d578ff9c0c6506e7e627eca15e42369e
|
[
"MIT"
] | null | null | null |
modules/core/src/MetaObject/logging/logging_macros.hpp
|
dtmoodie/MetaObject
|
8238d143d578ff9c0c6506e7e627eca15e42369e
|
[
"MIT"
] | 3
|
2017-01-08T21:09:48.000Z
|
2018-02-10T04:27:32.000Z
|
#ifndef MO_LOGGING_LOGGING_MACROS_HPP
#define MO_LOGGING_LOGGING_MACROS_HPP
#include "callstack.hpp"
#include <spdlog/fmt/fmt.h>
#include <spdlog/fmt/ostr.h>
#if defined(__GNUC__) && __GNUC__ == 4 && defined(__NVCC__)
// These empy definitions are for GCC 4.8 with cuda 6.5 since it can't handle fmt
#define LOG_EVERY_N_VARNAME(base, line)
#define LOG_EVERY_N_VARNAME_CONCAT(base, line)
#define LOG_OCCURRENCES
#define LOG_OCCURRENCES_MOD_N
#define LOG_THEN_THROW(level, ...)
#define THROW(level, ...)
#define MO_ASSERT(CHECK)
#define MO_ASSERT_GT(LHS, RHS)
#define MO_ASSERT_GE(LHS, RHS)
#define MO_ASSERT_FMT(CHECK, ...)
#define MO_LOG(LEVEL, ...)
#else
// All other competent compilers
#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base##line
#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
#define LOG_THEN_THROW(level, LOGGER, ...) \
do \
{ \
std::string msg = fmt::format(__VA_ARGS__); \
LOGGER.level(msg); \
mo::throwWithCallstack(std::runtime_error(std::move(msg))); \
} while (0)
#define THROW(level, ...) LOG_THEN_THROW(level, mo::getDefaultLogger(), __VA_ARGS__)
#define THROW_LOGGER(LOGGER, level, ...) LOG_THEN_THROW(level, LOGGER, __VA_ARGS__)
#define MO_ASSERT_LOGGER(LOGGER, CHECK) \
if (!(CHECK)) \
THROW(error, #CHECK)
#define MO_ASSERT(CHECK) MO_ASSERT_LOGGER(mo::getDefaultLogger(), CHECK)
#define MO_ASSERT_EQ(LHS, RHS) \
if ((LHS) != (RHS)) \
THROW(error, #LHS " != " #RHS " [{} != {}]", LHS, RHS)
#define MO_ASSERT_FMT(CHECK, ...) \
if (!(CHECK)) \
THROW(error, __VA_ARGS__)
#define MO_ASSERT_GT(LHS, RHS) \
if (!((LHS) > (RHS))) \
THROW(error, #LHS " <= " #RHS " [{} <= {}]", LHS, RHS)
#define MO_ASSERT_GE(LHS, RHS) \
if (!((LHS) >= (RHS))) \
THROW(error, #LHS " < " #RHS " [{} < {}]", LHS, RHS)
#define MO_LOG(LEVEL, ...) mo::getDefaultLogger().LEVEL(__VA_ARGS__)
#endif
#endif // MO_LOGGING_LOGGING_MACROS_HPP
| 46.539474
| 120
| 0.412214
|
dtmoodie
|
6a6f18c655199562b2e4dec1b14e964eaaa1cad0
| 4,194
|
cpp
|
C++
|
src/Engine/App/Entity.cpp
|
kimkulling/osre
|
b738c87e37d0b1d2d0779a412b88ce68517c4328
|
[
"MIT"
] | 118
|
2015-05-12T15:12:14.000Z
|
2021-11-14T15:41:11.000Z
|
src/Engine/App/Entity.cpp
|
kimkulling/osre
|
b738c87e37d0b1d2d0779a412b88ce68517c4328
|
[
"MIT"
] | 76
|
2015-06-06T18:04:24.000Z
|
2022-01-14T20:17:37.000Z
|
src/Engine/App/Entity.cpp
|
kimkulling/osre
|
b738c87e37d0b1d2d0779a412b88ce68517c4328
|
[
"MIT"
] | 7
|
2016-06-28T09:14:38.000Z
|
2021-03-12T02:07:52.000Z
|
/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015-2021 OSRE ( Open Source Render Engine ) by Kim Kulling
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 <osre/App/AbstractBehaviour.h>
#include <osre/App/Component.h>
#include <osre/App/Entity.h>
#include <osre/App/World.h>
#include <osre/Scene/MeshProcessor.h>
namespace OSRE {
namespace App {
using namespace ::OSRE::Scene;
using namespace ::OSRE::RenderBackend;
Entity::Entity(const String &name, const Common::Ids &ids, World *world) :
Object(name),
m_behaviour(nullptr),
m_renderComponent(nullptr),
m_node(nullptr),
m_ids(ids),
m_aabb(),
mOwner(world) {
m_renderComponent = new RenderComponent(this, 1);
if (nullptr != world) {
mOwner->addEntity(this);
}
}
Entity::~Entity() {
delete m_renderComponent;
if (nullptr != mOwner) {
mOwner->removeEntity(this);
}
}
void Entity::setBehaviourControl(AbstractBehaviour *behaviour) {
m_behaviour = behaviour;
}
void Entity::addStaticMesh(RenderBackend::Mesh *mesh ) {
if (nullptr == mesh) {
return;
}
RenderComponent *comp = (RenderComponent *)getComponent(ComponentType::RenderComponentType);
if (nullptr == comp) {
return;
}
comp->addStaticMesh(mesh);
Scene::MeshProcessor processor;
processor.addGeo(mesh);
if (processor.execute()) {
setAABB(processor.getAABB());
}
}
void Entity::addStaticMeshes(const MeshArray &meshArray) {
if (meshArray.isEmpty()) {
return;
}
RenderComponent *comp = (RenderComponent *)getComponent(ComponentType::RenderComponentType);
if (nullptr != comp) {
comp->addStaticMeshArray(meshArray);
}
Scene::MeshProcessor processor;
for (ui32 i = 0; i < meshArray.size(); ++i) {
processor.addGeo(meshArray[i]);
}
if (processor.execute()) {
setAABB(processor.getAABB());
}
}
void Entity::setNode(Node *node) {
m_node = node;
}
Node *Entity::getNode() const {
return m_node;
}
bool Entity::preprocess() {
return true;
}
bool Entity::update(Time dt) {
if (nullptr != m_behaviour) {
m_behaviour->update(dt);
}
return true;
}
bool Entity::render(RenderBackend::RenderBackendService *rbSrv) {
m_renderComponent->render(rbSrv);
return true;
}
bool Entity::postprocess() {
return true;
}
Component *Entity::getComponent(ComponentType type) const {
switch (type) {
case OSRE::App::ComponentType::RenderComponentType:
return m_renderComponent;
case OSRE::App::ComponentType::ScriptComponent:
break;
case OSRE::App::ComponentType::MaxNumComponents:
case OSRE::App::ComponentType::InvalidComponent:
break;
default:
break;
}
return nullptr;
}
void Entity::setAABB(const Node::AABB &aabb) {
m_aabb = aabb;
}
const Node::AABB &Entity::getAABB() const {
return m_aabb;
}
} // Namespace App
} // Namespace OSRE
| 27.592105
| 97
| 0.651168
|
kimkulling
|
6a6f5aa1b606eeb85ad97f15508e3423638e7e4f
| 1,132
|
hpp
|
C++
|
src/stan/mcmc/hmc/nuts_classic/unit_e_nuts_classic.hpp
|
drezap/stan
|
9b319ed125e2a7d14d0c9c246d2f462dad668537
|
[
"BSD-3-Clause"
] | 1
|
2019-07-05T01:40:40.000Z
|
2019-07-05T01:40:40.000Z
|
src/stan/mcmc/hmc/nuts_classic/unit_e_nuts_classic.hpp
|
drezap/stan
|
9b319ed125e2a7d14d0c9c246d2f462dad668537
|
[
"BSD-3-Clause"
] | null | null | null |
src/stan/mcmc/hmc/nuts_classic/unit_e_nuts_classic.hpp
|
drezap/stan
|
9b319ed125e2a7d14d0c9c246d2f462dad668537
|
[
"BSD-3-Clause"
] | 1
|
2018-08-28T12:09:08.000Z
|
2018-08-28T12:09:08.000Z
|
#ifndef STAN_MCMC_HMC_NUTS_CLASSIC_UNIT_E_NUTS_CLASSIC_HPP
#define STAN_MCMC_HMC_NUTS_CLASSIC_UNIT_E_NUTS_CLASSIC_HPP
#include <stan/mcmc/hmc/nuts_classic/base_nuts_classic.hpp>
#include <stan/mcmc/hmc/hamiltonians/unit_e_point.hpp>
#include <stan/mcmc/hmc/hamiltonians/unit_e_metric.hpp>
#include <stan/mcmc/hmc/integrators/expl_leapfrog.hpp>
namespace stan {
namespace mcmc {
// The No-U-Turn Sampler (NUTS) on a
// Euclidean manifold with unit metric
template <class Model, class BaseRNG>
class unit_e_nuts_classic:
public base_nuts_classic<Model, unit_e_metric,
expl_leapfrog, BaseRNG> {
public:
unit_e_nuts_classic(const Model& model, BaseRNG& rng):
base_nuts_classic<Model, unit_e_metric,
expl_leapfrog, BaseRNG>(model, rng) { }
bool compute_criterion(ps_point& start,
unit_e_point& finish,
Eigen::VectorXd& rho) {
return finish.p.dot(rho - finish.p) > 0
&& start.p.dot(rho - start.p) > 0;
}
};
} // mcmc
} // stan
#endif
| 34.30303
| 65
| 0.64841
|
drezap
|
6a7681e2a6bea7ce3a2c76007a063924bcaaa1a9
| 845
|
cpp
|
C++
|
60A.cpp
|
felikjunvianto/kfile-codeforces-submissions
|
1b53da27a294a12063b0912e12ad32efe24af678
|
[
"MIT"
] | null | null | null |
60A.cpp
|
felikjunvianto/kfile-codeforces-submissions
|
1b53da27a294a12063b0912e12ad32efe24af678
|
[
"MIT"
] | null | null | null |
60A.cpp
|
felikjunvianto/kfile-codeforces-submissions
|
1b53da27a294a12063b0912e12ad32efe24af678
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
using namespace std;
int next,N,M,x,ans;
bool cek[1010];
char arah[10],da[10],db[10],dc[10];
int main()
{
scanf("%d %d",&N,&M);
memset(cek,true,sizeof(cek));
while(M--)
{
scanf("%s %s %s %s %d",da,db,arah,dc,&x);
if(arah[0]=='r') next=-1; else next=1;
for(int i=x;i&&(i<=N);i+=next) cek[i]=false;
}
ans=0;
for(x=1;x<=N;x++) if(cek[x]) ans++;
printf("%d\n",ans?ans:-1);
return 0;
}
| 18.369565
| 47
| 0.60355
|
felikjunvianto
|
6a76ade92f5ffde7e01f53caac461481206da438
| 10,835
|
cxx
|
C++
|
VTK/IO/vtkBYUWriter.cxx
|
matthb2/ParaView-beforekitwareswtichedtogit
|
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
|
[
"BSD-3-Clause"
] | 1
|
2021-07-31T19:38:03.000Z
|
2021-07-31T19:38:03.000Z
|
VTK/IO/vtkBYUWriter.cxx
|
matthb2/ParaView-beforekitwareswtichedtogit
|
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
|
[
"BSD-3-Clause"
] | null | null | null |
VTK/IO/vtkBYUWriter.cxx
|
matthb2/ParaView-beforekitwareswtichedtogit
|
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
|
[
"BSD-3-Clause"
] | 2
|
2019-01-22T19:51:40.000Z
|
2021-07-31T19:38:05.000Z
|
/*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile$
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkBYUWriter.h"
#include "vtkCellArray.h"
#include "vtkErrorCode.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#if !defined(_WIN32) || defined(__CYGWIN__)
# include <unistd.h> /* unlink */
#else
# include <io.h> /* unlink */
#endif
#include <vtkstd/string>
vtkCxxRevisionMacro(vtkBYUWriter, "$Revision$");
vtkStandardNewMacro(vtkBYUWriter);
// Create object so that it writes displacement, scalar, and texture files
// (if data is available).
vtkBYUWriter::vtkBYUWriter()
{
this->GeometryFileName = NULL;
this->DisplacementFileName = NULL;
this->ScalarFileName = NULL;
this->TextureFileName = NULL;
this->WriteDisplacement = 1;
this->WriteScalar = 1;
this->WriteTexture = 1;
}
vtkBYUWriter::~vtkBYUWriter()
{
if ( this->GeometryFileName )
{
delete [] this->GeometryFileName;
}
if ( this->DisplacementFileName )
{
delete [] this->DisplacementFileName;
}
if ( this->ScalarFileName )
{
delete [] this->ScalarFileName;
}
if ( this->TextureFileName )
{
delete [] this->TextureFileName;
}
}
// Write out data in MOVIE.BYU format.
void vtkBYUWriter::WriteData()
{
FILE *geomFp;
vtkPolyData *input= this->GetInput();
int numPts=input->GetNumberOfPoints();
if ( numPts < 1 )
{
vtkErrorMacro(<<"No data to write!");
return;
}
if ( !this->GeometryFileName )
{
vtkErrorMacro(<< "Geometry file name was not specified");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return;
}
if ((geomFp = fopen(this->GeometryFileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFileName);
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return;
}
else
{
this->WriteGeometryFile(geomFp,numPts);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
fclose(geomFp);
vtkErrorMacro("Ran out of disk space; deleting file: "
<< this->GeometryFileName);
unlink(this->GeometryFileName);
return;
}
}
this->WriteDisplacementFile(numPts);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
fclose(geomFp);
unlink(this->GeometryFileName);
unlink(this->DisplacementFileName);
vtkErrorMacro("Ran out of disk space; deleting files: "
<< this->GeometryFileName << " "
<< this->DisplacementFileName);
return;
}
this->WriteScalarFile(numPts);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
vtkstd::string errorMessage;
fclose(geomFp);
unlink(this->GeometryFileName);
errorMessage = "Ran out of disk space; deleting files: ";
errorMessage += this->GeometryFileName;
errorMessage += " ";
if (this->DisplacementFileName)
{
unlink(this->DisplacementFileName);
errorMessage += this->DisplacementFileName;
errorMessage += " ";
}
unlink(this->ScalarFileName);
errorMessage += this->ScalarFileName;
vtkErrorMacro( << errorMessage.c_str());
return;
}
this->WriteTextureFile(numPts);
if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)
{
fclose(geomFp);
vtkstd::string errorMessage;
unlink(this->GeometryFileName);
errorMessage = "Ran out of disk space; deleting files: ";
errorMessage += this->GeometryFileName;
errorMessage += " ";
if (this->DisplacementFileName)
{
unlink(this->DisplacementFileName);
errorMessage += this->DisplacementFileName;
errorMessage += " ";
}
if (this->ScalarFileName)
{
unlink(this->ScalarFileName);
errorMessage += this->ScalarFileName;
errorMessage += " ";
}
unlink(this->TextureFileName);
errorMessage += this->TextureFileName;
vtkErrorMacro( << errorMessage.c_str());
return;
}
// Close the file
fclose (geomFp);
}
void vtkBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts)
{
int numPolys, numEdges;
int i;
double *x;
vtkIdType npts = 0;
vtkIdType *pts = 0;
vtkPoints *inPts;
vtkCellArray *inPolys;
vtkPolyData *input= this->GetInput();
//
// Check input
//
inPolys=input->GetPolys();
if ( (inPts=input->GetPoints()) == NULL || inPolys == NULL )
{
vtkErrorMacro(<<"No data to write!");
return;
}
//
// Write header (not using fixed format! - potential problem in some files.)
//
numPolys = input->GetPolys()->GetNumberOfCells();
for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
{
numEdges += npts;
}
if (fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
if (fprintf (geomFile, "%d %d\n", 1, numPolys) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
//
// Write data
//
// write point coordinates
for (i=0; i < numPts; i++)
{
x = inPts->GetPoint(i);
if (fprintf(geomFile, "%e %e %e ", x[0], x[1], x[2]) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
if ( (i % 2) )
{
if (fprintf(geomFile, "\n") < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
}
}
if ( (numPts % 2) )
{
if (fprintf(geomFile, "\n") < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
}
// write poly data. Remember 1-offset.
for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
{
// write this polygon
// treating vtkIdType as int
for (i=0; i < (npts-1); i++)
{
if (fprintf (geomFile, "%d ", static_cast<int>(pts[i]+1)) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
}
if (fprintf (geomFile, "%d\n", static_cast<int>(-(pts[npts-1]+1))) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
return;
}
}
vtkDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons");
}
void vtkBYUWriter::WriteDisplacementFile(int numPts)
{
FILE *dispFp;
int i;
double *v;
vtkDataArray *inVectors;
vtkPolyData *input= this->GetInput();
if ( this->WriteDisplacement && this->DisplacementFileName &&
(inVectors = input->GetPointData()->GetVectors()) != NULL )
{
if ( !(dispFp = fopen(this->DisplacementFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open displacement file");
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
v = inVectors->GetTuple(i);
if (fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
fclose(dispFp);
return;
}
if ( (i % 2) )
{
if (fprintf (dispFp, "\n") < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
fclose(dispFp);
return;
}
}
}
vtkDebugMacro(<<"Wrote " << numPts << " displacements");
fclose (dispFp);
}
void vtkBYUWriter::WriteScalarFile(int numPts)
{
FILE *scalarFp;
int i;
float s;
vtkDataArray *inScalars;
vtkPolyData *input= this->GetInput();
if ( this->WriteScalar && this->ScalarFileName &&
(inScalars = input->GetPointData()->GetScalars()) != NULL )
{
if ( !(scalarFp = fopen(this->ScalarFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open scalar file");
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
s = inScalars->GetComponent(i,0);
if (fprintf(scalarFp, "%e ", s) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
fclose(scalarFp);
return;
}
if ( i != 0 && !(i % 6) )
{
if (fprintf (scalarFp, "\n") < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
fclose(scalarFp);
return;
}
}
}
fclose (scalarFp);
vtkDebugMacro(<<"Wrote " << numPts << " scalars");
}
void vtkBYUWriter::WriteTextureFile(int numPts)
{
FILE *textureFp;
int i;
double *t;
vtkDataArray *inTCoords;
vtkPolyData *input= this->GetInput();
if ( this->WriteTexture && this->TextureFileName &&
(inTCoords = input->GetPointData()->GetTCoords()) != NULL )
{
if ( !(textureFp = fopen(this->TextureFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open texture file");
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
if ( i != 0 && !(i % 3) )
{
if (fprintf (textureFp, "\n") < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
fclose(textureFp);
return;
}
}
t = inTCoords->GetTuple(i);
if (fprintf(textureFp, "%e %e", t[0], t[1]) < 0)
{
this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);
fclose(textureFp);
return;
}
}
fclose (textureFp);
vtkDebugMacro(<<"Wrote " << numPts << " texture coordinates");
}
void vtkBYUWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Geometry File Name: "
<< (this->GeometryFileName ? this->GeometryFileName : "(none)") << "\n";
os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n");
os << indent << "Displacement File Name: "
<< (this->DisplacementFileName ? this->DisplacementFileName : "(none)") << "\n";
os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n");
os << indent << "Scalar File Name: "
<< (this->ScalarFileName ? this->ScalarFileName : "(none)") << "\n";
os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n");
os << indent << "Texture File Name: "
<< (this->TextureFileName ? this->TextureFileName : "(none)") << "\n";
}
| 25.25641
| 89
| 0.594555
|
matthb2
|
6a8198ec5eb2ff402f417791fbf8361c14da4a57
| 3,398
|
cpp
|
C++
|
test/TestSere.cpp
|
craft095/sere
|
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
|
[
"MIT"
] | null | null | null |
test/TestSere.cpp
|
craft095/sere
|
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
|
[
"MIT"
] | null | null | null |
test/TestSere.cpp
|
craft095/sere
|
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
|
[
"MIT"
] | null | null | null |
#include "catch2/catch.hpp"
#include "test/GenLetter.hpp"
#include "test/GenBoolExpr.hpp"
#include "test/EvalBoolExpr.hpp"
#include "test/EvalSere.hpp"
#include "test/EvalNfasl.hpp"
#include "test/Tools.hpp"
#include "test/ToolsZ3.hpp"
#include "ast/BoolExpr.hpp"
#include "ast/SereExpr.hpp"
#include "sat/Sat.hpp"
TEST_CASE("Sere") {
SECTION("empty") {
CHECK(evalSere(*RE_EMPTY, {}) == Match_Ok);
CHECK(evalSere(*RE_EMPTY, {makeNames({},{})}) == Match_Failed);
}
SECTION("boolean") {
CHECK(evalSere(*RE_SEREBOOL(RE_TRUE), {makeNames({1}, {0})}) == Match_Ok);
CHECK(evalSere(*RE_SEREBOOL(RE_FALSE), {makeNames({1}, {0})}) == Match_Failed);
CHECK(evalSere(*RE_SEREBOOL(RE_NOT(RE_TRUE)), {makeNames({1}, {0})}) == Match_Failed);
CHECK(evalSere(*RE_SEREBOOL(RE_VAR(1)), {makeNames({1}, {0})}) == Match_Ok);
CHECK(evalSere(*RE_SEREBOOL(RE_VAR(0)), {makeNames({1}, {0})}) == Match_Failed);
Ptr<SereExpr> tc = RE_SEREBOOL(RE_AND(RE_TRUE, RE_NOT(RE_VAR(0))));
CHECK(evalSere(*tc, {makeNames({1}, {0})}) == Match_Ok);
CHECK(evalSere(*tc, {makeNames({0}, {1})}) == Match_Failed);
CHECK(evalSere(*tc, {makeNames({1}, {0}), makeNames({1}, {0})}) == Match_Failed);
CHECK(evalSere(*tc, {}) == Match_Partial);
// ASSERT_EQ(evalSere(*tc, {{"z", "y"}}), Match_Failed);
}
SECTION("concat") {
CHECK(evalSere(*RE_CONCAT
(RE_SEREBOOL(RE_VAR(0)),
RE_SEREBOOL(RE_VAR(1))),
{}) == Match_Partial);
CHECK(evalSere(*RE_CONCAT
(RE_SEREBOOL(RE_VAR(0)),
RE_SEREBOOL(RE_VAR(1))),
{makeNames({0},{1}),makeNames({1},{0})}) == Match_Ok);
CHECK(evalSere(*RE_CONCAT
(RE_SEREBOOL(RE_VAR(0)),
RE_SEREBOOL(RE_VAR(1))),
{makeNames({0,1},{}),makeNames({0},{1})}) == Match_Failed);
CHECK(evalSere
(*RE_CONCAT
(RE_CONCAT
(RE_SEREBOOL(RE_VAR(0)),
RE_SEREBOOL(RE_VAR(1))
),
RE_SEREBOOL(RE_VAR(0))),
{makeNames({0},{1})}) == Match_Partial);
CHECK(evalSere
(*RE_CONCAT
(RE_CONCAT
(RE_SEREBOOL(RE_VAR(0)),
RE_SEREBOOL(RE_VAR(1))
),
RE_SEREBOOL(RE_VAR(0))),
{makeNames({0},{1}),makeNames({0},{1})}) == Match_Failed);
}
}
TEST_CASE("Bool Expressions") {
constexpr size_t atoms = 3;
CHECK(!sat(*RE_AND(
RE_VAR(0),
RE_NOT(RE_VAR(0)))));
auto expr = GENERATE(Catch2::take(100, genBoolExpr(3, atoms)));
SECTION("Minisat") {
CHECK(sat(*expr) == satisfiable(boolSereToZex(*expr)));
}
#if 0
{
auto letter = GENERATE(Catch2::take(10, genLetter(atoms)));
SECTION("Z3") {
CHECK(evalBool(*expr, letter) == evalBoolZ3(*expr, letter));
}
SECTION("RtPredicate") {
std::vector<uint8_t> data;
rt::toRtPredicate(*expr, data);
CHECK(evalBool(*expr, letter) == rt::eval(letter, &data[0], data.size()));
}
}
#endif
}
TEST_CASE("Sere vs Nfasl") {
constexpr size_t atoms = 3;
auto expr = GENERATE(Catch2::take(10, genBoolExpr(3, atoms)));
auto word = GENERATE(Catch2::take(3, genWord(atoms, 0, 3)));
auto nfasl = sereToNfasl(*RE_SEREBOOL(expr));
REQUIRE(evalSere(*RE_SEREBOOL(expr), word) == evalNfasl(nfasl, word));
}
| 32.361905
| 90
| 0.572984
|
craft095
|
6a822558bef69cc924668c795089a17ccc2b9c9f
| 1,865
|
hpp
|
C++
|
third_party/boost/simd/function/frexp.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | 1
|
2018-01-14T12:49:14.000Z
|
2018-01-14T12:49:14.000Z
|
third_party/boost/simd/function/frexp.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/boost/simd/function/frexp.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | 2
|
2017-12-12T12:29:52.000Z
|
2019-04-08T15:55:25.000Z
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_FREXP_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_FREXP_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-ieee
Function object implementing frexp capabilities
Computes a mantissa and an exponent pair for the input
@par Semantic:
For every parameter of floating type @c T
@code
std::tie(m, e)= frexp(x);
@endcode
is similar to:
@code
as_integer_t<T> e = exponent(x)+1;
T m = copysign(mantissa(x)/2, x);
@endcode
The call
@code
std:pair<T,as_integer_t<T>> p = frexp(x);
@endcode
can also be used.
@par Note:
This function splits a floating point value @c v f in a signed mantissa @c m and
an exponent @c e so that: @f$v = m\times 2^e@f$,
with absolute value of @c m \f$\in [1/2, 1[\f$
@warninbox{Take care that these results differ from the returns of the functions @ref mantissa
and @ref exponent}
The decorators fast_ and std_ can be used.
fast_ provides a speedier call, but special values as Nan or Inf are not handled properly.
std_ transmit the call to std::frexp. That implies that simd is ever emulated.
@see exponent, mantissa, copysign
**/
std::pair<T, as_integer_t<Value>> frexp(Value const & v0);
} }
#endif
#include <boost/simd/function/scalar/frexp.hpp>
#include <boost/simd/function/scalar/frexp.hpp>
#include <boost/simd/function/simd/frexp.hpp>
#endif
| 25.547945
| 100
| 0.617158
|
xmar
|
6a8689133b64f4ea599d6c612f480d916ebb8c17
| 2,634
|
cpp
|
C++
|
graph-source-code/266-D/12228977.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/266-D/12228977.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/266-D/12228977.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: GNU C++11
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <iostream>
#include <complex>
using namespace std;
#define pb push_back
#define mp make_pair
#define point complex<double>
#define xx real()
#define yy imag()
const int maxn = 205, inf = 1 << 27;
int g[maxn][maxn], g1[maxn][maxn];
int qq[maxn], h, t, n, dis[maxn];
char col[maxn];
int aa[maxn], dd[maxn], x[maxn], bb[maxn], l;
int find_min(){
int i, ind, ind1, ans;
ind = 1;
for(i = 2; i <= n; i++){
if (aa[i] > aa[ind] || aa[i] == aa[ind] && x[i] > x[ind]){
ind = i;
}
}
ans = aa[ind];
while(x[ind] < l){
ind1 = -1;
for(i = 1; i <= n; i++){
if (x[i] + dd[i] > x[ind] + dd[ind] &&
(ind1 == -1 || aa[i] > aa[ind1] ||
aa[i] == aa[ind1] && dd[i] > dd[ind1])){
ind1 = i;
}
}
if (ind1 == -1)
break;
ans = min(ans, (x[ind] + dd[ind] + aa[ind1]) / 2);
ind = ind1;
}
return ans;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int m, i, j, k, a, b, w;
int cur, ans;
scanf("%d %d", &n, &m);
for(i = 0; i < m; i++){
scanf("%d %d %d", &a, &b, &w);
g[a][b] = g[b][a] = 2 * w;
}
for(i = 1; i <= n; i++){
for(j = i + 1; j <= n; j++){
g1[i][j] = g1[j][i] = (g[i][j]? g[i][j]: inf);
}
}
for(k = 1; k <= n; k++){
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++){
g1[i][j] = min(g1[i][j], g1[i][k] + g1[k][j]);
}
}
}
ans = inf;
for(i = 1; i <= n; i++){
cur = 0;
for(j = 1; j <= n; j++){
cur = max(cur, g1[i][j]);
}
ans = min(ans, cur);
}
for(i = 1; i <= n; i++){
for(j = i + 1; j <= n; j++){
if (!g[i][j])
continue;
cur = 0;
l = g[i][j];
for(k = 1; k <= n; k++){
aa[k] = g1[i][k];
bb[k] = g1[j][k];
x[k] = (bb[k] + l - aa[k]) / 2;
dd[k] = aa[k] + x[k];
}
cur = find_min();
ans = min(ans, cur);
}
}
printf("%d.%d", ans / 2, 5 * (ans % 2));
}
| 24.616822
| 67
| 0.368261
|
AmrARaouf
|
6a86e7a4783f289dcfeea887c1971865e5a29469
| 12,677
|
cpp
|
C++
|
worldeditor/src/graph/sceneview.cpp
|
thunder-engine/thunder
|
14a70d46532b8b78635835fc05c0ac2f33a12d8b
|
[
"Apache-2.0"
] | 162
|
2020-09-18T19:42:43.000Z
|
2022-03-30T20:27:42.000Z
|
worldeditor/src/graph/sceneview.cpp
|
thunder-engine/thunder
|
14a70d46532b8b78635835fc05c0ac2f33a12d8b
|
[
"Apache-2.0"
] | 162
|
2020-10-10T11:16:52.000Z
|
2022-03-30T17:09:11.000Z
|
worldeditor/src/graph/sceneview.cpp
|
thunder-engine/thunder
|
14a70d46532b8b78635835fc05c0ac2f33a12d8b
|
[
"Apache-2.0"
] | 12
|
2020-10-18T09:16:35.000Z
|
2022-01-08T11:23:17.000Z
|
#include "sceneview.h"
#include <QWindow>
#include <QStandardPaths>
#include <QMouseEvent>
#include <QVBoxLayout>
#include <QDebug>
#include <engine.h>
#include <timer.h>
#include <components/actor.h>
#include <components/scene.h>
#include <components/camera.h>
#include <resources/pipeline.h>
#include <systems/rendersystem.h>
#include "pluginmanager.h"
#define NONE 0
#define RELEASE 1
#define PRESS 2
#define REPEAT 3
SceneView::SceneView(QWidget *parent) :
QWidget(parent),
m_pScene(nullptr),
m_pEngine(nullptr) {
QVBoxLayout *l = new QVBoxLayout;
l->setContentsMargins(0, 0, 0, 0);
setLayout(l);
RenderSystem *render = PluginManager::instance()->render();
if(render) {
m_pRHIWindow = render->createRhiWindow();
m_pRHIWindow->installEventFilter(this);
connect(m_pRHIWindow, SIGNAL(draw()), this, SLOT(onDraw()), Qt::DirectConnection);
layout()->addWidget(QWidget::createWindowContainer(m_pRHIWindow));
} else {
qCritical() << "Unable to create rendering surface.";
}
}
SceneView::~SceneView() {
m_pEngine->setPlatformAdaptor(nullptr);
}
void SceneView::setEngine(Engine *engine) {
m_pEngine = engine;
m_pEngine->setPlatformAdaptor(this);
}
void SceneView::setScene(Scene *scene) {
m_pScene = scene;
}
void SceneView::onDraw() {
if(m_pScene) {
Timer::update();
findCamera();
if(m_pEngine) {
m_pEngine->update(m_pScene);
}
}
}
Input::KeyCode mapToInput(int32_t key) {
Input::KeyCode result = Input::KEY_UNKNOWN;
switch(key) {
case Qt::Key_Space: result = Input::KEY_SPACE; break;
case Qt::Key_Apostrophe: result = Input::KEY_APOSTROPHE; break;
case Qt::Key_Comma: result = Input::KEY_COMMA; break;
case Qt::Key_Minus: result = Input::KEY_MINUS; break;
case Qt::Key_Period: result = Input::KEY_PERIOD; break;
case Qt::Key_Slash: result = Input::KEY_SLASH; break;
case Qt::Key_0: result = Input::KEY_0; break;
case Qt::Key_1: result = Input::KEY_1; break;
case Qt::Key_2: result = Input::KEY_2; break;
case Qt::Key_3: result = Input::KEY_3; break;
case Qt::Key_4: result = Input::KEY_4; break;
case Qt::Key_5: result = Input::KEY_5; break;
case Qt::Key_6: result = Input::KEY_6; break;
case Qt::Key_7: result = Input::KEY_7; break;
case Qt::Key_8: result = Input::KEY_8; break;
case Qt::Key_9: result = Input::KEY_9; break;
case Qt::Key_Semicolon: result = Input::KEY_SEMICOLON; break;
case Qt::Key_Equal: result = Input::KEY_EQUAL; break;
case Qt::Key_A: result = Input::KEY_A; break;
case Qt::Key_B: result = Input::KEY_B; break;
case Qt::Key_C: result = Input::KEY_C; break;
case Qt::Key_D: result = Input::KEY_D; break;
case Qt::Key_E: result = Input::KEY_E; break;
case Qt::Key_F: result = Input::KEY_F; break;
case Qt::Key_G: result = Input::KEY_G; break;
case Qt::Key_H: result = Input::KEY_H; break;
case Qt::Key_I: result = Input::KEY_I; break;
case Qt::Key_J: result = Input::KEY_J; break;
case Qt::Key_K: result = Input::KEY_K; break;
case Qt::Key_L: result = Input::KEY_L; break;
case Qt::Key_M: result = Input::KEY_M; break;
case Qt::Key_N: result = Input::KEY_N; break;
case Qt::Key_O: result = Input::KEY_O; break;
case Qt::Key_P: result = Input::KEY_P; break;
case Qt::Key_Q: result = Input::KEY_Q; break;
case Qt::Key_R: result = Input::KEY_R; break;
case Qt::Key_S: result = Input::KEY_S; break;
case Qt::Key_T: result = Input::KEY_T; break;
case Qt::Key_U: result = Input::KEY_U; break;
case Qt::Key_V: result = Input::KEY_V; break;
case Qt::Key_W: result = Input::KEY_W; break;
case Qt::Key_X: result = Input::KEY_X; break;
case Qt::Key_Y: result = Input::KEY_Y; break;
case Qt::Key_Z: result = Input::KEY_Z; break;
case Qt::Key_BracketLeft: result = Input::KEY_LEFT_BRACKET; break;
case Qt::Key_Backslash: result = Input::KEY_BACKSLASH; break;
case Qt::Key_BracketRight: result = Input::KEY_RIGHT_BRACKET; break;
case Qt::Key_Agrave: result = Input::KEY_GRAVE_ACCENT; break;
//result = Input::KEY_WORLD_1; break;
//result = Input::KEY_WORLD_2; break;
case Qt::Key_Escape: result = Input::KEY_ESCAPE; break;
case Qt::Key_Enter: result = Input::KEY_ENTER; break;
case Qt::Key_Tab: result = Input::KEY_TAB; break;
case Qt::Key_Backspace: result = Input::KEY_BACKSPACE; break;
case Qt::Key_Insert: result = Input::KEY_INSERT; break;
case Qt::Key_Delete: result = Input::KEY_DELETE; break;
case Qt::Key_Right: result = Input::KEY_RIGHT; break;
case Qt::Key_Left: result = Input::KEY_LEFT; break;
case Qt::Key_Down: result = Input::KEY_DOWN; break;
case Qt::Key_Up: result = Input::KEY_UP; break;
case Qt::Key_PageUp: result = Input::KEY_PAGE_UP; break;
case Qt::Key_PageDown: result = Input::KEY_PAGE_DOWN; break;
case Qt::Key_Home: result = Input::KEY_HOME; break;
case Qt::Key_End: result = Input::KEY_END; break;
case Qt::Key_CapsLock: result = Input::KEY_CAPS_LOCK; break;
case Qt::Key_ScrollLock: result = Input::KEY_SCROLL_LOCK; break;
case Qt::Key_NumLock: result = Input::KEY_NUM_LOCK; break;
//result = Input::KEY_PRINT_SCREEN; break;
case Qt::Key_Pause: result = Input::KEY_PAUSE; break;
case Qt::Key_F1 : result = Input::KEY_F1; break;
case Qt::Key_F2 : result = Input::KEY_F2; break;
case Qt::Key_F3 : result = Input::KEY_F3; break;
case Qt::Key_F4 : result = Input::KEY_F4; break;
case Qt::Key_F5 : result = Input::KEY_F5; break;
case Qt::Key_F6 : result = Input::KEY_F6; break;
case Qt::Key_F7 : result = Input::KEY_F7; break;
case Qt::Key_F8 : result = Input::KEY_F8; break;
case Qt::Key_F9 : result = Input::KEY_F9; break;
case Qt::Key_F10: result = Input::KEY_F10; break;
case Qt::Key_F11: result = Input::KEY_F11; break;
case Qt::Key_F12: result = Input::KEY_F12; break;
case Qt::Key_F13: result = Input::KEY_F13; break;
case Qt::Key_F14: result = Input::KEY_F14; break;
case Qt::Key_F15: result = Input::KEY_F15; break;
case Qt::Key_F16: result = Input::KEY_F16; break;
case Qt::Key_F17: result = Input::KEY_F17; break;
case Qt::Key_F18: result = Input::KEY_F18; break;
case Qt::Key_F19: result = Input::KEY_F19; break;
case Qt::Key_F20: result = Input::KEY_F20; break;
case Qt::Key_F21: result = Input::KEY_F21; break;
case Qt::Key_F22: result = Input::KEY_F22; break;
case Qt::Key_F23: result = Input::KEY_F23; break;
case Qt::Key_F24: result = Input::KEY_F24; break;
case Qt::Key_F25: result = Input::KEY_F25; break;
//result = Input::KEY_KP_0; break;
//result = Input::KEY_KP_1; break;
//result = Input::KEY_KP_2; break;
//result = Input::KEY_KP_3; break;
//result = Input::KEY_KP_4; break;
//result = Input::KEY_KP_5; break;
//result = Input::KEY_KP_6; break;
//result = Input::KEY_KP_7; break;
//result = Input::KEY_KP_8; break;
//result = Input::KEY_KP_9; break;
//result = Input::KEY_KP_DECIMAL; break;
//result = Input::KEY_KP_DIVIDE; break;
//result = Input::KEY_KP_MULTIPLY; break;
//result = Input::KEY_KP_SUBTRACT; break;
//result = Input::KEY_KP_ADD; break;
//result = Input::KEY_KP_ENTER; break;
//result = Input::KEY_KP_EQUAL; break;
case Qt::Key_Shift: result = Input::KEY_LEFT_SHIFT; break;
case Qt::Key_Control: result = Input::KEY_LEFT_CONTROL; break;
case Qt::Key_Alt: result = Input::KEY_LEFT_ALT; break;
case Qt::Key_Super_L: result = Input::KEY_LEFT_SUPER; break;
//result = Input::KEY_RIGHT_SHIFT; break;
//result = Input::KEY_RIGHT_CONTROL; break;
//result = Input::KEY_RIGHT_ALT; break;
case Qt::Key_Super_R: result = Input::KEY_RIGHT_SUPER; break;
case Qt::Key_Menu: result = Input::KEY_MENU; break;
default: break;
}
return result;
}
void SceneView::update() {
m_inputString.clear();
for(auto &it : m_Keys) {
switch(it.second) {
case RELEASE: it.second = NONE; break;
case PRESS: it.second = REPEAT; break;
default: break;
}
}
for(auto &it : m_MouseButtons) {
switch(it.second) {
case RELEASE: it.second = NONE; break;
case PRESS: it.second = REPEAT; break;
default: break;
}
}
}
bool SceneView::key(Input::KeyCode code) {
return (m_Keys[code] > RELEASE);
}
bool SceneView::keyPressed(Input::KeyCode code) {
return (m_Keys[code] == PRESS);
}
bool SceneView::keyReleased(Input::KeyCode code) {
return (m_Keys[code] == RELEASE);
}
string SceneView::inputString() {
return m_inputString;
}
bool SceneView::mouseButton(Input::MouseButton button) {
return (m_MouseButtons[button] > RELEASE);
}
bool SceneView::mousePressed(Input::MouseButton button) {
return (m_MouseButtons[button] == PRESS);
}
bool SceneView::mouseReleased(Input::MouseButton button) {
return (m_MouseButtons[button] == RELEASE);
}
bool SceneView::eventFilter(QObject *object, QEvent *event) {
switch(event->type()) {
case QEvent::KeyPress: {
QKeyEvent *ev = static_cast<QKeyEvent *>(event);
m_Keys[mapToInput(ev->key())] = ev->isAutoRepeat() ? REPEAT : PRESS;
m_inputString += ev->text().toStdString();
return true;
}
case QEvent::KeyRelease: {
QKeyEvent *ev = static_cast<QKeyEvent *>(event);
m_Keys[mapToInput(ev->key())] = RELEASE;
return true;
}
case QEvent::MouseButtonPress: {
QMouseEvent *ev = static_cast<QMouseEvent *>(event);
Input::MouseButton btn = Input::LEFT;
switch(ev->button()) {
case Qt::LeftButton: btn = Input::LEFT; break;
case Qt::RightButton: btn = Input::RIGHT; break;
case Qt::MiddleButton: btn = Input::MIDDLE; break;
case Qt::ExtraButton1: btn = Input::BUTTON0; break;
case Qt::ExtraButton2: btn = Input::BUTTON1; break;
case Qt::ExtraButton3: btn = Input::BUTTON2; break;
case Qt::ExtraButton4: btn = Input::BUTTON3; break;
case Qt::ExtraButton5: btn = Input::BUTTON4; break;
default: break;
}
m_MouseButtons[btn] = PRESS;
return true;
}
case QEvent::MouseButtonRelease: {
QMouseEvent *ev = static_cast<QMouseEvent *>(event);
Input::MouseButton btn = Input::LEFT;
switch(ev->button()) {
case Qt::LeftButton: btn = Input::LEFT; break;
case Qt::RightButton: btn = Input::RIGHT; break;
case Qt::MiddleButton: btn = Input::MIDDLE; break;
case Qt::ExtraButton1: btn = Input::BUTTON0; break;
case Qt::ExtraButton2: btn = Input::BUTTON1; break;
case Qt::ExtraButton3: btn = Input::BUTTON2; break;
case Qt::ExtraButton4: btn = Input::BUTTON3; break;
case Qt::ExtraButton5: btn = Input::BUTTON4; break;
default: break;
}
m_MouseButtons[btn] = RELEASE;
return true;
}
default: break;
}
return QObject::eventFilter(object, event);
}
void SceneView::findCamera() {
Actor *chunk = m_pScene->findChild<Actor *>(false);
if(chunk) {
Camera *camera = chunk->findChild<Camera *>();
if(camera) {
Pipeline *pipe = camera->pipeline();
pipe->resize(width(), height());
}
Camera::setCurrent(camera);
}
}
Vector4 SceneView::mousePosition() {
QPoint p = mapFromGlobal(QCursor::pos());
return Vector4(p.x(),
height() - p.y(),
static_cast<float>(p.x()) / width(),
static_cast<float>(height() - p.y()) / height());
}
Vector4 SceneView::mouseDelta() { return Vector4(); }
void SceneView::setMousePosition(int32_t x, int32_t y) {
QCursor::setPos(mapToGlobal(QPoint(x, y)));
}
uint32_t SceneView::screenWidth() { return width(); }
uint32_t SceneView::screenHeight() { return height(); }
uint32_t SceneView::joystickCount() { return 0; }
uint32_t SceneView::joystickButtons(uint32_t) { return 0; }
Vector4 SceneView::joystickThumbs(uint32_t) { return Vector4(); }
Vector2 SceneView::joystickTriggers(uint32_t) { return Vector2(); }
void *SceneView::pluginLoad(const char *) { return nullptr; }
bool SceneView::pluginUnload(void *) { return false; }
void *SceneView::pluginAddress(void *, const string &) { return nullptr; }
string SceneView::locationLocalDir() { return QStandardPaths::writableLocation(QStandardPaths::ConfigLocation).toStdString(); }
| 37.505917
| 127
| 0.646052
|
thunder-engine
|
6a872ea13d8c17dd490397ba34300338814d7b91
| 3,674
|
cpp
|
C++
|
chapter-3/p-3.3/src/main.cpp
|
ahmedfawzyelaraby/cracking-the-coding-interview
|
82395e711dd3136c0b762ac846f345cad39a4d66
|
[
"MIT"
] | 1
|
2020-06-08T09:40:06.000Z
|
2020-06-08T09:40:06.000Z
|
chapter-3/p-3.3/src/main.cpp
|
ahmedfawzyelaraby/cracking-the-coding-interview
|
82395e711dd3136c0b762ac846f345cad39a4d66
|
[
"MIT"
] | null | null | null |
chapter-3/p-3.3/src/main.cpp
|
ahmedfawzyelaraby/cracking-the-coding-interview
|
82395e711dd3136c0b762ac846f345cad39a4d66
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <memory>
#include <vector>
class StackNode {
public:
StackNode(int input_node_value) {
this->node_value = input_node_value;
this->next_node = NULL;
}
~StackNode() {}
void setNext(std::unique_ptr<StackNode> input_next_node) {
this->next_node = std::move(input_next_node);
}
std::unique_ptr<StackNode> getNext() {
return std::move(this->next_node);
}
int getValue() {
return this->node_value;
}
private:
int node_value;
std::unique_ptr<StackNode> next_node;
};
class MyStack {
public:
MyStack() {}
~MyStack() {}
void push(int node_value) {
std::unique_ptr<StackNode> tmp = std::make_unique<StackNode>(node_value);
if(this->top != nullptr)
tmp->setNext(std::move(top));
this->top = std::move(tmp);
this->stack_size++;
}
int pop() {
if(this->top != nullptr) {
std::unique_ptr<StackNode> tmp = std::move(this->top);
this->top = std::move(tmp->getNext());
this->stack_size--;
return tmp->getValue();
}
}
int peek() {
if(this->top != nullptr) {
return this->top->getValue();
}
}
bool isEmpty() {
return (this->top == nullptr);
}
int size() { return this->stack_size; }
private:
std::unique_ptr<StackNode> top;
int stack_size = 0;
};
class SetOfStacks {
public:
SetOfStacks(int input_max_stack_size) {
this->max_stack_size = input_max_stack_size;
}
~SetOfStacks() {}
void push(int node_value) {
if(this->set_of_stacks.size() <= 0) {
std::unique_ptr<MyStack> new_stack = std::make_unique<MyStack>();
this->set_of_stacks.push_back(std::move(new_stack));
}
if(this->set_of_stacks[this->set_of_stacks.size() - 1]->size() >= this->max_stack_size) {
std::unique_ptr<MyStack> new_stack = std::make_unique<MyStack>();
this->set_of_stacks.push_back(std::move(new_stack));
}
this->set_of_stacks[this->set_of_stacks.size() - 1]->push(node_value);
}
int pop() {
if(this->set_of_stacks.size() > 0) {
return this->set_of_stacks[this->set_of_stacks.size() - 1]->pop();
}
}
int peek() {
if(this->set_of_stacks.size() > 0) {
return this->set_of_stacks[this->set_of_stacks.size() - 1]->peek();
}
}
int isEmpty() {
if(this->set_of_stacks.size() <= 0)
return true;
if(this->set_of_stacks[0]->size() <= 0)
return true;
return false;
}
private:
int max_stack_size;
std::vector<std::unique_ptr<MyStack>> set_of_stacks;
};
int main(int argc, char** argv) {
SetOfStacks stack(2);
std::cout << stack.isEmpty() << std::endl;
std::cout << stack.peek() << std::endl;
std::cout << stack.pop() << std::endl;
stack.push(5);
std::cout << stack.peek() << std::endl;
stack.push(1);
std::cout << stack.peek() << std::endl;
stack.push(7);
std::cout << stack.peek() << std::endl;
stack.push(0);
std::cout << stack.peek() << std::endl;
std::cout << stack.pop() << std::endl;
std::cout << stack.pop() << std::endl;
return 0;
}
| 28.703125
| 101
| 0.510887
|
ahmedfawzyelaraby
|
6a8a295d833ea20ce7c45c1216170ae77c3534df
| 1,257
|
hpp
|
C++
|
include/ShaderAST/Expr/ExprIntrinsicCall.hpp
|
Praetonus/ShaderWriter
|
1c5b3961e3e1b91cb7158406998519853a4add07
|
[
"MIT"
] | null | null | null |
include/ShaderAST/Expr/ExprIntrinsicCall.hpp
|
Praetonus/ShaderWriter
|
1c5b3961e3e1b91cb7158406998519853a4add07
|
[
"MIT"
] | null | null | null |
include/ShaderAST/Expr/ExprIntrinsicCall.hpp
|
Praetonus/ShaderWriter
|
1c5b3961e3e1b91cb7158406998519853a4add07
|
[
"MIT"
] | null | null | null |
/*
See LICENSE file in root folder
*/
#ifndef ___AST_ExprIntrinsicCall_H___
#define ___AST_ExprIntrinsicCall_H___
#pragma once
#include "ExprList.hpp"
#include "EnumIntrinsic.hpp"
#include "IntrinsicCallHelpers.hpp"
namespace ast::expr
{
class IntrinsicCall
: public Expr
{
public:
IntrinsicCall( type::TypePtr type
, Intrinsic intrinsic
, ExprList && argList );
void accept( VisitorPtr vis )override;
inline ExprList const & getArgList()const
{
return m_argList;
}
inline Intrinsic getIntrinsic()const
{
return m_intrinsic;
}
private:
Intrinsic m_intrinsic;
ExprList m_argList;
};
using IntrinsicCallPtr = std::unique_ptr< IntrinsicCall >;
inline IntrinsicCallPtr makeIntrinsicCall( type::TypePtr type
, Intrinsic intrinsic
, ExprList && argList )
{
return std::make_unique< IntrinsicCall >( std::move( type )
, intrinsic
, std::move( argList ) );
}
template< typename ... Params >
inline IntrinsicCallPtr makeIntrinsicCall( type::TypePtr type
, Intrinsic intrinsic
, Params ... args )
{
ExprList argList;
helpers::fillArgsListRec( argList, std::forward< Params >( args )... );
return makeIntrinsicCall( std::move( type )
, intrinsic
, std::move( argList ) );
}
}
#endif
| 19.640625
| 73
| 0.709626
|
Praetonus
|
6a8b39ad0f1515de8a726431430e5022bac90547
| 3,520
|
cc
|
C++
|
src/lib/MeshFEM/FieldSampler.cc
|
MeshFEM/MeshFEM
|
9b3619fa450d83722879bfd0f5a3fe69d927bd63
|
[
"MIT"
] | 19
|
2020-10-21T10:05:17.000Z
|
2022-03-20T13:41:50.000Z
|
src/lib/MeshFEM/FieldSampler.cc
|
MeshFEM/MeshFEM
|
9b3619fa450d83722879bfd0f5a3fe69d927bd63
|
[
"MIT"
] | 4
|
2021-01-01T15:58:15.000Z
|
2021-09-19T03:31:09.000Z
|
src/lib/MeshFEM/FieldSampler.cc
|
MeshFEM/MeshFEM
|
9b3619fa450d83722879bfd0f5a3fe69d927bd63
|
[
"MIT"
] | 4
|
2020-10-05T09:01:50.000Z
|
2022-01-11T03:02:39.000Z
|
#include "FieldSampler.hh"
#include "libigl_aabb/point_simplex_squared_distance.h"
#include "libigl_aabb/AABB.h"
template<size_t N>
struct SamplerAABB : public iglaabb::AABB<Eigen::MatrixXd, int(N)> {
using Base = iglaabb::AABB<Eigen::MatrixXd, int(N)>;
using Base::Base;
};
////////////////////////////////////////////////////////////////////////////////
// Implementation of FieldSamplerImpl<N>'s methods
// (must be in this .cc so that all libigl_aabb includes are quarantined).
////////////////////////////////////////////////////////////////////////////////
template<size_t N>
FieldSamplerImpl<N>::FieldSamplerImpl(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F)
: m_V(V), m_F(F) {
if (F.cols() > 3) throw std::runtime_error("Raw mesh sampler only works on point/edge/triangle soups; use FEMMesh sampler for tet meshes.");
m_samplerAABB = std::make_unique<SamplerAABB<N>>();
m_samplerAABB->init(m_V, m_F);
}
template<size_t N>
void FieldSamplerImpl<N>::m_closestElementAndPointImpl(Eigen::Ref<const Eigen::MatrixXd> P,
Eigen::VectorXd &sq_dists,
Eigen::VectorXi &I,
Eigen::MatrixXd &C) const {
if (P.cols() != m_V.cols()) throw std::runtime_error("Query points of wrong dimension.");
m_samplerAABB->squared_distance(m_V, m_F, P, sq_dists, I, C);
}
template<size_t N>
void FieldSamplerImpl<N>::m_closestElementAndBaryCoordsImpl(Eigen::Ref<const Eigen::MatrixXd> P,
Eigen::VectorXd &sq_dists,
Eigen::VectorXi &I,
Eigen::MatrixXd &B,
Eigen::MatrixXd &C) const {
m_closestElementAndPointImpl(P, sq_dists, I, C);
const size_t np = P.rows();
B.resize(np, m_F.cols());
iglaabb::parallel_for(np, [&B, &I, &C, this](int ii) {
double dist;
Eigen::Matrix<double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, /* MaxCols */ 3> baryCoords(1, m_F.cols());
Eigen::Matrix<double, 1, N> pt;
iglaabb::point_simplex_squared_distance<N>(C.row(ii), m_V, m_F, I[ii], dist, pt, baryCoords);
B.row(ii) = baryCoords;
}, 10000);
}
template<size_t N>
FieldSamplerImpl<N>::~FieldSamplerImpl() { }
////////////////////////////////////////////////////////////////////////////////
// Factory Function Definitions
////////////////////////////////////////////////////////////////////////////////
std::unique_ptr<FieldSampler> ConstructFieldSamplerImpl(Eigen::Ref<const Eigen::MatrixXd> V,
Eigen::Ref<const Eigen::MatrixXi> F) {
if (V.cols() == 3) return std::unique_ptr<FieldSampler>(static_cast<FieldSampler *>(new RawMeshFieldSampler<3>(V, F)));
else if (V.cols() == 2) return std::unique_ptr<FieldSampler>(static_cast<FieldSampler *>(new RawMeshFieldSampler<2>(V, F)));
else throw std::runtime_error("Only 2D and 3D samplers are implemented.");
}
////////////////////////////////////////////////////////////////////////////////
// Explicit Instantiations
////////////////////////////////////////////////////////////////////////////////
template struct MESHFEM_EXPORT FieldSamplerImpl<2>;
template struct MESHFEM_EXPORT FieldSamplerImpl<3>;
| 49.577465
| 144
| 0.513352
|
MeshFEM
|
6a910a6a1ef848094f5380a9b7e404c74f02dc89
| 78
|
cpp
|
C++
|
TrabalhoPOO/HardSkin.cpp
|
mbcrocci/TrabalhoPOO
|
30378382b412e3ed875dbb2bfb897061dafc73ef
|
[
"MIT"
] | null | null | null |
TrabalhoPOO/HardSkin.cpp
|
mbcrocci/TrabalhoPOO
|
30378382b412e3ed875dbb2bfb897061dafc73ef
|
[
"MIT"
] | null | null | null |
TrabalhoPOO/HardSkin.cpp
|
mbcrocci/TrabalhoPOO
|
30378382b412e3ed875dbb2bfb897061dafc73ef
|
[
"MIT"
] | null | null | null |
#include "HardSkin.h"
HardSkin::HardSkin ()
{}
HardSkin::~HardSkin ()
{}
| 7.090909
| 22
| 0.615385
|
mbcrocci
|
6a94376443437cc584b6709d7c8f6bf7e501d7ae
| 1,075
|
cpp
|
C++
|
2016 Long Contest for NSU and KUET - 2 ( BIT episode 1 )/O - Cvjetici.cpp
|
anirudha-ani/NSU-Problem-Solver
|
2f6312fe5823c0352358f5db654dd0e1a619ce75
|
[
"Apache-2.0"
] | null | null | null |
2016 Long Contest for NSU and KUET - 2 ( BIT episode 1 )/O - Cvjetici.cpp
|
anirudha-ani/NSU-Problem-Solver
|
2f6312fe5823c0352358f5db654dd0e1a619ce75
|
[
"Apache-2.0"
] | null | null | null |
2016 Long Contest for NSU and KUET - 2 ( BIT episode 1 )/O - Cvjetici.cpp
|
anirudha-ani/NSU-Problem-Solver
|
2f6312fe5823c0352358f5db654dd0e1a619ce75
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int data[100005];
int flag[100005] = {0};
void update (int index , int value)
{
while(index < 100005)
{
data[index] += value;
index += ((index)& (-index));
}
}
int query(int index)
{
int sum = 0 ;
while(index > 0)
{
sum += data[index];
index -= ((index) & (-index));
}
return sum ;
}
int main()
{
int N , index1 , index2 , answer , query1 , query2;
scanf("%d", &N);
memset(data , 0 , sizeof(data));
for(int i = 0 ; i < N ; i++)
{
scanf("%d %d", &index1 , &index2);
query1 = 0;
query2 = 0;
query1 = (query(index1))-flag[index1];
flag[index1] += query1;
query2 = (query(index2))- flag[index2];
flag[index2] += query2;
answer = (query1 + query2);
printf("%d\n", answer);
update(index1 + 1 , 1);
update(index2 , -1);
}
return 0;
}
| 17.916667
| 56
| 0.469767
|
anirudha-ani
|
6a95c5b25e1fd6fd0e10a612a72b2472515a10e1
| 224
|
cpp
|
C++
|
chap06/Exer06_03.cpp
|
sjbarigye/CPP_Primer
|
d9d31a73a45ca46909bae104804fc9503ab242f2
|
[
"Apache-2.0"
] | 50
|
2016-01-08T14:28:53.000Z
|
2022-01-21T12:55:00.000Z
|
chap06/Exer06_03.cpp
|
sjbarigye/CPP_Primer
|
d9d31a73a45ca46909bae104804fc9503ab242f2
|
[
"Apache-2.0"
] | 2
|
2017-06-05T16:45:20.000Z
|
2021-04-17T13:39:24.000Z
|
chap06/Exer06_03.cpp
|
sjbarigye/CPP_Primer
|
d9d31a73a45ca46909bae104804fc9503ab242f2
|
[
"Apache-2.0"
] | 18
|
2016-08-17T15:23:51.000Z
|
2022-03-26T18:08:43.000Z
|
#include <iostream>
using std::cout;
using std::endl;
int fact(int val)
{
int ret = 1;
while(val > 1)
ret *= val--;
return ret;
}
int main()
{
int j = fact(12);
cout << j << endl;
return 0;
}
| 13.176471
| 22
| 0.517857
|
sjbarigye
|
6a96cab43d06be7a55468f57d9f3a7cad64e8080
| 26,444
|
cpp
|
C++
|
lugre/src/lugre_gfx2D_L.cpp
|
ghoulsblade/vegaogre
|
2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f
|
[
"MIT"
] | 1
|
2020-10-18T14:33:05.000Z
|
2020-10-18T14:33:05.000Z
|
lugre/src/lugre_gfx2D_L.cpp
|
ghoulsblade/vegaogre
|
2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f
|
[
"MIT"
] | null | null | null |
lugre/src/lugre_gfx2D_L.cpp
|
ghoulsblade/vegaogre
|
2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f
|
[
"MIT"
] | null | null | null |
#include "lugre_prefix.h"
#include "lugre_scripting.h"
#include "lugre_luabind.h"
#include "lugre_gfx2D.h"
#include "lugre_BorderColourClipPaneOverlay.h"
#include "lugre_CompassOverlay.h"
#include "lugre_RobRenderableOverlay.h"
#include "lugre_SortedOverlayContainer.h"
#include "lugre_gfx3D.h"
#include "lugre_ogrewrapper.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#define kCursorOverlayZOrder 640
namespace Lugre {
class cGfx2D_L : public cLuaBind<cGfx2D> { public:
/// called by Register(), registers object-methods (see cLuaBind constructor for examples)
virtual void RegisterMethods (lua_State *L) { PROFILE
// mlMethod.push_back((struct luaL_reg){"Meemba", cGfx_L::Get});
// lua_register(L,"MyGlobalFun", MyGlobalFun);
// lua_register(L,"MyStaticMethod", &cSomeClass::MyStaticMethod);
lua_register(L,"CreateGfx2D", &cGfx2D_L::CreateGfx2D);
lua_register(L,"CreateCursorGfx2D", &cGfx2D_L::CreateCursorGfx2D);
lua_register(L,"GetGfx2DCount", &cGfx2D_L::GetGfx2DCount);
#define REGISTER_METHOD(methodname) mlMethod.push_back(make_luaL_reg(#methodname,&cGfx2D_L::methodname));
REGISTER_METHOD(Destroy);
REGISTER_METHOD(InitCompass);
REGISTER_METHOD(InitPanel);
REGISTER_METHOD(InitCCPO);
REGISTER_METHOD(InitCCTO);
REGISTER_METHOD(InitBCCPO);
REGISTER_METHOD(InitSOC);
REGISTER_METHOD(InitRROC);
REGISTER_METHOD(InitText);
REGISTER_METHOD(SetPrepareFrameStep);
REGISTER_METHOD(SetTransparent);
REGISTER_METHOD(SetVisible);
REGISTER_METHOD(GetVisible);
REGISTER_METHOD(SetMaterial);
REGISTER_METHOD(SetBorderMaterial);
REGISTER_METHOD(SetPos);
REGISTER_METHOD(GetPos);
REGISTER_METHOD(SetDimensions);
REGISTER_METHOD(GetDimensions);
REGISTER_METHOD(SetTextAlignment);
REGISTER_METHOD(SetAlignment);
REGISTER_METHOD(SetUV);
REGISTER_METHOD(SetPartUV);
REGISTER_METHOD(SetClip);
REGISTER_METHOD(SetBorder);
REGISTER_METHOD(SetCharHeight);
REGISTER_METHOD(SetFont);
REGISTER_METHOD(SetText);
REGISTER_METHOD(SetAutoWrap);
REGISTER_METHOD(SetColour);
REGISTER_METHOD(SetColours);
REGISTER_METHOD(SetPartColours);
REGISTER_METHOD(SetRotate);
REGISTER_METHOD(GetTextBounds);
REGISTER_METHOD(GetGlyphAtPos);
REGISTER_METHOD(GetGlyphBounds);
REGISTER_METHOD(SetUVMid);
REGISTER_METHOD(SetUVRad);
REGISTER_METHOD(SetAngBias);
REGISTER_METHOD(SetRankFactor);
REGISTER_METHOD(SetTrackPosSceneNode);
REGISTER_METHOD(SetTrackOffset);
REGISTER_METHOD(SetTrackMouse);
REGISTER_METHOD(GetLeft);
REGISTER_METHOD(GetTop);
REGISTER_METHOD(GetDerivedLeft);
REGISTER_METHOD(GetDerivedTop);
REGISTER_METHOD(GetWidth);
REGISTER_METHOD(GetHeight);
REGISTER_METHOD(RenderableBegin);
REGISTER_METHOD(RenderableVertex);
REGISTER_METHOD(RenderableIndex);
REGISTER_METHOD(RenderableIndex3);
REGISTER_METHOD(RenderableEnd);
REGISTER_METHOD(RenderableSkipVertices);
REGISTER_METHOD(RenderableSkipIndices);
REGISTER_METHOD(SOC_ChildBringToFront);
REGISTER_METHOD(SOC_ChildSendToBack);
REGISTER_METHOD(SOC_ChildInsertAfter);
REGISTER_METHOD(SOC_ChildInsertBefore);
// synced with include/gfx2D.h
#define RegisterClassConstant(name) cScripting::SetGlobal(L,#name,cGfx2D::name)
RegisterClassConstant(kGfx2DAlign_Left);
RegisterClassConstant(kGfx2DAlign_Top);
RegisterClassConstant(kGfx2DAlign_Right);
RegisterClassConstant(kGfx2DAlign_Bottom);
RegisterClassConstant(kGfx2DAlign_Center);
#undef RegisterClassConstant
#define RegisterClassConstant(name) cScripting::SetGlobal(L,#name,cBorderColourClipPaneOverlay::name)
RegisterClassConstant(kBCCPOPart_LT);
RegisterClassConstant(kBCCPOPart_T);
RegisterClassConstant(kBCCPOPart_RT);
RegisterClassConstant(kBCCPOPart_L);
RegisterClassConstant(kBCCPOPart_R);
RegisterClassConstant(kBCCPOPart_LB);
RegisterClassConstant(kBCCPOPart_B);
RegisterClassConstant(kBCCPOPart_RB);
RegisterClassConstant(kBCCPOPart_M);
}
/// called by Register(), registers object-member-vars (see cLuaBind::RegisterMembers() for examples)
virtual void RegisterMembers () { PROFILE
cGfx2D* prototype = new cGfx2D(); // memory leak : never deleted, but better than side effects
cMemberVar_REGISTER(prototype, kVarType_Vector2, mvTrackPosOffset, 0);
cMemberVar_REGISTER(prototype, kVarType_Vector2, mvTrackPosTargetSizeFactor, 0);
cMemberVar_REGISTER(prototype, kVarType_Vector2, mvTrackPosOwnSizeFactor, 0);
cMemberVar_REGISTER(prototype, kVarType_Vector2, mvTrackClampMin, 0);
cMemberVar_REGISTER(prototype, kVarType_Vector2, mvTrackClampMax, 0);
cMemberVar_REGISTER(prototype, kVarType_Vector2, mvTrackSetSizeFactor, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackClamp, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackHideIfClamped, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackHideIfBehindCam, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackClampMaxXIfBehindCam, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackClampMaxYIfBehindCam, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackSetSize, 0);
cMemberVar_REGISTER(prototype, kVarType_bool, mbTrackMouse, 0);
}
/// static methods exported to lua
/// returns the number of gfx3d objects that are currently allocated
static int GetGfx2DCount (lua_State *L) { PROFILE
lua_pushnumber(L,cGfx2D::miCount);
return 1;
}
/// for lua : gfx2d CreateGfx2D ()
static int CreateGfx2D (lua_State *L) { PROFILE
cGfx2D* target = new cGfx2D();
return CreateUData(L,target);
}
/// creates a gfx2d on kCursorOverlayZOrder, typically used for mouse cursors
/// for lua : gfx2d CreateCursorGfx2D ()
static int CreateCursorGfx2D (lua_State *L) { PROFILE
Ogre::Overlay* pCursorOverlay = cGfx2D::CreateOverlay(cGfx2D::GetUniqueName().c_str(),kCursorOverlayZOrder);
cGfx2D* target = new cGfx2D(pCursorOverlay);
return CreateUData(L,target);
}
/// for lua : void Destroy ()
static int Destroy (lua_State *L) { PROFILE
//printf("cGfx2D_L::Destroy start\n");
delete checkudata_alive(L);
//printf("cGfx2D_L::Destroy end\n");
return 0;
}
/// see also InitCCPO : ColorClipPaneOverlay
/// for lua : void InitPanel (gfx2d_parent=0)
static int InitPanel (lua_State *L) { PROFILE /*(cGfx2D* pParent=0); */
checkudata_alive(L)->InitPanel((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// iris specific compass widget, TODO : remove me ? might need plugin system or redesign
/// for lua : void InitCompass (gfx2d_parent=0)
static int InitCompass (lua_State *L) { PROFILE /*(cGfx2D* pParent=0); */
checkudata_alive(L)->InitCompass((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// ColorClipPaneOverlay
/// for lua : void InitCCPO (gfx2d_parent=0)
static int InitCCPO (lua_State *L) { PROFILE /*(cGfx2D* pParent=0); */
checkudata_alive(L)->InitCCPO((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// ColorClipTextOverlay
/// for lua : void InitCCTO (gfx2d_parent=0)
static int InitCCTO (lua_State *L) { PROFILE /*(cGfx2D* pParent=0); */
checkudata_alive(L)->InitCCTO((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// BorderColorClipPaneOverlay
/// for lua : void InitBCCPO (gfx2d_parent=0)
static int InitBCCPO (lua_State *L) { PROFILE /*(cGfx2D* pParent=0); */
checkudata_alive(L)->InitBCCPO((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// SortedOverlayContainer
/// for lua : void InitSOC (gfx2d_parent=0)
static int InitSOC (lua_State *L) { PROFILE
checkudata_alive(L)->InitSOC((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// RobRenderableOverlayContainer
/// for lua : void InitRROC (gfx2d_parent=0)
static int InitRROC (lua_State *L) { PROFILE
checkudata_alive(L)->InitRROC((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// Text Overlay ( see also ColorClipTextOverlay above )
/// for lua : void InitText (gfx2d_parent=0)
static int InitText (lua_State *L) { PROFILE
checkudata_alive(L)->InitText((lua_gettop(L) > 1 && !lua_isnil(L,2))?checkudata_alive(L,2):0);
return 0;
}
/// if true, a framestep method is called every frame, used for calculating position and similar
/// for lua : void SetPrepareFrameStep (bActive)
static int SetPrepareFrameStep (lua_State *L) { PROFILE
checkudata_alive(L)->SetPrepareFrameStep(lua_isboolean(L,2) ? lua_toboolean(L,2) : luaL_checkint(L,2));
return 0;
}
/// TODO : find out and document if this affects children as well (e.g. if you set a container visible=false, are the childs hidden)
/// see also SetTransparent
/// for lua : void SetVisible (bVis)
static int SetVisible (lua_State *L) { PROFILE /*(const bool bVisible); */
checkudata_alive(L)->SetVisible(lua_isboolean(L,2) ? lua_toboolean(L,2) : luaL_checkint(L,2));
return 0;
}
/// for overlays
/// prevents drawing, similar to SetVisible, TODO : detailed description and look up what this does exactly, i think it prevents drawing of container background but not of the childs
/// see also SetVisible
/// for lua : void SetTransparent (bTransparent)
static int SetTransparent (lua_State *L) { PROFILE /*(const bool bVisible); */
cColourClipPaneOverlay* pCCPO = checkudata_alive(L)->mpCCPO;
if (pCCPO) pCCPO->setTransparent(lua_isboolean(L,2) ? lua_toboolean(L,2) : luaL_checkint(L,2));
return 0;
}
/// for lua : bool GetVisible ()
static int GetVisible (lua_State *L) { PROFILE /*(const bool bVisible); */
lua_pushboolean(L,checkudata_alive(L)->GetVisible());
return 1;
}
/// sets material (inner for BorderColorClipPaneOverlay)
/// for lua : void SetMaterial (sMatName);
static int SetMaterial (lua_State *L) { PROFILE /*(const char* szMat); */
checkudata_alive(L)->SetMaterial(luaL_checkstring(L, 2));
return 0;
}
/// for BorderColorClipPaneOverlay, sets the material of the border
/// for lua : void SetBorderMaterial(sMatName)
static int SetBorderMaterial (lua_State *L) { PROFILE
checkudata_alive(L)->SetBorderMaterial(luaL_checkstring(L, 2));
return 0;
}
/// position
/// for lua : void SetPos(x,y)
static int SetPos (lua_State *L) { PROFILE
checkudata_alive(L)->SetPos(luaL_checknumber(L, 2),luaL_checknumber(L, 3));
return 0;
}
/// position
/// for lua : x,y GetPos ()
static int GetPos (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetLeft());
lua_pushnumber(L,checkudata_alive(L)->GetTop());
return 2;
}
/// size
/// for lua : void SetDimensions (w,h)
static int SetDimensions (lua_State *L) { PROFILE
checkudata_alive(L)->SetDimensions(luaL_checknumber(L, 2),luaL_checknumber(L, 3));
return 0;
}
/// for lua : w,h = GetDimensions ()
static int GetDimensions (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetWidth());
lua_pushnumber(L,checkudata_alive(L)->GetHeight());
return 2;
}
/// for lua : void SetAlignment (iHAlign,iVAlign)
/// iHAlign : kGfx2DAlign_Left , kGfx2DAlign_Right , kGfx2DAlign_Center
/// iVAlign : kGfx2DAlign_Top , kGfx2DAlign_Bottom , kGfx2DAlign_Center
static int SetAlignment (lua_State *L) { PROFILE
checkudata_alive(L)->SetAlignment(luaL_checkint(L, 2),luaL_checkint(L, 3));
return 0;
}
/// iHAlign : kGfx2DAlign_Left , kGfx2DAlign_Right , kGfx2DAlign_Center
/// for lua : void SetTextAlignment(iTextAlign)
static int SetTextAlignment (lua_State *L) { PROFILE
checkudata_alive(L)->SetTextAlignment(luaL_checkint(L, 2));
return 0;
}
/// for lua : void SetUV (float u1, float v1, float u2, float v2)
/// left,top = u1,u2 right,bottom = u2,v2
static int SetUV (lua_State *L) { PROFILE
checkudata_alive(L)->SetUV(luaL_checknumber(L, 2),luaL_checknumber(L, 3),luaL_checknumber(L, 4),luaL_checknumber(L, 5));
return 0;
}
/// for lua : void SetPartUV (int iPartID,float u1, float v1, float u2, float v2)
/// left,top = u1,u2 right,bottom = u2,v2 texturecoordinates
/// iPartID = kBCCPOPart_LT T RT L R LB B RB M : L=Left T=Top R=Right B=Bottom M=Middle
static int SetPartUV (lua_State *L) { PROFILE
checkudata_alive(L)->SetPartUV(luaL_checkint(L, 2),luaL_checknumber(L, 3),luaL_checknumber(L, 4),luaL_checknumber(L, 5),luaL_checknumber(L, 6));
return 0;
}
/// for lua : void SetClip (float left,float top,float width,float height)
/// ColorClipPaneOverlay ColorClipPaneOverlay ColorClipTextOverlay
/// warning : this function is rather lowlevel and requires absolute coordinates, so you have to update the widget during movement or so
static int SetClip (lua_State *L) { PROFILE
checkudata_alive(L)->SetClip(luaL_checknumber(L, 2),luaL_checknumber(L, 3),luaL_checknumber(L, 4),luaL_checknumber(L, 5));
return 0;
}
/// for lua : void SetBorder (float left,float top,float right,float bottom)
/// for BorderColourClipPaneOverlay (the "width" of the border parts on left,top,right,bottom)
static int SetBorder (lua_State *L) { PROFILE
checkudata_alive(L)->SetBorder(luaL_checknumber(L, 2),luaL_checknumber(L, 3),luaL_checknumber(L, 4),luaL_checknumber(L, 5));
return 0;
}
/// for lua : void SetCharHeight (float height)
/// set font-size for text (InitText) and ColorClipTextOverlay (InitCCTO)
/// the height in pixels of a char (todo:sure about pixels? might also be in some screen-relative format..)
static int SetCharHeight (lua_State *L) { PROFILE /*(float fHeight); */
checkudata_alive(L)->SetCharHeight(luaL_checknumber(L, 2));
return 0;
}
/// for text (InitText) and ColorClipTextOverlay (InitCCTO)
/// set font for text (InitText) and ColorClipTextOverlay (InitCCTO)
/// for lua : void SetFont (sFontName)
static int SetFont (lua_State *L) { PROFILE /*(const char* szFont); */
checkudata_alive(L)->SetFont(luaL_checkstring(L, 2));
return 0;
}
/// for text (InitText) and ColorClipTextOverlay (InitCCTO)
/// uses mpOverlayElement->setCaption, so it might work on other types as well automatically later
/// (we currently only have those two)
/// for lua : void SetText (sText)
static int SetText (lua_State *L) { PROFILE /*(const char* szText); */
checkudata_alive(L)->SetText(luaL_checkstring(L, 2));
return 0;
}
/// for lua : void SetAutoWrap (iMaxW) -- usually in pixels
/// text is wrapped automatically if it is too long : newlines are inserted on word boundaries.
static int SetAutoWrap (lua_State *L) { PROFILE
checkudata_alive(L)->SetAutoWrap(luaL_checkint(L, 2));
return 0;
}
/// for lua : void SetColour (r,g,b,a)
/// for ColorClipPaneOverlay, BorderColorClipPaneOverlay(same color for all edges), and ColorClipTextOverlay
/// uses mpOverlayElement->setColour , so it might work automatically for future widgets
static int SetColour (lua_State *L) { PROFILE
checkudata_alive(L)->SetColour(luaSFZ_checkColour4(L, 2));
return 0;
}
/// lt:left top , rb:right bottom
/// for lua : void SetColours ((lt:)r,g,b,a, (rt:)r,g,b,a, (lb:)r,g,b,a, (rb:)r,g,b,a)
static int SetColours (lua_State *L) { PROFILE
checkudata_alive(L)->SetColours(luaSFZ_checkColour4(L,2),luaSFZ_checkColour4(L,6),luaSFZ_checkColour4(L,10),luaSFZ_checkColour4(L,14));
return 0;
}
/// lt:left top , rb:right bottom
/// for lua : void SetPartColours (iPartID, (lt:)r,g,b,a, (rt:)r,g,b,a, (lb:)r,g,b,a, (rb:)r,g,b,a)
/// iPartID = kBCCPOPart_LT T RT L R LB B RB M : L=Left T=Top R=Right B=Bottom M=Middle
static int SetPartColours (lua_State *L) { PROFILE
checkudata_alive(L)->SetPartColours(luaL_checkint(L, 2),luaSFZ_checkColour4(L,3),luaSFZ_checkColour4(L,7),luaSFZ_checkColour4(L,11),luaSFZ_checkColour4(L,15));
return 0;
}
/// obsolete, doesn't do anything now
/// for lua : void SetRotate (angle)
static int SetRotate (lua_State *L) { PROFILE /*(float radians); */
checkudata_alive(L)->SetRotate(luaL_checknumber(L, 2));
return 0;
}
/// only for cColourClipTextOverlay
/// for lua : w,h GetTextBounds ()
static int GetTextBounds (lua_State *L) { PROFILE
Ogre::Real w,h;
checkudata_alive(L)->GetTextBounds(w,h);
lua_pushnumber(L,w);
lua_pushnumber(L,h);
return 2;
}
/// only for cColourClipTextOverlay
/// GlyphIndex at position, if this returns 1234, then the "letter" displayed at the position was text[1234]
/// for lua : int GetGlyphAtPos (x,y)
static int GetGlyphAtPos (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetGlyphAtPos(luaL_checkint(L, 2),luaL_checkint(L, 3)));
return 1;
}
/// only for cColourClipTextOverlay
/// for lua : l,t,r,b GetGlyphBounds(iGlyphIndex)
/// GlyphIndex is for example the index returned from GetGlyphAtPos
static int GetGlyphBounds (lua_State *L) { PROFILE
Ogre::Real l,t,r,b;
checkudata_alive(L)->GetGlyphBounds(luaL_checkint(L, 2),l,t,r,b);
lua_pushnumber(L,l);
lua_pushnumber(L,t);
lua_pushnumber(L,r);
lua_pushnumber(L,b);
return 4;
}
/// for lua : float GetLeft ()
/// in coordinates relative to the parent coordinate system
static int GetLeft (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetLeft());
return 1;
}
/// for lua : float GetTop ()
/// in coordinates relative to the parent coordinate system
static int GetTop (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetTop());
return 1;
}
/// for lua : float GetDerivedLeft ()
/// in absolute coordinates (todo : is this pixels or in screen-relative [-1;1]?)
static int GetDerivedLeft (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetDerivedLeft());
return 1;
}
/// for lua : float GetDerivedTop ()
/// in absolute coordinates (todo : is this pixels or in screen-relative [-1;1]?)
static int GetDerivedTop (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetDerivedTop());
return 1;
}
/// for lua : float GetWidth ()
/// (todo : is this pixels or in screen-relative [-1;1]?)
static int GetWidth (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetWidth());
return 1;
}
/// for lua : float GetHeight ()
/// (todo : is this pixels or in screen-relative [-1;1]?)
static int GetHeight (lua_State *L) { PROFILE
lua_pushnumber(L,checkudata_alive(L)->GetHeight());
return 1;
}
/// for lua : void RenderableBegin (iVertexCount,iIndexCount,bDynamic,bKeepOldIndices,opType)
/// optype like OT_TRIANGLE_LIST
static int RenderableBegin (lua_State *L) { PROFILE
// void Begin (size_t iVertexCount,size_t iIndexCount,bool bDynamic,bool bKeepOldIndices,RenderOperation::OperationType opType);
checkudata_alive(L)->mpRROC->Begin(
luaL_checkint(L,2),
luaL_checkint(L,3),
lua_isboolean(L,4) ? lua_toboolean(L,4) : luaL_checkint(L,4),
lua_isboolean(L,5) ? lua_toboolean(L,5) : luaL_checkint(L,5),
(Ogre::RenderOperation::OperationType)luaL_checkint(L,6)
);
return 0;
}
/// must be called between RenderableBegin and RenderableEnd
/// Real : 1 float
/// Vector3 : 3 floats x,y,z
/// ColourValue : 4 floats r,g,b,a
/// void RenderableVertex (float,float,float,...);
/// void RenderableVertex (...)
static int RenderableVertex (lua_State *L) { PROFILE
cRobRenderOp* pRobRenderOp = checkudata_alive(L)->mpRROC;
if (!pRobRenderOp) return 0;
#define F(i) luaL_checknumber(L,i)
#define V(i) Vector3(F(i+0),F(i+1),F(i+2))
#define C(i) ColourValue(F(i+0),F(i+1),F(i+2),F(i+3))
Ogre::Vector3 p(F(2),F(3),F(4));
int argc = lua_gettop(L) - 1; // arguments, not counting "this"-object
switch (argc) {
case 3: pRobRenderOp->Vertex(p); // x,y,z
break;case 5: pRobRenderOp->Vertex(p,F(5),F(6)); // x,y,z,u,v
break;case 6: pRobRenderOp->Vertex(p,V(5)); // x,y,z,nx,ny,nz
break;case 8: pRobRenderOp->Vertex(p,V(5),F(8),F(9)); // x,y,z,nx,ny,nz,u,v
break;case 7: pRobRenderOp->Vertex(p,C(5)); // x,y,z, r,g,b,a
break;case 9: pRobRenderOp->Vertex(p,F(5),F(6),C(7)); // x,y,z,u,v, r,g,b,a
break;case 10: pRobRenderOp->Vertex(p,V(5),C(8)); // x,y,z,nx,ny,nz, r,g,b,a
break;case 12: pRobRenderOp->Vertex(p,V(5),F(8),F(9),C(10));// x,y,z,nx,ny,nz,u,v, r,g,b,a
break;default: printf("WARNING ! cGfx3D_L::RenderableVertex : strange argument count : %d\n",argc);
}
return 0;
}
/// must be called between RenderableBegin and RenderableEnd
/// void RenderableIndex (iIndex)
static int RenderableIndex (lua_State *L) { PROFILE
checkudata_alive(L)->mpRROC->Index(luaL_checkint(L,2));
return 0;
}
/// must be called between RenderableBegin and RenderableEnd
/// void RenderableIndex3 (iIndex,iIndex,iIndex)
static int RenderableIndex3 (lua_State *L) { PROFILE
checkudata_alive(L)->mpRROC->Index(luaL_checkint(L,2));
checkudata_alive(L)->mpRROC->Index(luaL_checkint(L,3));
checkudata_alive(L)->mpRROC->Index(luaL_checkint(L,4));
return 0;
}
/// void RenderableSkipVertices (int iNumberOfVerticesToSkip)
static int RenderableSkipVertices (lua_State *L) { PROFILE
checkudata_alive(L)->mpRROC->SkipVertices(luaL_checkint(L,2));
return 0;
}
/// void RenderableSkipIndices (int iNumberOfVerticesToSkip)
static int RenderableSkipIndices (lua_State *L) { PROFILE
checkudata_alive(L)->mpRROC->SkipIndices(luaL_checkint(L,2));
return 0;
}
/// void RenderableEnd ()
static int RenderableEnd (lua_State *L) { PROFILE
checkudata_alive(L)->mpRROC->End();
return 0;
}
/// ***** ***** ***** ***** ***** SortedOverlayContainer
/// void SOC_ChildBringToFront (gfx2d_child)
static int SOC_ChildBringToFront (lua_State *L) { PROFILE
cSortedOverlayContainer* pSOC = checkudata_alive(L)->mpSOC;
Ogre::OverlayElement* pChild = checkudata_alive(L,2)->mpOverlayElement;
if (pSOC && pChild) pSOC->ChildBringToFront(pChild);
return 0;
}
/// void SOC_ChildSendToBack (gfx2d_child)
static int SOC_ChildSendToBack (lua_State *L) { PROFILE
cSortedOverlayContainer* pSOC = checkudata_alive(L)->mpSOC;
Ogre::OverlayElement* pChild = checkudata_alive(L,2)->mpOverlayElement;
if (pSOC && pChild) pSOC->ChildSendToBack(pChild);
return 0;
}
/// void SOC_ChildInsertAfter (gfx2d_child,gfx2d_other)
static int SOC_ChildInsertAfter (lua_State *L) { PROFILE
cSortedOverlayContainer* pSOC = checkudata_alive(L)->mpSOC;
Ogre::OverlayElement* pChild = checkudata_alive(L,2)->mpOverlayElement;
Ogre::OverlayElement* pOther = checkudata_alive(L,3)->mpOverlayElement;
if (pSOC && pChild && pOther) pSOC->ChildInsertAfter(pChild,pOther);
return 0;
}
/// void SOC_ChildInsertBefore (gfx2d_child,gfx2d_other)
static int SOC_ChildInsertBefore (lua_State *L) { PROFILE
cSortedOverlayContainer* pSOC = checkudata_alive(L)->mpSOC;
Ogre::OverlayElement* pChild = checkudata_alive(L,2)->mpOverlayElement;
Ogre::OverlayElement* pOther = checkudata_alive(L,3)->mpOverlayElement;
if (pSOC && pChild && pOther) pSOC->ChildInsertBefore(pChild,pOther);
return 0;
}
/// ***** ***** ***** ***** ***** rest
/// only for cCompassOverlay
/// for lua : void SetUVMid (u,v)
static int SetUVMid (lua_State *L) { PROFILE
cCompassOverlay* pCompass = checkudata_alive(L)->mpCompass;
if (pCompass) pCompass->SetUVMid(luaL_checknumber(L,2),luaL_checknumber(L,3));
return 0;
}
/// only for cCompassOverlay
/// for lua : void SetUVRad (u,v)
static int SetUVRad (lua_State *L) { PROFILE
cCompassOverlay* pCompass = checkudata_alive(L)->mpCompass;
if (pCompass) pCompass->SetUVRad(luaL_checknumber(L,2),luaL_checknumber(L,3));
return 0;
}
/// only for cCompassOverlay
/// for lua : void SetAngBias (ang)
/// rotation ?
static int SetAngBias (lua_State *L) { PROFILE
cCompassOverlay* pCompass = checkudata_alive(L)->mpCompass;
if (pCompass) pCompass->SetAngBias(luaL_checknumber(L,2));
return 0;
}
/// only for cSortedOverlayContainer
/// for lua : void SetRankFactor (int iRankFaktor)
/// lowlevel access to a parameter used for a workaround for the ogre-overlay systems limitation of 650 overlay z orders
static int SetRankFactor (lua_State *L) { PROFILE
cSortedOverlayContainer* pSortedContainer = checkudata_alive(L)->mpSOC;
if (pSortedContainer) pSortedContainer->SetRankFactor(luaL_checkint(L,2));
return 0;
}
/// for lua : void SetTrackPosSceneNode(gfx3d or nil)
/// set own pos to the projected(3d to 2d) position of a scenenode
static int SetTrackPosSceneNode (lua_State *L) { PROFILE
cGfx3D* target = (lua_gettop(L) > 1 && !lua_isnil(L,2))?cLuaBind<cGfx3D>::checkudata_alive(L,2):0;
checkudata_alive(L)->mpTrackPosTarget = target;
if (target) checkudata_alive(L)->SetPrepareFrameStep(true);
return 0;
}
/// for lua : void SetTrackOffset(float x,float y)
/// specifies a position offset to be applied when tracking, see also SetTrackMouse SetTrackPosSceneNode
static int SetTrackOffset (lua_State *L) { PROFILE /*(const bool bVisible); */
checkudata_alive(L)->mvTrackPosOffset.x = luaL_checknumber(L,2);
checkudata_alive(L)->mvTrackPosOffset.y = luaL_checknumber(L,3);
return 0;
}
/// for lua : void SetTrackMouse(bool bOn)
/// sets the pos to the mousepos every frame
/// (you should call SetPrepareFrameStep(false) manually if you turn this off and nothing else requires stepping)
static int SetTrackMouse (lua_State *L) { PROFILE /*(const bool bVisible); */
bool bOn = (lua_isboolean(L,2) ? lua_toboolean(L,2) : luaL_checkint(L,2));
checkudata_alive(L)->mbTrackMouse = bOn;
if (bOn) checkudata_alive(L)->SetPrepareFrameStep(true);
return 0;
}
virtual const char* GetLuaTypeName () { return "lugre.gfx2D"; }
};
/// lua binding
void cGfx2D::LuaRegister (lua_State *L) { PROFILE
cLuaBind<cGfx2D>::GetSingletonPtr(new cGfx2D_L())->LuaRegister(L);
}
};
| 39.35119
| 184
| 0.70568
|
ghoulsblade
|
6a9bdb256c9ecc5b41ab9cc515e3752e2964d59d
| 776
|
cpp
|
C++
|
work05/2.cpp
|
kashapovd/basic_prog_1semester
|
0c45a564f50b668e37d7ff0717e18f68e79ab200
|
[
"Unlicense"
] | 1
|
2019-12-08T07:21:45.000Z
|
2019-12-08T07:21:45.000Z
|
work05/2.cpp
|
kashapovd/basic_prog_1semester
|
0c45a564f50b668e37d7ff0717e18f68e79ab200
|
[
"Unlicense"
] | null | null | null |
work05/2.cpp
|
kashapovd/basic_prog_1semester
|
0c45a564f50b668e37d7ff0717e18f68e79ab200
|
[
"Unlicense"
] | null | null | null |
/*
* 4. Для заданного натурального числа N вывести в столбик все простые числа меньшие N.
* Простое число – это натуральное число, имеющее ровно два различных натуральных делителя,
* то есть простое число делится нацело только на самого себя и единицу. Является ли число простым оформить как функцию
*/
#include <iostream>
using namespace std;
int main() {
int N, simple_test(int i);
cout << "N = ";
cin >> N;
int i = 2;
cout << "Простые числа, меньшие " << N << ": ";
while(i < N) {
if(simple_test(i)) {
cout << i << " ";
}
i++;
}
cout << "\n";
}
int simple_test(int i) {
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
return false;
}
}
return true;
}
| 22.171429
| 119
| 0.546392
|
kashapovd
|
6a9d75980af87db53e8b2b43004e63f87c6dbb6e
| 805
|
cpp
|
C++
|
source/omni/ui/blueprint.cpp
|
daniel-kun/omni
|
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
|
[
"MIT"
] | 33
|
2015-03-21T04:12:45.000Z
|
2021-04-18T21:44:33.000Z
|
source/omni/ui/blueprint.cpp
|
daniel-kun/omni
|
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
|
[
"MIT"
] | null | null | null |
source/omni/ui/blueprint.cpp
|
daniel-kun/omni
|
ec9e0a2688677f53c3b4aa3b68f4f788a81e8a18
|
[
"MIT"
] | 2
|
2016-03-05T12:57:05.000Z
|
2017-09-12T10:11:52.000Z
|
#include <omni/ui/blueprint.hpp>
#include <QPainter>
omni::ui::blueprint::blueprint (QWidget * parent) :
QWidget (parent)
{
setAutoFillBackground (true);
QPalette pal;
pal.setColor (QPalette::Background, QColor::fromRgb (0xFF, 0xFF, 0xFF));
// pal.setColor (QPalette::Background, QColor::fromRgb (0x64, 0xA7, 0xC1));
setPalette (pal);
}
void omni::ui::blueprint::paintEvent (QPaintEvent *)
{
return;
QPainter painter (this);
painter.setPen (QColor::fromRgb (0xE3, 0xE3, 0xE5));
int w = width ();
int h = height ();
const int hstep = 20;
const int vstep = 20;
for (int x = 0; x <= w; x += hstep) {
for (int y = 0; y <= h; y += vstep) {
painter.drawLine (0, y, w, y);
painter.drawLine (x, 0 ,x, h);
}
}
}
| 25.967742
| 78
| 0.582609
|
daniel-kun
|
6aa2a636762ed664fce5e15f6b02744cce920e23
| 8,480
|
cpp
|
C++
|
src/Graphics/World.cpp
|
boudra/darkmatter
|
807ef3dc0d10e3ddff75fb4cf965acfa86423624
|
[
"MIT"
] | 7
|
2015-07-29T15:04:56.000Z
|
2021-07-23T13:59:30.000Z
|
src/Graphics/World.cpp
|
boudra/darkmatter
|
807ef3dc0d10e3ddff75fb4cf965acfa86423624
|
[
"MIT"
] | null | null | null |
src/Graphics/World.cpp
|
boudra/darkmatter
|
807ef3dc0d10e3ddff75fb4cf965acfa86423624
|
[
"MIT"
] | 1
|
2015-08-27T14:31:22.000Z
|
2015-08-27T14:31:22.000Z
|
#include "Graphics/World.hpp"
#include "Core/EntityManager.hpp"
#include "Animation/Animation.hpp"
#include "Core/Engine.hpp"
#include "Components/PhysicsComponent.hpp"
#include "Components/Cursor.hpp"
#include "Graphics/RenderSystem.hpp"
#include "Resource/ResourceManager.hpp"
#include <GL/glew.h>
#ifdef _WIN32
#include <GL/wglew.h>
#endif
#include <cstring>
#include <unordered_map>
namespace dm {
void unlock_body(Entity* e) { e->component<BodyComponent>().lock = false; }
bool World::move(BodyComponent& body, int x, int y) {
if (!m_map(body.position.x + x, body.position.y + y).free) {
return false;
}
this->set_position(body, body.position.x + x, body.position.y + y);
return true;
}
void World::component_added(const uint32_t component_type, Entity e) {
// e.component<BodyComponent>().execute(Command::Type::GO_TO, Vec2i
// {20,20});
}
void World::set_position(BodyComponent& body, int x, int y) {
if (!body.ghost) {
Tile& last_position = m_map(body.position);
Tile& new_position = m_map(x, y);
last_position.free = true;
last_position.entity = nullptr;
new_position.free = false;
new_position.entity = body.parent;
}
body.position.x = x;
body.position.y = y;
}
Vec3f World::real_position(Vec2i position, Vec3f size) {
Vec3f positionf{static_cast<float>(position.x),
static_cast<float>(position.y), 0.0f};
Vec3f real = (positionf * TILE_SIZE) + ((TILE_SIZE * 0.5f) - (size * 0.5f));
// real.y += TILE_SIZE.y * 0.5f - size.y * 0.25f;
real.z = 0.0001f;
return real;
}
void World::update(GameState& state) {
auto& bodies = COMPONENTS(BodyComponent);
auto& cursors = COMPONENTS(Cursor);
for (auto& body : bodies) {
Entity* e = body.parent;
AnimationComponent* animation =
e->has_component<AnimationComponent>()
? &e->component<AnimationComponent>()
: nullptr;
if (!body.lock && !body.dirty && body.commands.size() > 0) {
Command command = body.commands.top();
/* TODO: FSM */
switch (command.type) {
case Command::Type::MOVE_UP: {
if (this->move(body, 0, 1)) {
if (animation)
animation->animate("move_up", 1.0f, false,
&unlock_body);
body.lock = true;
}
body.pop_command();
} break;
case Command::Type::MOVE_DOWN: {
if (this->move(body, 0, -1)) {
if (animation)
animation->animate("move_down", 1.0f, false,
&unlock_body);
body.lock = true;
}
body.pop_command();
} break;
case Command::Type::MOVE_RIGHT: {
if (this->move(body, 1, 0)) {
if (animation)
animation->animate("move_right", 1.0f, false,
&unlock_body);
body.lock = true;
}
body.pop_command();
} break;
case Command::Type::MOVE_LEFT: {
if (this->move(body, -1, 0)) {
if (animation)
animation->animate("move_left", 1.0f, false,
&unlock_body);
body.lock = true;
}
body.pop_command();
} break;
case Command::Type::GO_TO: {
const Vec2i destination = command.data.Cast<Vec2i>();
const Vec2i diff = destination - body.position;
const Vec2i& pos = body.position;
if ((diff.x == 0 && diff.y == 0) ||
!m_map(destination).free) {
body.pop_command();
break;
}
if (abs(diff.x) > abs(diff.y)) {
if (diff.x > 0) {
if (m_map(pos.x + 1, pos.y).free) {
body.execute(Command::Type::MOVE_RIGHT);
} else if (m_map(pos.x, pos.y + 1).free) {
body.execute(Command::Type::MOVE_UP);
} else if (m_map(pos.x, pos.y - 1).free) {
body.execute(Command::Type::MOVE_DOWN);
} else if (m_map(pos.x - 1, pos.y).free) {
body.execute(Command::Type::MOVE_LEFT);
} else {
body.pop_command();
}
} else {
if (m_map(pos.x - 1, pos.y).free) {
body.execute(Command::Type::MOVE_LEFT);
} else if (m_map(pos.x, pos.y + 1).free) {
body.execute(Command::Type::MOVE_UP);
} else if (m_map(pos.x, pos.y - 1).free) {
body.execute(Command::Type::MOVE_DOWN);
} else if (m_map(pos.x + 1, pos.y).free) {
body.execute(Command::Type::MOVE_RIGHT);
} else {
body.pop_command();
}
}
} else {
if (diff.y > 0) {
if (m_map(pos.x, pos.y + 1).free) {
body.execute(Command::Type::MOVE_UP);
} else if (m_map(pos.x + 1, pos.y).free) {
body.execute(Command::Type::MOVE_RIGHT);
} else if (m_map(pos.x - 1, pos.y).free) {
body.execute(Command::Type::MOVE_LEFT);
} else if (m_map(pos.x, pos.y - 1).free) {
body.execute(Command::Type::MOVE_DOWN);
} else {
body.pop_command();
}
} else {
if (m_map(pos.x, pos.y - 1).free) {
body.execute(Command::Type::MOVE_DOWN);
} else if (m_map(pos.x - 1, pos.y).free) {
body.execute(Command::Type::MOVE_LEFT);
} else if (m_map(pos.x + 1, pos.y).free) {
body.execute(Command::Type::MOVE_RIGHT);
} else if (m_map(pos.x, pos.y + 1).free) {
body.execute(Command::Type::MOVE_UP);
} else {
body.pop_command();
}
}
}
} break;
default:
assert(false, "Unknown command");
body.pop_command();
break;
};
}
if (body.dirty && body.parent->has_component<PhysicsComponent>()) {
auto& physics = body.parent->component<PhysicsComponent>();
physics.position = this->real_position(body.position, physics.size);
this->set_position(body, body.position.x, body.position.y);
body.dirty = false;
}
}
for (auto& cursor : cursors) {
Entity* selected = cursor.selected;
if (!selected) continue;
auto& cursor_physics = cursor.parent->component<PhysicsComponent>();
auto& selected_physics = selected->component<PhysicsComponent>();
cursor_physics.size = Vec3f(selected_physics.size.x);
Vec3f relative =
selected_physics.size * 0.5f - cursor_physics.size * 0.5f;
cursor_physics.position.x = selected_physics.position.x + relative.x;
cursor_physics.position.y = selected_physics.position.y + relative.y;
cursor_physics.position.z = 0.0001f;
}
}
} /* namespace dm */
| 38.371041
| 80
| 0.440802
|
boudra
|
6aa3c3bd35796f80c044e3588138073ae8dea1b9
| 1,971
|
cpp
|
C++
|
ctest/tests/Serializer.cpp
|
mgradysaunders/Precept
|
0677c70ac4ed9e0a8c5aad7b049daad22998de9e
|
[
"BSD-2-Clause"
] | null | null | null |
ctest/tests/Serializer.cpp
|
mgradysaunders/Precept
|
0677c70ac4ed9e0a8c5aad7b049daad22998de9e
|
[
"BSD-2-Clause"
] | null | null | null |
ctest/tests/Serializer.cpp
|
mgradysaunders/Precept
|
0677c70ac4ed9e0a8c5aad7b049daad22998de9e
|
[
"BSD-2-Clause"
] | null | null | null |
#include "../testing.h"
#include <pre/Serializer>
#include <pre/StringID>
using namespace pre;
static int Serial_ctor_calls = 0;
static int Serial_dtor_calls = 0;
static int Serial_serialize_calls = 0;
class Serial : public Serializable {
public:
Serial() { ++Serial_ctor_calls; }
~Serial() { ++Serial_dtor_calls; }
};
class SerialBranch final : public Serial {
public:
SERIALIZABLE(SerialBranch);
void serialize(Serializer& serializer) {
serializer <=> serials;
++Serial_serialize_calls;
}
public:
std::map<std::string, RefPtr<Serial>> serials;
};
class SerialLeaf final : public Serial {
public:
SERIALIZABLE(SerialLeaf);
void serialize(Serializer& serializer) {
serializer <=> string_id;
serializer <=> value;
++Serial_serialize_calls;
}
SerialLeaf() = default;
SerialLeaf(StringID<> id, double v) : string_id(id), value(v) {}
public:
StringID<> string_id;
double value = 0;
};
TEST_CASE("Serializer") {
std::stringstream ss;
{
RefPtr branch1(new SerialBranch());
RefPtr branch2(new SerialBranch());
RefPtr leaf1(new SerialLeaf("Leaf1", 2.784));
RefPtr leaf2(new SerialLeaf("Leaf2", -1.993));
RefPtr leaf3(new SerialLeaf("Leaf3", -4.761));
branch1->serials["1"] = leaf1;
branch1->serials["2"] = leaf2;
branch2->serials["3"] = leaf3;
branch2->serials["1"] = leaf1;
branch2->serials["2"] = branch1;
StandardSerializer serializer(static_cast<std::ostream&>(ss));
serializer <=> branch2;
CHECK(Serial_ctor_calls == Serial_serialize_calls);
}
{
Serial_ctor_calls = 0;
Serial_dtor_calls = 0;
RefPtr<Serial> foo(nullptr);
StandardSerializer serializer(static_cast<std::istream&>(ss));
serializer <=> foo;
CHECK(Serial_ctor_calls == 5);
}
CHECK(Serial_ctor_calls == Serial_dtor_calls);
}
| 26.635135
| 70
| 0.632674
|
mgradysaunders
|
6aa5eac7415ca832d080ed5c0db31a010e77bca3
| 2,012
|
cpp
|
C++
|
test/cpp/main.cpp
|
moritzmhmk/charls-js
|
73fed2d8165a2385809700f9d8ae2ac12ff24269
|
[
"MIT"
] | 8
|
2020-04-17T18:01:38.000Z
|
2022-03-01T08:48:21.000Z
|
test/cpp/main.cpp
|
moritzmhmk/charls-js
|
73fed2d8165a2385809700f9d8ae2ac12ff24269
|
[
"MIT"
] | 2
|
2020-04-30T02:51:01.000Z
|
2022-01-12T22:39:11.000Z
|
test/cpp/main.cpp
|
moritzmhmk/charls-js
|
73fed2d8165a2385809700f9d8ae2ac12ff24269
|
[
"MIT"
] | 6
|
2020-04-17T18:01:48.000Z
|
2022-03-16T06:32:06.000Z
|
#include "../../extern/charls/include/charls/charls.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
#include <time.h>
void readFile(std::string fileName, std::vector<unsigned char>& vec) {
// open the file:
std::ifstream file(fileName, std::ios::binary);
// Stop eating new lines in binary mode!!!
file.unsetf(std::ios::skipws);
// get its size:
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// reserve capacity
vec.reserve(fileSize);
// read the data:
vec.insert(vec.begin(),
std::istream_iterator<unsigned char>(file),
std::istream_iterator<unsigned char>());
}
enum { NS_PER_SECOND = 1000000000 };
void sub_timespec(struct timespec t1, struct timespec t2, struct timespec *td)
{
td->tv_nsec = t2.tv_nsec - t1.tv_nsec;
td->tv_sec = t2.tv_sec - t1.tv_sec;
if (td->tv_sec > 0 && td->tv_nsec < 0)
{
td->tv_nsec += NS_PER_SECOND;
td->tv_sec--;
}
else if (td->tv_sec < 0 && td->tv_nsec > 0)
{
td->tv_nsec -= NS_PER_SECOND;
td->tv_sec++;
}
}
using namespace charls;
void decode(const char* path, size_t iterations = 1) {
std::vector<unsigned char> source;
readFile(path, source);
std::vector<unsigned char> destination;
timespec start, finish, delta;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
for(int i=0; i < iterations; i++) {
jpegls_decoder::decode(source, destination);
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &finish);
sub_timespec(start, finish, &delta);
const double ms = (double)(delta.tv_nsec / iterations) / 1000000.0;
printf("Decode of %s took %f ms\n", path, ms);
}
int main(int argc, char** argv) {
decode("test/fixtures/jls/CT1.JLS");
decode("test/fixtures/jls/CT2.JLS");
//decode("test/fixtures/jls/MG1.JLS");
decode("extern/charls/test/lena8b.jls");
return 0;
}
| 27.561644
| 78
| 0.630716
|
moritzmhmk
|
6aac21d5f6239895a60440bc3aa034aac960dd08
| 8,446
|
cpp
|
C++
|
FloatingMeasure_Test/FloatingMeasure_Test.cpp
|
github-baron/FloatingMeasure
|
1419d95c168bd7c9927854f0fc8e7c3681b93d2d
|
[
"MIT"
] | 1
|
2020-11-09T07:13:03.000Z
|
2020-11-09T07:13:03.000Z
|
FloatingMeasure_Test/FloatingMeasure_Test.cpp
|
github-baron/FloatingMeasure
|
1419d95c168bd7c9927854f0fc8e7c3681b93d2d
|
[
"MIT"
] | 3
|
2020-01-27T16:20:50.000Z
|
2020-01-31T23:13:53.000Z
|
FloatingMeasure_Test/FloatingMeasure_Test.cpp
|
github-baron/FloatingMeasure
|
1419d95c168bd7c9927854f0fc8e7c3681b93d2d
|
[
"MIT"
] | null | null | null |
/*
* MIT License
*
* Copyright (c) 2020 Michael von Mengershausen
*
* 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 "../FloatingMeasure/Utils/Utils.h"
#include "../FloatingMeasure/Measure/ComplexMeasureMacros.h"
#include "../FloatingMeasure/FloatingMeasure/FloatingMeasure.h"
class CFloatingMeasure_Test : public CppUnit::TestFixture {
private:
CFloatingMeasure cfTest1, cfTest2, cfTest3;
public:
void setUp()
{
}
void tearDown()
{
}
void OperatorEqual()
{
cfTest1 = 10*mC/kK;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 10);
CPPUNIT_ASSERT_MESSAGE( cfTest1.Measure().DebugOut(), cfTest1.Measure() == mC/kK);
LOGTRACE("ErrorLogger","OperatorEqual");
// operator == ...
cfTest1 = 0.00000001*uV;
cfTest2 = 0.01*pV;
cfTest1.PrecisionActive(false);
cfTest2.PrecisionActive(false);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut() + "\n" + cfTest2.DebugOut() + "\n" +
cfTest1.PrintShort() + "\n" + cfTest2.PrintShort(), cfTest1 == cfTest2 );
}
void Normalize()
{
cfTest1 = 10*mC/kK;
cfTest1.Normalize();
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 10./1000./1000.);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == C/K);
}
void ScaleToTemperature()
{
cfTest1 = 185*K;
cfTest1.ScaleTo(C);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 185.-273.15);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == C);
cfTest1.ScaleTo(F);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 9./5.*(185.-273.15) + 32);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == F);
cfTest1.ScaleTo(K);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 185);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == K);
}
void NormalizeTemperature()
{
// °F --> °K
cfTest1 = 10*kF;
cfTest1.Normalize();
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 10*1000*5/9.+273.15-5./9*32.);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == K );
// °C --> °K
cfTest1 = 10*mC;
cfTest1.Normalize();
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 273.15+0.01);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == K );
}
void Simplify()
{
cfTest1 = 23403*uK/cC*V*uA/K*kF*MC;
cfTest1.Simplify();
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 23403*0.000001*100*1000000 );
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut() + "\n" + cfTest1.PrintShort(), cfTest1.Measure() == V*uA*kF );
}
void ScaleTo()
{
cfTest1 = 10*mV;
// scale to
cfTest1.ScaleTo(1*kV);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 0.00001 );
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == kV );
cfTest1.Normalize();
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 0.01 );
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == V );
cfTest1.ScaleTo(mV);
cfTest1.Precision(0.000001*kV);
cfTest1.PrecisionActive(true);
CPPUNIT_ASSERT_MESSAGE( cfTest1.PrintShort() + "\n" +
cfTest1.DebugOut(),
cfTest1.PrintShort() == "10*mV" );
// scale to
cfTest1.ScaleTo(1*kV);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 0.00001 );
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == kV );
cfTest1 = 10*V;
cfTest2 = 1000*h;
cfTest3 = 0.134342*uA;
cfTest3 *= cfTest2*cfTest1;
cfTest3.ScaleTo(V*A*h);
CPPUNIT_ASSERT_MESSAGE( cfTest3.DebugOut(), cfTest3.Floating() == 0.00134342 );
CPPUNIT_ASSERT_MESSAGE( cfTest3.DebugOut(), cfTest3.Measure() == V*A*h );
}
void Precision()
{
// operator +=
CFloatingMeasure cfTest2;
cfTest2 = 220*V;
cfTest1 = 10*mV;
cfTest1.ScaleTo(kV);
CFloatingMeasure cfTest3;
cfTest1 += cfTest2;
cfTest1.Precision(1*mV);
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Floating() == 0.220010 );
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Measure() == kV );
// check for different precision : [0.1,1[ --> nDigits = 1
cfTest1.Precision(0.99*mV);
CPPUNIT_ASSERT_MESSAGE( cfTest1.PrintShort(), cfTest1.PrintShort() == "0.2200100*kV" );
cfTest2 = 312.3432*GV;
// 312.3432 GV -
// 0.000000220010 GV =
// 312.34319977999
cfTest2 -= cfTest1;
cfTest2.Precision(1*cV);
CPPUNIT_ASSERT_MESSAGE( cfTest2.DebugOut(), cfTest2.Floating() == 312.34319977999 );
CPPUNIT_ASSERT_MESSAGE( cfTest2.DebugOut(), cfTest2.Measure() == GV );
cfTest2.Precision(1*dV);
cfTest2.PrecisionActive(true);
CPPUNIT_ASSERT_MESSAGE( cfTest2.DebugOut(), cfTest2.Floating() == 312.34319978000 );
CPPUNIT_ASSERT_MESSAGE( cfTest2.DebugOut(), cfTest2.Measure() == GV );
// now check the limits:
// 0.9999 dV --> 0.1 dV digits
// 10 dV --> 10 dV digits
cfTest2.Precision(0.999999999*dV);
CPPUNIT_ASSERT_MESSAGE( cfTest2.DebugOut(), cfTest2.Floating() == 312.34319977999 );
cfTest2.Precision(1*dV);
CPPUNIT_ASSERT_MESSAGE( cfTest2.DebugOut(), cfTest2.Floating() == 312.34319978000 );
}
void Valid()
{
// ::Valid
cfTest1 = 10*myNAN*uV;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), !cfTest1.Valid());
cfTest1 = 10*uV;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1.Valid());
cfTest1 = 10*uV/us*kV*ZA/CComplexMeasure(pmUnknown,bmAmpere)*uA/kV;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), !cfTest1.Valid());
cfTest1 = 10*uV*us*kV*ZA/CComplexMeasure(pmUnknown,bmAmpere)*uA/kV;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), !cfTest1.Valid());
// check operators with inversion
cfTest1 = mV*10;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1 == 10*mV);
cfTest1 = 10*uA/mV*10;
CPPUNIT_ASSERT_MESSAGE( cfTest1.DebugOut(), cfTest1 == 100*uA/mV);
}
void Velocity()
{
// velocity check
cfTest1 = 3.6*m;
cfTest2 = 1*s;
cfTest3 = cfTest1 / cfTest2;
CPPUNIT_ASSERT_MESSAGE( cfTest3.DebugOut(), cfTest3 == 3.6*m/s);
cfTest3.Precision(0.1*m/s);
cfTest3.PrecisionActive(true);
CPPUNIT_ASSERT_MESSAGE( cfTest3.PrintShort(), cfTest3.PrintShort() == "3.6*m/s");
cfTest3.Precision(0.00001*km/h);
cfTest3.ScaleTo(km/h);
CPPUNIT_ASSERT_MESSAGE( cfTest3.DebugOut() + "\n" + cfTest3.PrintShort(), cfTest3 == 3.6*km/h/1000.*3600.);
}
};
| 37.207048
| 115
| 0.608335
|
github-baron
|
6aadb9a01efd13a31dbde8e7753453cb9fcd3936
| 652
|
cpp
|
C++
|
gameMainDriver/gameMainDriver.cpp
|
FullSiliconAlchemist/comp345-V2
|
459ed4490139360d8ec7816523191ca95ccaded3
|
[
"MIT"
] | 1
|
2019-10-10T15:16:12.000Z
|
2019-10-10T15:16:12.000Z
|
gameMainDriver/gameMainDriver.cpp
|
FullSiliconAlchemist/comp345-V2
|
459ed4490139360d8ec7816523191ca95ccaded3
|
[
"MIT"
] | null | null | null |
gameMainDriver/gameMainDriver.cpp
|
FullSiliconAlchemist/comp345-V2
|
459ed4490139360d8ec7816523191ca95ccaded3
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include "../MapProject/Map.h"
#include "../MapProject/Map.cpp"
#include "../MapProject/Country.h"
#include "../MapProject/Country.cpp"
#include "../MapLoaderProject/MapLoader.h"
#include "../MapLoaderProject/MapLoader.cpp"
int main()
{
std::cout << "Hello, friend." << std::endl;
std::cout << "Welcome to the best damn game you've ever laid eyes on." << std::endl;
std::string mapPath = "C:\\tmp\\dataFile.txt";
MapLoader * newMap = new MapLoader(&mapPath);
newMap->openFileAndStore(newMap->getFileName());
}
| 23.285714
| 85
| 0.693252
|
FullSiliconAlchemist
|
6aadc74baf75e7314e9ac1133865ea3fd2b607af
| 1,930
|
cpp
|
C++
|
3DEngine2/src/common/Window.cpp
|
rainnymig/ThreeDeeEngine-2
|
3f4c00cbf1c816072a020d850095295da6c29ccb
|
[
"BSD-3-Clause"
] | null | null | null |
3DEngine2/src/common/Window.cpp
|
rainnymig/ThreeDeeEngine-2
|
3f4c00cbf1c816072a020d850095295da6c29ccb
|
[
"BSD-3-Clause"
] | null | null | null |
3DEngine2/src/common/Window.cpp
|
rainnymig/ThreeDeeEngine-2
|
3f4c00cbf1c816072a020d850095295da6c29ccb
|
[
"BSD-3-Clause"
] | null | null | null |
#include "pch.h"
#include "common/Window.h"
namespace tde
{
Window::Window(
ConstructorTag aConstructorTag,
HWND aWindowHandle)
: mWindowHandle(aWindowHandle)
{}
bool Window::RegisterWindow(const WNDCLASSEX* apWndClassEx)
{
if (!RegisterClassExW(apWndClassEx))
{
return false;
}
return true;
}
std::unique_ptr<Window> Window::MakeWindow(
DWORD aExStyle,
LPCWSTR aClassName,
LPCWSTR aWindowName,
DWORD aStyle,
int aX,
int aY,
int aWidth,
int aHeight,
HWND aWndParent,
HMENU aMenu,
HINSTANCE ahInstance,
LPVOID apParam)
{
HWND hwnd = CreateWindowEx(aExStyle, aClassName, aWindowName, aStyle, aX, aY, aWidth, aHeight, aWndParent, aMenu, ahInstance, apParam);
if (!hwnd)
{
throw std::runtime_error("failed to create window");
}
return std::make_unique<Window>(ConstructorTag(), hwnd);
}
Window::~Window()
{
DestroyWindow(mWindowHandle);
}
HWND Window::GetWindowHandle() const
{
return mWindowHandle;
}
void Window::Show()
{
ShowWindow(mWindowHandle, SW_SHOWNORMAL);
}
void Window::Minimize()
{
ShowWindow(mWindowHandle, SW_SHOWMINIMIZED);
}
void Window::Maximize()
{
ShowWindow(mWindowHandle, SW_SHOWMAXIMIZED);
}
void Window::ToggleFullscreen()
{
if (mIsFullscreen)
{
SetWindowLongPtr(mWindowHandle, GWL_STYLE, WS_OVERLAPPEDWINDOW);
SetWindowLongPtr(mWindowHandle, GWL_EXSTYLE, 0);
int width = 800;
int height = 600;
ShowWindow(mWindowHandle, SW_SHOWNORMAL);
SetWindowPos(mWindowHandle, HWND_TOP, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
else
{
SetWindowLongPtr(mWindowHandle, GWL_STYLE, 0);
SetWindowLongPtr(mWindowHandle, GWL_EXSTYLE, WS_EX_TOPMOST);
SetWindowPos(mWindowHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
ShowWindow(mWindowHandle, SW_SHOWMAXIMIZED);
}
mIsFullscreen = !mIsFullscreen;
}
}
| 20.752688
| 137
| 0.717098
|
rainnymig
|
6ac5c319f2297f88b69f89b33cc81c38004b4e0c
| 102,443
|
cpp
|
C++
|
test/make_matrix.cpp
|
bebuch/Mitrax
|
bc33a1b93058886daab3e4ef736ef9b519111454
|
[
"BSL-1.0"
] | null | null | null |
test/make_matrix.cpp
|
bebuch/Mitrax
|
bc33a1b93058886daab3e4ef736ef9b519111454
|
[
"BSL-1.0"
] | null | null | null |
test/make_matrix.cpp
|
bebuch/Mitrax
|
bc33a1b93058886daab3e4ef736ef9b519111454
|
[
"BSL-1.0"
] | null | null | null |
// -----------------------------------------------------------------------------
// Copyright (c) 2015-2018 Benjamin Buch
//
// https://github.com/bebuch/mitrax
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE mitrax make_matrix
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>
#include <mitrax/make_matrix.hpp>
#include <complex>
#include <iostream>
using namespace mitrax;
using namespace mitrax::literals;
template < typename T >
auto rt_id(T&& v){
return boost::typeindex::type_id_runtime(static_cast< T&& >(v));
}
template < typename T >
auto const id = boost::typeindex::type_id< T >();
template < typename Matrix, size_t RefC, size_t RefR >
constexpr bool check_fn(
Matrix& m,
value_type_t< Matrix > const(&ref)[RefR][RefC]
){
using value_type = value_type_t< Matrix >;
bool res = true;
res &= m.cols() == cols< col_t(RefC) >();
res &= m.rows() == rows< row_t(RefR) >();
for(size_t y = 0; y < RefR; ++y){
for(size_t x = 0; x < RefC; ++x){
res &= m(c_t(x), r_t(y)) == ref[y][x];
}
}
if constexpr(Matrix::ct_cols == 1_C || Matrix::ct_rows == 1_R){
auto vec_ref =
reinterpret_cast< value_type const(&)[RefC * RefR] >(ref);
for(size_t i = 0; i < RefC * RefR; ++i){
res &= m[d_t(i)] == vec_ref[i];
}
}
if constexpr(Matrix::ct_cols == 1_C && Matrix::ct_rows == 1_R){
res &= static_cast< value_type >(m) == ref[0][0];
}
return res;
}
template < typename M, col_t C, row_t R, size_t RefC, size_t RefR >
constexpr bool check(
matrix< M, C, R > const& m,
value_type_t< M > const(&ref)[RefR][RefC]
){
return check_fn(m, ref);
}
template < typename M, col_t C, row_t R, size_t RefC, size_t RefR >
constexpr bool check(
matrix< M, C, R >& m,
value_type_t< M > const(&ref)[RefR][RefC]
){
auto const& m_const = m;
return check_fn(m, ref) && check(m_const, ref);
}
template < typename T >
struct fn_xy_t{
template < typename T1, typename T2 >
constexpr T operator()(T1 x, T2 y)const noexcept{
return size_t(x) + size_t(y) * 10;
}
};
template < typename T >
struct fn_x_t{
template < typename T1 >
constexpr T operator()(T1 i)const noexcept{
return size_t(i) * 10;
}
};
template < typename T >
struct fn_y_t{
template < typename T1 >
constexpr T operator()(T1 i)const noexcept{
return size_t(i);
}
};
template < typename T >
struct fn_i_t{
template < typename T1 >
constexpr T operator()(T1 i)const noexcept{
return size_t(i) + size_t(i) * 10;
}
};
BOOST_AUTO_TEST_SUITE(suite_make_matrix)
using types = boost::mpl::list< int, double, std::complex< float > >;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_types, T, types){
BOOST_TEST((
id< std_matrix< T, 3_C, 4_R > > ==
id< matrix< detail::stack_matrix_impl< T, 3_C, 4_R >, 3_C, 4_R > >
));
BOOST_TEST((
id< std_bitmap< T > > ==
id< bitmap< detail::heap_matrix_impl< T, 0_C, 0_R > > >
));
BOOST_TEST((
id< std_col_vector< T, 4_R > > ==
id< col_vector< detail::stack_matrix_impl< T, 1_C, 4_R >, 4_R > >
));
BOOST_TEST((
id< std_col_vector< T, 4_R > > ==
id< matrix< detail::stack_matrix_impl< T, 1_C, 4_R >, 1_C, 4_R > >
));
BOOST_TEST((
id< std_row_vector< T, 4_C > > ==
id< row_vector< detail::stack_matrix_impl< T, 4_C, 1_R >, 4_C > >
));
BOOST_TEST((
id< std_row_vector< T, 4_C > > ==
id< matrix< detail::stack_matrix_impl< T, 4_C, 1_R >, 4_C, 1_R > >
));
BOOST_TEST((
id< std_square_matrix< T, 4_D > > ==
id< square_matrix< detail::stack_matrix_impl< T, 4_C, 4_R >, 4_D > >
));
BOOST_TEST((
id< std_square_matrix< T, 4_D > > ==
id< matrix< detail::stack_matrix_impl< T, 4_C, 4_R >, 4_C, 4_R > >
));
BOOST_TEST((
id< heap_matrix< T, 3_C, 4_R > > ==
id< matrix< detail::heap_matrix_impl< T, 3_C, 4_R >, 3_C, 4_R > >
));
BOOST_TEST((
id< heap_matrix< T, 0_C, 4_R > > ==
id< matrix< detail::heap_matrix_impl< T, 0_C, 4_R >, 0_C, 4_R > >
));
BOOST_TEST((
id< heap_matrix< T, 3_C, 0_R > > ==
id< matrix< detail::heap_matrix_impl< T, 3_C, 0_R >, 3_C, 0_R > >
));
BOOST_TEST((
id< heap_matrix< T, 0_C, 0_R > > ==
id< matrix< detail::heap_matrix_impl< T, 0_C, 0_R >, 0_C, 0_R > >
));
BOOST_TEST((
id< heap_col_vector< T, 4_R > > ==
id< col_vector< detail::heap_matrix_impl< T, 1_C, 4_R >, 4_R > >
));
BOOST_TEST((
id< heap_col_vector< T, 0_R > > ==
id< col_vector< detail::heap_matrix_impl< T, 1_C, 0_R >, 0_R > >
));
BOOST_TEST((
id< heap_col_vector< T, 4_R > > ==
id< matrix< detail::heap_matrix_impl< T, 1_C, 4_R >, 1_C, 4_R > >
));
BOOST_TEST((
id< heap_col_vector< T, 0_R > > ==
id< matrix< detail::heap_matrix_impl< T, 1_C, 0_R >, 1_C, 0_R > >
));
BOOST_TEST((
id< heap_row_vector< T, 4_C > > ==
id< row_vector< detail::heap_matrix_impl< T, 4_C, 1_R >, 4_C > >
));
BOOST_TEST((
id< heap_row_vector< T, 0_C > > ==
id< row_vector< detail::heap_matrix_impl< T, 0_C, 1_R >, 0_C > >
));
BOOST_TEST((
id< heap_row_vector< T, 4_C > > ==
id< matrix< detail::heap_matrix_impl< T, 4_C, 1_R >, 4_C, 1_R > >
));
BOOST_TEST((
id< heap_row_vector< T, 0_C > > ==
id< matrix< detail::heap_matrix_impl< T, 0_C, 1_R >, 0_C, 1_R > >
));
BOOST_TEST((
id< heap_square_matrix< T, 4_D > > ==
id< square_matrix< detail::heap_matrix_impl< T, 4_C, 4_R >, 4_D > >
));
BOOST_TEST((
id< heap_square_matrix< T, 0_D > > ==
id< square_matrix< detail::heap_matrix_impl< T, 0_C, 0_R >, 0_D > >
));
BOOST_TEST((
id< heap_square_matrix< T, 4_D > > ==
id< matrix< detail::heap_matrix_impl< T, 4_C, 4_R >, 4_C, 4_R > >
));
BOOST_TEST((
id< heap_square_matrix< T, 0_D > > ==
id< matrix< detail::heap_matrix_impl< T, 0_C, 0_R >, 0_C, 0_R > >
));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_3x3, T, types){
constexpr T ref_0[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
constexpr T ref_v[3][3] = {{7, 7, 7}, {7, 7, 7}, {7, 7, 7}};
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
static constexpr T init_i[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][3] = {{0, 1, 2}, {10, 11, 12}, {20, 21, 22}};
constexpr auto fn = fn_xy_t< T >();
constexpr auto m01 = make_matrix_v< T >(3_CS, 3_RS);
auto m02 = make_matrix_v< T >(3_CD, 3_RS);
auto m03 = make_matrix_v< T >(3_CS, 3_RD);
auto m04 = make_matrix_v< T >(3_CD, 3_RD);
constexpr auto m05 = make_matrix_v< T >(dim_pair(3_CS, 3_RS));
auto m06 = make_matrix_v< T >(dim_pair(3_CD, 3_RS));
auto m07 = make_matrix_v< T >(dim_pair(3_CS, 3_RD));
auto m08 = make_matrix_v< T >(dim_pair(3_CD, 3_RD));
constexpr auto m09 = make_matrix_v< T >(3_DS);
auto m10 = make_matrix_v< T >(3_DD);
constexpr auto m11 = make_matrix_v< T >(dim_pair(3_DS));
auto m12 = make_matrix_v< T >(dim_pair(3_DD));
constexpr auto m13 = make_matrix_v(3_CS, 3_RS, T(7));
auto m14 = make_matrix_v(3_CD, 3_RS, T(7));
auto m15 = make_matrix_v(3_CS, 3_RD, T(7));
auto m16 = make_matrix_v(3_CD, 3_RD, T(7));
constexpr auto m17 = make_matrix_v(dim_pair(3_CS, 3_RS), T(7));
auto m18 = make_matrix_v(dim_pair(3_CD, 3_RS), T(7));
auto m19 = make_matrix_v(dim_pair(3_CS, 3_RD), T(7));
auto m20 = make_matrix_v(dim_pair(3_CD, 3_RD), T(7));
constexpr auto m21 = make_matrix_v(3_DS, T(7));
auto m22 = make_matrix_v(3_DD, T(7));
constexpr auto m23 = make_matrix_v(dim_pair(3_DS), T(7));
auto m24 = make_matrix_v(dim_pair(3_DD), T(7));
constexpr auto m25 =
make_matrix< T >(3_CS, 3_RS, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
auto m26 =
make_matrix< T >(3_CD, 3_RS, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
auto m27 =
make_matrix< T >(3_CS, 3_RD, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
auto m28 =
make_matrix< T >(3_CD, 3_RD, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
constexpr auto m29 = make_matrix(3_CS, 3_RS, ref_i);
auto m30 = make_matrix(3_CD, 3_RS, ref_i);
auto m31 = make_matrix(3_CS, 3_RD, ref_i);
auto m32 = make_matrix(3_CD, 3_RD, ref_i);
constexpr auto m33 =
make_matrix< T >(3_DS, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
auto m34 =
make_matrix< T >(3_DD, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
constexpr auto m35 = make_matrix(3_DS, ref_i);
auto m36 = make_matrix(3_DD, ref_i);
constexpr auto m37 = make_matrix_fn(3_CS, 3_RS, fn);
auto m38 = make_matrix_fn(3_CD, 3_RS, fn);
auto m39 = make_matrix_fn(3_CS, 3_RD, fn);
auto m40 = make_matrix_fn(3_CD, 3_RD, fn);
constexpr auto m41 = make_matrix_fn(dim_pair(3_CS, 3_RS), fn);
auto m42 = make_matrix_fn(dim_pair(3_CD, 3_RS), fn);
auto m43 = make_matrix_fn(dim_pair(3_CS, 3_RD), fn);
auto m44 = make_matrix_fn(dim_pair(3_CD, 3_RD), fn);
constexpr auto m45 = make_matrix_fn(3_DS, fn);
auto m46 = make_matrix_fn(3_DD, fn);
constexpr auto m47 = make_matrix_fn(dim_pair(3_DS), fn);
auto m48 = make_matrix_fn(dim_pair(3_DD), fn);
constexpr auto m49 = make_matrix_i(3_CS, 3_RS, init_p);
auto m50 = make_matrix_i(3_CD, 3_RS, init_p);
auto m51 = make_matrix_i(3_CS, 3_RD, init_p);
auto m52 = make_matrix_i(3_CD, 3_RD, init_p);
constexpr auto m53 = make_matrix_i(dim_pair(3_CS, 3_RS), init_p);
auto m54 = make_matrix_i(dim_pair(3_CD, 3_RS), init_p);
auto m55 = make_matrix_i(dim_pair(3_CS, 3_RD), init_p);
auto m56 = make_matrix_i(dim_pair(3_CD, 3_RD), init_p);
constexpr auto m57 = make_matrix_i(3_DS, init_p);
auto m58 = make_matrix_i(3_DD, init_p);
constexpr auto m59 = make_matrix_i(dim_pair(3_DS), init_p);
auto m60 = make_matrix_i(dim_pair(3_DD), init_p);
constexpr auto m61 = make_matrix< T >({{0, 1, 2}, {3, 4, 5}, {6, 7, 8}});
constexpr auto m62 = make_matrix(ref_i);
constexpr auto m63 = make_matrix(
{{T(0), T(1), T(2)}, {T(3), T(4), T(5)}, {T(6), T(7), T(8)}});
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m18) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m19) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m22) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m23) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m24) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m26) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m27) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m28) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m29) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m30) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m31) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m32) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m34) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m35) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m36) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m37) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m38) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m39) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m40) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m41) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m42) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m43) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m44) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m45) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m46) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m47) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m48) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m49) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m50) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m51) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m52) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m53) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m54) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m55) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m56) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m57) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m58) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m59) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m60) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m61) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m62) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m63) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((check(m01, ref_0)));
BOOST_TEST((check(m02, ref_0)));
BOOST_TEST((check(m03, ref_0)));
BOOST_TEST((check(m04, ref_0)));
BOOST_TEST((check(m05, ref_0)));
BOOST_TEST((check(m06, ref_0)));
BOOST_TEST((check(m07, ref_0)));
BOOST_TEST((check(m08, ref_0)));
BOOST_TEST((check(m09, ref_0)));
BOOST_TEST((check(m10, ref_0)));
BOOST_TEST((check(m11, ref_0)));
BOOST_TEST((check(m12, ref_0)));
BOOST_TEST((check(m13, ref_v)));
BOOST_TEST((check(m14, ref_v)));
BOOST_TEST((check(m15, ref_v)));
BOOST_TEST((check(m16, ref_v)));
BOOST_TEST((check(m17, ref_v)));
BOOST_TEST((check(m18, ref_v)));
BOOST_TEST((check(m19, ref_v)));
BOOST_TEST((check(m20, ref_v)));
BOOST_TEST((check(m21, ref_v)));
BOOST_TEST((check(m22, ref_v)));
BOOST_TEST((check(m23, ref_v)));
BOOST_TEST((check(m24, ref_v)));
BOOST_TEST((check(m25, ref_i)));
BOOST_TEST((check(m26, ref_i)));
BOOST_TEST((check(m27, ref_i)));
BOOST_TEST((check(m28, ref_i)));
BOOST_TEST((check(m29, ref_i)));
BOOST_TEST((check(m30, ref_i)));
BOOST_TEST((check(m31, ref_i)));
BOOST_TEST((check(m32, ref_i)));
BOOST_TEST((check(m33, ref_i)));
BOOST_TEST((check(m34, ref_i)));
BOOST_TEST((check(m35, ref_i)));
BOOST_TEST((check(m36, ref_i)));
BOOST_TEST((check(m37, ref_f)));
BOOST_TEST((check(m38, ref_f)));
BOOST_TEST((check(m39, ref_f)));
BOOST_TEST((check(m40, ref_f)));
BOOST_TEST((check(m41, ref_f)));
BOOST_TEST((check(m42, ref_f)));
BOOST_TEST((check(m43, ref_f)));
BOOST_TEST((check(m44, ref_f)));
BOOST_TEST((check(m45, ref_f)));
BOOST_TEST((check(m46, ref_f)));
BOOST_TEST((check(m47, ref_f)));
BOOST_TEST((check(m48, ref_f)));
BOOST_TEST((check(m49, ref_i)));
BOOST_TEST((check(m50, ref_i)));
BOOST_TEST((check(m51, ref_i)));
BOOST_TEST((check(m52, ref_i)));
BOOST_TEST((check(m53, ref_i)));
BOOST_TEST((check(m54, ref_i)));
BOOST_TEST((check(m55, ref_i)));
BOOST_TEST((check(m56, ref_i)));
BOOST_TEST((check(m57, ref_i)));
BOOST_TEST((check(m58, ref_i)));
BOOST_TEST((check(m59, ref_i)));
BOOST_TEST((check(m60, ref_i)));
BOOST_TEST((check(m61, ref_i)));
BOOST_TEST((check(m62, ref_i)));
BOOST_TEST((check(m63, ref_i)));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_2x3, T, types){
constexpr T ref_0[3][2] = {{0, 0}, {0, 0}, {0, 0}};
constexpr T ref_v[3][2] = {{7, 7}, {7, 7}, {7, 7}};
constexpr T ref_i[3][2] = {{0, 1}, {2, 3}, {4, 5}};
static constexpr T init_i[6] = {0, 1, 2, 3, 4, 5};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][2] = {{0, 1}, {10, 11}, {20, 21}};
constexpr auto fn = fn_xy_t< T >();
constexpr auto m01 = make_matrix_v< T >(2_CS, 3_RS);
auto m02 = make_matrix_v< T >(2_CD, 3_RS);
auto m03 = make_matrix_v< T >(2_CS, 3_RD);
auto m04 = make_matrix_v< T >(2_CD, 3_RD);
constexpr auto m05 = make_matrix_v< T >(dim_pair(2_CS, 3_RS));
auto m06 = make_matrix_v< T >(dim_pair(2_CD, 3_RS));
auto m07 = make_matrix_v< T >(dim_pair(2_CS, 3_RD));
auto m08 = make_matrix_v< T >(dim_pair(2_CD, 3_RD));
constexpr auto m09 = make_matrix_v(2_CS, 3_RS, T(7));
auto m10 = make_matrix_v(2_CD, 3_RS, T(7));
auto m11 = make_matrix_v(2_CS, 3_RD, T(7));
auto m12 = make_matrix_v(2_CD, 3_RD, T(7));
constexpr auto m13 = make_matrix_v(dim_pair(2_CS, 3_RS), T(7));
auto m14 = make_matrix_v(dim_pair(2_CD, 3_RS), T(7));
auto m15 = make_matrix_v(dim_pair(2_CS, 3_RD), T(7));
auto m16 = make_matrix_v(dim_pair(2_CD, 3_RD), T(7));
constexpr auto m17 =
make_matrix< T >(2_CS, 3_RS, {{0, 1}, {2, 3}, {4, 5}});
auto m18 = make_matrix< T >(2_CD, 3_RS, {{0, 1}, {2, 3}, {4, 5}});
auto m19 = make_matrix< T >(2_CS, 3_RD, {{0, 1}, {2, 3}, {4, 5}});
auto m20 = make_matrix< T >(2_CD, 3_RD, {{0, 1}, {2, 3}, {4, 5}});
constexpr auto m21 = make_matrix(2_CS, 3_RS, ref_i);
auto m22 = make_matrix(2_CD, 3_RS, ref_i);
auto m23 = make_matrix(2_CS, 3_RD, ref_i);
auto m24 = make_matrix(2_CD, 3_RD, ref_i);
constexpr auto m25 = make_matrix_fn(2_CS, 3_RS, fn);
auto m26 = make_matrix_fn(2_CD, 3_RS, fn);
auto m27 = make_matrix_fn(2_CS, 3_RD, fn);
auto m28 = make_matrix_fn(2_CD, 3_RD, fn);
constexpr auto m29 = make_matrix_fn(dim_pair(2_CS, 3_RS), fn);
auto m30 = make_matrix_fn(dim_pair(2_CD, 3_RS), fn);
auto m31 = make_matrix_fn(dim_pair(2_CS, 3_RD), fn);
auto m32 = make_matrix_fn(dim_pair(2_CD, 3_RD), fn);
constexpr auto m33 = make_matrix_i(2_CS, 3_RS, init_p);
auto m34 = make_matrix_i(2_CD, 3_RS, init_p);
auto m35 = make_matrix_i(2_CS, 3_RD, init_p);
auto m36 = make_matrix_i(2_CD, 3_RD, init_p);
constexpr auto m37 = make_matrix_i(dim_pair(2_CS, 3_RS), init_p);
auto m38 = make_matrix_i(dim_pair(2_CD, 3_RS), init_p);
auto m39 = make_matrix_i(dim_pair(2_CS, 3_RD), init_p);
auto m40 = make_matrix_i(dim_pair(2_CD, 3_RD), init_p);
constexpr auto m41 = make_matrix< T >({{0, 1}, {2, 3}, {4, 5}});
constexpr auto m42 = make_matrix(ref_i);
constexpr auto m43 = make_matrix(
{{T(0), T(1)}, {T(2), T(3)}, {T(4), T(5)}});
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m18) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m19) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m22) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m23) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m24) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m26) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m27) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m28) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m29) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m30) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m31) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m32) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m34) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m35) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m36) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m37) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m38) == id< std_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m39) == id< std_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m40) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m41) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m42) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m43) == id< std_matrix< T, 2_C, 3_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_0));
BOOST_TEST(check(m08, ref_0));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_v));
BOOST_TEST(check(m14, ref_v));
BOOST_TEST(check(m15, ref_v));
BOOST_TEST(check(m16, ref_v));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_i));
BOOST_TEST(check(m22, ref_i));
BOOST_TEST(check(m23, ref_i));
BOOST_TEST(check(m24, ref_i));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_f));
BOOST_TEST(check(m28, ref_f));
BOOST_TEST(check(m29, ref_f));
BOOST_TEST(check(m30, ref_f));
BOOST_TEST(check(m31, ref_f));
BOOST_TEST(check(m32, ref_f));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m36, ref_i));
BOOST_TEST(check(m37, ref_i));
BOOST_TEST(check(m38, ref_i));
BOOST_TEST(check(m39, ref_i));
BOOST_TEST(check(m40, ref_i));
BOOST_TEST(check(m41, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_3x2, T, types){
constexpr T ref_0[2][3] = {{0, 0, 0}, {0, 0, 0}};
constexpr T ref_v[2][3] = {{7, 7, 7}, {7, 7, 7}};
constexpr T ref_i[2][3] = {{0, 1, 2}, {3, 4, 5}};
static constexpr T init_i[6] = {0, 1, 2, 3, 4, 5};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[2][3] = {{0, 1, 2}, {10, 11, 12}};
constexpr auto fn = fn_xy_t< T >();
constexpr auto m01 = make_matrix_v< T >(3_CS, 2_RS);
auto m02 = make_matrix_v< T >(3_CD, 2_RS);
auto m03 = make_matrix_v< T >(3_CS, 2_RD);
auto m04 = make_matrix_v< T >(3_CD, 2_RD);
constexpr auto m05 = make_matrix_v< T >(dim_pair(3_CS, 2_RS));
auto m06 = make_matrix_v< T >(dim_pair(3_CD, 2_RS));
auto m07 = make_matrix_v< T >(dim_pair(3_CS, 2_RD));
auto m08 = make_matrix_v< T >(dim_pair(3_CD, 2_RD));
constexpr auto m09 = make_matrix_v(3_CS, 2_RS, T(7));
auto m10 = make_matrix_v(3_CD, 2_RS, T(7));
auto m11 = make_matrix_v(3_CS, 2_RD, T(7));
auto m12 = make_matrix_v(3_CD, 2_RD, T(7));
constexpr auto m13 = make_matrix_v(dim_pair(3_CS, 2_RS), T(7));
auto m14 = make_matrix_v(dim_pair(3_CD, 2_RS), T(7));
auto m15 = make_matrix_v(dim_pair(3_CS, 2_RD), T(7));
auto m16 = make_matrix_v(dim_pair(3_CD, 2_RD), T(7));
constexpr auto m17 = make_matrix< T >(3_CS, 2_RS, {{0, 1, 2}, {3, 4, 5}});
auto m18 = make_matrix< T >(3_CD, 2_RS, {{0, 1, 2}, {3, 4, 5}});
auto m19 = make_matrix< T >(3_CS, 2_RD, {{0, 1, 2}, {3, 4, 5}});
auto m20 = make_matrix< T >(3_CD, 2_RD, {{0, 1, 2}, {3, 4, 5}});
constexpr auto m21 = make_matrix(3_CS, 2_RS, ref_i);
auto m22 = make_matrix(3_CD, 2_RS, ref_i);
auto m23 = make_matrix(3_CS, 2_RD, ref_i);
auto m24 = make_matrix(3_CD, 2_RD, ref_i);
constexpr auto m25 = make_matrix_fn(3_CS, 2_RS, fn);
auto m26 = make_matrix_fn(3_CD, 2_RS, fn);
auto m27 = make_matrix_fn(3_CS, 2_RD, fn);
auto m28 = make_matrix_fn(3_CD, 2_RD, fn);
constexpr auto m29 = make_matrix_fn(dim_pair(3_CS, 2_RS), fn);
auto m30 = make_matrix_fn(dim_pair(3_CD, 2_RS), fn);
auto m31 = make_matrix_fn(dim_pair(3_CS, 2_RD), fn);
auto m32 = make_matrix_fn(dim_pair(3_CD, 2_RD), fn);
constexpr auto m33 = make_matrix_i(3_CS, 2_RS, init_p);
auto m34 = make_matrix_i(3_CD, 2_RS, init_p);
auto m35 = make_matrix_i(3_CS, 2_RD, init_p);
auto m36 = make_matrix_i(3_CD, 2_RD, init_p);
constexpr auto m37 = make_matrix_i(dim_pair(3_CS, 2_RS), init_p);
auto m38 = make_matrix_i(dim_pair(3_CD, 2_RS), init_p);
auto m39 = make_matrix_i(dim_pair(3_CS, 2_RD), init_p);
auto m40 = make_matrix_i(dim_pair(3_CD, 2_RD), init_p);
constexpr auto m41 = make_matrix< T >({{0, 1, 2}, {3, 4, 5}});
constexpr auto m42 = make_matrix(ref_i);
constexpr auto m43 = make_matrix(
{{T(0), T(1), T(2)}, {T(3), T(4), T(5)}});
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m18) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m19) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m22) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m23) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m24) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m26) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m27) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m28) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m29) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m30) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m31) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m32) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m34) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m35) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m36) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m37) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m38) == id< std_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m39) == id< std_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m40) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m41) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m42) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m43) == id< std_matrix< T, 3_C, 2_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_0));
BOOST_TEST(check(m08, ref_0));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_v));
BOOST_TEST(check(m14, ref_v));
BOOST_TEST(check(m15, ref_v));
BOOST_TEST(check(m16, ref_v));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_i));
BOOST_TEST(check(m22, ref_i));
BOOST_TEST(check(m23, ref_i));
BOOST_TEST(check(m24, ref_i));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_f));
BOOST_TEST(check(m28, ref_f));
BOOST_TEST(check(m29, ref_f));
BOOST_TEST(check(m30, ref_f));
BOOST_TEST(check(m31, ref_f));
BOOST_TEST(check(m32, ref_f));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m36, ref_i));
BOOST_TEST(check(m37, ref_i));
BOOST_TEST(check(m38, ref_i));
BOOST_TEST(check(m39, ref_i));
BOOST_TEST(check(m40, ref_i));
BOOST_TEST(check(m41, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_1x3, T, types){
constexpr T ref_0[3][1] = {{0}, {0}, {0}};
constexpr T ref_v[3][1] = {{7}, {7}, {7}};
constexpr T ref_i[3][1] = {{0}, {1}, {2}};
constexpr T ref_i_vec[3] = {0, 1, 2};
static constexpr T init_i[3] = {0, 1, 2};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][1] = {{0}, {10}, {20}};
constexpr auto fn_xy = fn_xy_t< T >();
constexpr auto fn_i = fn_x_t< T >();
constexpr auto m01 = make_matrix_v< T >(1_CS, 3_RS);
auto m02 = make_vector_v< T >(3_RS);
auto m03 = make_matrix_v< T >(1_CS, 3_RD);
auto m04 = make_vector_v< T >(3_RD);
constexpr auto m05 = make_matrix_v< T >(dim_pair(1_CS, 3_RS));
auto m06 = make_matrix_v< T >(dim_pair(1_CS, 3_RD));
constexpr auto m07 = make_matrix_v(1_CS, 3_RS, T(7));
auto m08 = make_vector_v(3_RS, T(7));
auto m09 = make_matrix_v(1_CS, 3_RD, T(7));
auto m10 = make_vector_v(3_RD, T(7));
constexpr auto m11 = make_matrix_v(dim_pair(1_CS, 3_RS), T(7));
auto m12 = make_matrix_v(dim_pair(1_CS, 3_RD), T(7));
constexpr auto m13 = make_matrix< T >(1_CS, 3_RS, {{0}, {1}, {2}});
auto m14 = make_vector< T >(3_RS, {0, 1, 2});
auto m15 = make_matrix< T >(1_CS, 3_RD, {{0}, {1}, {2}});
auto m16 = make_vector< T >(3_RD, {0, 1, 2});
constexpr auto m17 = make_matrix(1_CS, 3_RS, ref_i);
auto m18 = make_vector(3_RS, ref_i_vec);
auto m19 = make_matrix(1_CS, 3_RD, ref_i);
auto m20 = make_vector(3_RD, ref_i_vec);
constexpr auto m21 = make_matrix_fn(1_CS, 3_RS, fn_xy);
auto m22 = make_vector_fn(3_RS, fn_i);
auto m23 = make_matrix_fn(1_CS, 3_RD, fn_xy);
auto m24 = make_vector_fn(3_RD, fn_i);
constexpr auto m25 = make_matrix_fn(dim_pair(1_CS, 3_RS), fn_xy);
auto m26 = make_matrix_fn(dim_pair(1_CS, 3_RD), fn_xy);
constexpr auto m27 = make_matrix_i(1_CS, 3_RS, init_p);
auto m28 = make_vector_i(3_RS, init_p);
auto m29 = make_matrix_i(1_CS, 3_RD, init_p);
auto m30 = make_vector_i(3_RD, init_p);
constexpr auto m31 = make_matrix_i(dim_pair(1_CS, 3_RS), init_p);
auto m32 = make_matrix_i(dim_pair(1_CS, 3_RD), init_p);
constexpr auto m33 = make_matrix< T >({{0}, {1}, {2}});
constexpr auto m34 = make_matrix(ref_i);
constexpr auto m35 = make_matrix({{T(0)}, {T(1)}, {T(2)}});
constexpr auto m42 = make_col_vector< T >({0, 1, 2});
constexpr auto m43 = make_col_vector(ref_i_vec);
constexpr auto m44 = make_col_vector({T(0), T(1), T(2)});
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m18) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m19) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m22) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m23) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m24) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m26) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m27) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m28) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m29) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m30) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m31) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m32) == id< std_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m34) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m35) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m42) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m43) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m44) == id< std_matrix< T, 1_C, 3_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_v));
BOOST_TEST(check(m08, ref_v));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
BOOST_TEST(check(m16, ref_i));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_f));
BOOST_TEST(check(m22, ref_f));
BOOST_TEST(check(m23, ref_f));
BOOST_TEST(check(m24, ref_f));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_i));
BOOST_TEST(check(m28, ref_i));
BOOST_TEST(check(m29, ref_i));
BOOST_TEST(check(m30, ref_i));
BOOST_TEST(check(m31, ref_i));
BOOST_TEST(check(m32, ref_i));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
BOOST_TEST(check(m44, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_3x1, T, types){
constexpr T ref_0[1][3] = {{0, 0, 0}};
constexpr T ref_v[1][3] = {{7, 7, 7}};
constexpr T ref_i[1][3] = {{0, 1, 2}};
constexpr T ref_i_vec[3] = {0, 1, 2};
static constexpr T init_i[3] = {0, 1, 2};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[1][3] = {{0, 1, 2}};
constexpr auto fn_xy = fn_xy_t< T >();
constexpr auto fn_i = fn_y_t< T >();
constexpr auto m01 = make_matrix_v< T >(3_CS, 1_RS);
auto m02 = make_vector_v< T >(3_CS);
auto m03 = make_matrix_v< T >(3_CD, 1_RS);
auto m04 = make_vector_v< T >(3_CD);
constexpr auto m05 = make_matrix_v< T >(dim_pair(3_CS, 1_RS));
auto m06 = make_matrix_v< T >(dim_pair(3_CD, 1_RS));
constexpr auto m07 = make_matrix_v(3_CS, 1_RS, T(7));
auto m08 = make_vector_v(3_CS, T(7));
auto m09 = make_matrix_v(3_CD, 1_RS, T(7));
auto m10 = make_vector_v(3_CD, T(7));
constexpr auto m11 = make_matrix_v(dim_pair(3_CS, 1_RS), T(7));
auto m12 = make_matrix_v(dim_pair(3_CD, 1_RS), T(7));
constexpr auto m13 = make_matrix< T >(3_CS, 1_RS, {{0, 1, 2}});
auto m14 = make_vector< T >(3_CS, {0, 1, 2});
auto m15 = make_matrix< T >(3_CD, 1_RS, {{0, 1, 2}});
auto m16 = make_vector< T >(3_CD, {0, 1, 2});
constexpr auto m17 = make_matrix(3_CS, 1_RS, ref_i);
auto m18 = make_vector(3_CS, ref_i_vec);
auto m19 = make_matrix(3_CD, 1_RS, ref_i);
auto m20 = make_vector(3_CD, ref_i_vec);
constexpr auto m21 = make_matrix_fn(3_CS, 1_RS, fn_xy);
auto m22 = make_vector_fn(3_CS, fn_i);
auto m23 = make_matrix_fn(3_CD, 1_RS, fn_xy);
auto m24 = make_vector_fn(3_CD, fn_i);
constexpr auto m25 = make_matrix_fn(dim_pair(3_CS, 1_RS), fn_xy);
auto m26 = make_matrix_fn(dim_pair(3_CD, 1_RS), fn_xy);
constexpr auto m27 = make_matrix_i(3_CS, 1_RS, init_p);
auto m28 = make_vector_i(3_CS, init_p);
auto m29 = make_matrix_i(3_CD, 1_RS, init_p);
auto m30 = make_vector_i(3_CD, init_p);
constexpr auto m31 = make_matrix_i(dim_pair(3_CS, 1_RS), init_p);
auto m32 = make_matrix_i(dim_pair(3_CD, 1_RS), init_p);
constexpr auto m33 = make_matrix< T >({{0, 1, 2}});
constexpr auto m34 = make_matrix(ref_i);
constexpr auto m35 = make_matrix({{T(0), T(1), T(2)}});
constexpr auto m42 = make_row_vector< T >({0, 1, 2});
constexpr auto m43 = make_row_vector(ref_i_vec);
constexpr auto m44 = make_row_vector({T(0), T(1), T(2)});
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m16) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m17) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m18) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m19) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m20) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m21) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m22) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m23) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m24) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m25) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m26) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m27) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m28) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m29) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m30) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m31) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m32) == id< std_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m33) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m34) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m35) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m42) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m43) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m44) == id< std_matrix< T, 3_C, 1_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_v));
BOOST_TEST(check(m08, ref_v));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
BOOST_TEST(check(m16, ref_i));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_f));
BOOST_TEST(check(m22, ref_f));
BOOST_TEST(check(m23, ref_f));
BOOST_TEST(check(m24, ref_f));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_i));
BOOST_TEST(check(m28, ref_i));
BOOST_TEST(check(m29, ref_i));
BOOST_TEST(check(m30, ref_i));
BOOST_TEST(check(m31, ref_i));
BOOST_TEST(check(m32, ref_i));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
BOOST_TEST(check(m44, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_std_matrix_1x1, T, types){
constexpr T ref_0[1][1] = {{0}};
constexpr T ref_v[1][1] = {{7}};
constexpr T ref_i[1][1] = {{0}};
constexpr T ref_i_vec[1] = {0};
static constexpr T init_i[1] = {0};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[1][1] = {{0}};
constexpr auto fn_xy = fn_xy_t< T >();
constexpr auto fn_x = fn_x_t< T >();
constexpr auto fn_y = fn_y_t< T >();
constexpr auto m01 = make_matrix_v< T >(1_CS, 1_RS);
auto m02 = make_vector_v< T >(1_CS);
auto m03 = make_vector_v< T >(1_RS);
constexpr auto m04 = make_matrix_v< T >(dim_pair(1_CS, 1_RS));
constexpr auto m05 = make_matrix_v< T >(1_DS);
constexpr auto m06 = make_matrix_v(1_CS, 1_RS, T(7));
auto m07 = make_vector_v(1_CS, T(7));
auto m08 = make_vector_v(1_RS, T(7));
constexpr auto m09 = make_matrix_v(dim_pair(1_CS, 1_RS), T(7));
constexpr auto m10 = make_matrix_v(1_DS, T(7));
constexpr auto m11 = make_matrix< T >(1_CS, 1_RS, {{0}});
auto m12 = make_vector< T >(1_CS, {0});
auto m13 = make_vector< T >(1_RS, {0});
constexpr auto m14 = make_matrix< T >(1_DS, {{0}});
constexpr auto m15 = make_matrix(1_CS, 1_RS, ref_i);
auto m16 = make_vector(1_CS, ref_i_vec);
auto m17 = make_vector(1_RS, ref_i_vec);
constexpr auto m18 = make_matrix(1_DS, ref_i);
constexpr auto m19 = make_matrix_fn(1_CS, 1_RS, fn_xy);
auto m20 = make_vector_fn(1_CS, fn_x);
auto m21 = make_vector_fn(1_RS, fn_y);
constexpr auto m22 = make_matrix_fn(dim_pair(1_CS, 1_RS), fn_xy);
constexpr auto m23 = make_matrix_fn(1_DS, fn_xy);
constexpr auto m24 = make_matrix_i(1_CS, 1_RS, init_p);
auto m25 = make_vector_i(1_CS, init_p);
auto m26 = make_vector_i(1_RS, init_p);
constexpr auto m27 = make_matrix_i(dim_pair(1_CS, 1_RS), init_p);
constexpr auto m28 = make_matrix_i(1_DS, init_p);
constexpr auto m29 = make_matrix< T >({{0}});
constexpr auto m30 = make_matrix(ref_i);
constexpr auto m31 = make_matrix({{T(0)}});
constexpr auto m35 = make_col_vector< T >({0});
constexpr auto m36 = make_col_vector(ref_i_vec);
constexpr auto m37 = make_col_vector({T(0)});
constexpr auto m41 = make_row_vector< T >({0});
constexpr auto m42 = make_row_vector(ref_i_vec);
constexpr auto m43 = make_row_vector({T(0)});
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m16) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m17) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m18) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m19) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m20) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m21) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m22) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m23) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m24) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m25) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m26) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m27) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m28) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m29) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m30) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m31) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m35) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m36) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m37) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m41) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m42) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m43) == id< std_matrix< T, 1_C, 1_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_v));
BOOST_TEST(check(m07, ref_v));
BOOST_TEST(check(m08, ref_v));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_i));
BOOST_TEST(check(m12, ref_i));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
BOOST_TEST(check(m16, ref_i));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_f));
BOOST_TEST(check(m20, ref_f));
BOOST_TEST(check(m21, ref_f));
BOOST_TEST(check(m22, ref_f));
BOOST_TEST(check(m23, ref_f));
BOOST_TEST(check(m24, ref_i));
BOOST_TEST(check(m25, ref_i));
BOOST_TEST(check(m26, ref_i));
BOOST_TEST(check(m27, ref_i));
BOOST_TEST(check(m28, ref_i));
BOOST_TEST(check(m29, ref_i));
BOOST_TEST(check(m30, ref_i));
BOOST_TEST(check(m31, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m36, ref_i));
BOOST_TEST(check(m37, ref_i));
BOOST_TEST(check(m41, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_diag_matrix, T, types){
constexpr T ref_0[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
constexpr T ref_v[3][3] = {{7, 0, 0}, {0, 7, 0}, {0, 0, 7}};
constexpr T ref_i[3][3] = {{0, 0, 0}, {0, 1, 0}, {0, 0, 2}};
constexpr T ref_i_vec[3] = {0, 1, 2};
static constexpr T init_i[3] = {0, 1, 2};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][3] = {{0, 0, 0}, {0, 11, 0}, {0, 0, 22}};
constexpr auto fn = fn_i_t< T >();
constexpr auto m01 = make_diag_matrix_v< T >(3_DS);
auto m02 = make_diag_matrix_v< T >(3_DD);
constexpr auto m03 = make_diag_matrix_v(3_DS, T(7));
auto m04 = make_diag_matrix_v(3_DD, T(7));
constexpr auto m05 = make_diag_matrix< T >(3_DS, {0, 1, 2});
auto m06 = make_diag_matrix< T >(3_DD, {0, 1, 2});
constexpr auto m07 = make_diag_matrix(3_DS, ref_i_vec);
auto m08 = make_diag_matrix(3_DD, ref_i_vec);
constexpr auto m09 = make_diag_matrix_fn(3_DS, fn);
auto m10 = make_diag_matrix_fn(3_DD, fn);
constexpr auto m11 = make_diag_matrix_i(3_DS, init_p);
auto m12 = make_diag_matrix_i(3_DD, init_p);
constexpr auto m13 = make_diag_matrix< T >({0, 1, 2});
constexpr auto m14 = make_diag_matrix({T(0), T(1), T(2)});
constexpr auto m15 = make_diag_matrix(ref_i_vec);
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m07) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m08) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m10) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m11) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m12) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_v));
BOOST_TEST(check(m04, ref_v));
BOOST_TEST(check(m05, ref_i));
BOOST_TEST(check(m06, ref_i));
BOOST_TEST(check(m07, ref_i));
BOOST_TEST(check(m08, ref_i));
BOOST_TEST(check(m09, ref_f));
BOOST_TEST(check(m10, ref_f));
BOOST_TEST(check(m11, ref_i));
BOOST_TEST(check(m12, ref_i));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_identity_matrix, T, types){
constexpr T ref_i[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
constexpr auto m01 = make_identity_matrix< T >(3_DS);
auto m02 = make_identity_matrix< T >(3_DD);
BOOST_TEST((rt_id(m01) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m01, ref_i));
BOOST_TEST(check(m02, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_copy_constructor, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
constexpr auto m01 = make_matrix(3_CS, 3_RS, ref_i);
auto m02 = make_matrix(3_CD, 3_RD, ref_i);
constexpr auto m03 = m01;
auto m04 = m02;
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_move_constructor, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
constexpr auto m01 = make_matrix(3_CS, 3_RS, ref_i);
auto m02 = make_matrix(3_CD, 3_RD, ref_i);
constexpr auto m03 = std::move(m01);
auto m04 = std::move(m02);
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_copy_assignment, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
constexpr auto m01 = make_matrix(3_CS, 3_RS, ref_i);
auto m02 = make_matrix(3_CD, 3_RD, ref_i);
auto m03 = make_matrix_v< T >(3_CS, 3_RS);
auto m04 = make_matrix_v< T >(0_CD, 0_RD); // also assign dimensions
m03 = m01;
m04 = m02;
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_move_assignment, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
constexpr auto m01 = make_matrix(3_CS, 3_RS, ref_i);
auto m02 = make_matrix(3_CD, 3_RD, ref_i);
auto m03 = make_matrix_v< T >(3_CS, 3_RS);
auto m04 = make_matrix_v< T >(0_CD, 0_RD); // also move dimensions
m03 = std::move(m01);
m04 = std::move(m02);
BOOST_TEST((rt_id(m03) == id< std_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< std_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_heap_matrix_3x3, T, types){
constexpr T ref_0[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
constexpr T ref_v[3][3] = {{7, 7, 7}, {7, 7, 7}, {7, 7, 7}};
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
static constexpr T init_i[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][3] = {{0, 1, 2}, {10, 11, 12}, {20, 21, 22}};
constexpr auto fn = fn_xy_t< T >();
auto m01 = make_matrix_v< T >(3_CS, 3_RS, T(), maker::heap);
auto m02 = make_matrix_v< T >(3_CD, 3_RS, T(), maker::heap);
auto m03 = make_matrix_v< T >(3_CS, 3_RD, T(), maker::heap);
auto m04 = make_matrix_v< T >(3_CD, 3_RD, T(), maker::heap);
auto m05 = make_matrix_v< T >(dim_pair(3_CS, 3_RS), T(), maker::heap);
auto m06 = make_matrix_v< T >(dim_pair(3_CD, 3_RS), T(), maker::heap);
auto m07 = make_matrix_v< T >(dim_pair(3_CS, 3_RD), T(), maker::heap);
auto m08 = make_matrix_v< T >(dim_pair(3_CD, 3_RD), T(), maker::heap);
auto m09 = make_matrix_v< T >(3_DS, T(), maker::heap);
auto m10 = make_matrix_v< T >(3_DD, T(), maker::heap);
auto m11 = make_matrix_v< T >(dim_pair(3_DS), T(), maker::heap);
auto m12 = make_matrix_v< T >(dim_pair(3_DD), T(), maker::heap);
auto m13 = make_matrix_v(3_CS, 3_RS, T(7), maker::heap);
auto m14 = make_matrix_v(3_CD, 3_RS, T(7), maker::heap);
auto m15 = make_matrix_v(3_CS, 3_RD, T(7), maker::heap);
auto m16 = make_matrix_v(3_CD, 3_RD, T(7), maker::heap);
auto m17 = make_matrix_v(dim_pair(3_CS, 3_RS), T(7), maker::heap);
auto m18 = make_matrix_v(dim_pair(3_CD, 3_RS), T(7), maker::heap);
auto m19 = make_matrix_v(dim_pair(3_CS, 3_RD), T(7), maker::heap);
auto m20 = make_matrix_v(dim_pair(3_CD, 3_RD), T(7), maker::heap);
auto m21 = make_matrix_v(3_DS, T(7), maker::heap);
auto m22 = make_matrix_v(3_DD, T(7), maker::heap);
auto m23 = make_matrix_v(dim_pair(3_DS), T(7), maker::heap);
auto m24 = make_matrix_v(dim_pair(3_DD), T(7), maker::heap);
auto m25 = make_matrix< T >
(3_CS, 3_RS, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m26 = make_matrix< T >
(3_CD, 3_RS, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m27 = make_matrix< T >
(3_CS, 3_RD, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m28 = make_matrix< T >
(3_CD, 3_RD, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m29 = make_matrix(3_CS, 3_RS, ref_i, maker::heap);
auto m30 = make_matrix(3_CD, 3_RS, ref_i, maker::heap);
auto m31 = make_matrix(3_CS, 3_RD, ref_i, maker::heap);
auto m32 = make_matrix(3_CD, 3_RD, ref_i, maker::heap);
auto m33 = make_matrix< T >
(3_DS, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m34 = make_matrix< T >
(3_DD, {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m35 = make_matrix(3_DS, ref_i, maker::heap);
auto m36 = make_matrix(3_DD, ref_i, maker::heap);
auto m37 = make_matrix_fn(3_CS, 3_RS, fn, maker::heap);
auto m38 = make_matrix_fn(3_CD, 3_RS, fn, maker::heap);
auto m39 = make_matrix_fn(3_CS, 3_RD, fn, maker::heap);
auto m40 = make_matrix_fn(3_CD, 3_RD, fn, maker::heap);
auto m41 = make_matrix_fn(dim_pair(3_CS, 3_RS), fn, maker::heap);
auto m42 = make_matrix_fn(dim_pair(3_CD, 3_RS), fn, maker::heap);
auto m43 = make_matrix_fn(dim_pair(3_CS, 3_RD), fn, maker::heap);
auto m44 = make_matrix_fn(dim_pair(3_CD, 3_RD), fn, maker::heap);
auto m45 = make_matrix_fn(3_DS, fn, maker::heap);
auto m46 = make_matrix_fn(3_DD, fn, maker::heap);
auto m47 = make_matrix_fn(dim_pair(3_DS), fn, maker::heap);
auto m48 = make_matrix_fn(dim_pair(3_DD), fn, maker::heap);
auto m49 = make_matrix_i(3_CS, 3_RS, init_p, maker::heap);
auto m50 = make_matrix_i(3_CD, 3_RS, init_p, maker::heap);
auto m51 = make_matrix_i(3_CS, 3_RD, init_p, maker::heap);
auto m52 = make_matrix_i(3_CD, 3_RD, init_p, maker::heap);
auto m53 = make_matrix_i(dim_pair(3_CS, 3_RS), init_p, maker::heap);
auto m54 = make_matrix_i(dim_pair(3_CD, 3_RS), init_p, maker::heap);
auto m55 = make_matrix_i(dim_pair(3_CS, 3_RD), init_p, maker::heap);
auto m56 = make_matrix_i(dim_pair(3_CD, 3_RD), init_p, maker::heap);
auto m57 = make_matrix_i(3_DS, init_p, maker::heap);
auto m58 = make_matrix_i(3_DD, init_p, maker::heap);
auto m59 = make_matrix_i(dim_pair(3_DS), init_p, maker::heap);
auto m60 = make_matrix_i(dim_pair(3_DD), init_p, maker::heap);
auto m61 = make_matrix< T >({{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}, maker::heap);
auto m62 = make_matrix(ref_i, maker::heap);
auto m63 = make_matrix(
{{T(0), T(1), T(2)}, {T(3), T(4), T(5)}, {T(6), T(7), T(8)}},
maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m18) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m19) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m22) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m23) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m24) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m26) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m27) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m28) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m29) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m30) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m31) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m32) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m34) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m35) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m36) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m37) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m38) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m39) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m40) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m41) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m42) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m43) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m44) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m45) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m46) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m47) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m48) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m49) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m50) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m51) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m52) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m53) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m54) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m55) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m56) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m57) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m58) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m59) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m60) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m61) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m62) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m63) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((check(m01, ref_0)));
BOOST_TEST((check(m02, ref_0)));
BOOST_TEST((check(m03, ref_0)));
BOOST_TEST((check(m04, ref_0)));
BOOST_TEST((check(m05, ref_0)));
BOOST_TEST((check(m06, ref_0)));
BOOST_TEST((check(m07, ref_0)));
BOOST_TEST((check(m08, ref_0)));
BOOST_TEST((check(m09, ref_0)));
BOOST_TEST((check(m10, ref_0)));
BOOST_TEST((check(m11, ref_0)));
BOOST_TEST((check(m12, ref_0)));
BOOST_TEST((check(m13, ref_v)));
BOOST_TEST((check(m14, ref_v)));
BOOST_TEST((check(m15, ref_v)));
BOOST_TEST((check(m16, ref_v)));
BOOST_TEST((check(m17, ref_v)));
BOOST_TEST((check(m18, ref_v)));
BOOST_TEST((check(m19, ref_v)));
BOOST_TEST((check(m20, ref_v)));
BOOST_TEST((check(m21, ref_v)));
BOOST_TEST((check(m22, ref_v)));
BOOST_TEST((check(m23, ref_v)));
BOOST_TEST((check(m24, ref_v)));
BOOST_TEST((check(m25, ref_i)));
BOOST_TEST((check(m26, ref_i)));
BOOST_TEST((check(m27, ref_i)));
BOOST_TEST((check(m28, ref_i)));
BOOST_TEST((check(m29, ref_i)));
BOOST_TEST((check(m30, ref_i)));
BOOST_TEST((check(m31, ref_i)));
BOOST_TEST((check(m32, ref_i)));
BOOST_TEST((check(m33, ref_i)));
BOOST_TEST((check(m34, ref_i)));
BOOST_TEST((check(m35, ref_i)));
BOOST_TEST((check(m36, ref_i)));
BOOST_TEST((check(m37, ref_f)));
BOOST_TEST((check(m38, ref_f)));
BOOST_TEST((check(m39, ref_f)));
BOOST_TEST((check(m40, ref_f)));
BOOST_TEST((check(m41, ref_f)));
BOOST_TEST((check(m42, ref_f)));
BOOST_TEST((check(m43, ref_f)));
BOOST_TEST((check(m44, ref_f)));
BOOST_TEST((check(m45, ref_f)));
BOOST_TEST((check(m46, ref_f)));
BOOST_TEST((check(m47, ref_f)));
BOOST_TEST((check(m48, ref_f)));
BOOST_TEST((check(m49, ref_i)));
BOOST_TEST((check(m50, ref_i)));
BOOST_TEST((check(m51, ref_i)));
BOOST_TEST((check(m52, ref_i)));
BOOST_TEST((check(m53, ref_i)));
BOOST_TEST((check(m54, ref_i)));
BOOST_TEST((check(m55, ref_i)));
BOOST_TEST((check(m56, ref_i)));
BOOST_TEST((check(m57, ref_i)));
BOOST_TEST((check(m58, ref_i)));
BOOST_TEST((check(m59, ref_i)));
BOOST_TEST((check(m60, ref_i)));
BOOST_TEST((check(m61, ref_i)));
BOOST_TEST((check(m62, ref_i)));
BOOST_TEST((check(m63, ref_i)));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_heap_matrix_2x3, T, types){
constexpr T ref_0[3][2] = {{0, 0}, {0, 0}, {0, 0}};
constexpr T ref_v[3][2] = {{7, 7}, {7, 7}, {7, 7}};
constexpr T ref_i[3][2] = {{0, 1}, {2, 3}, {4, 5}};
static constexpr T init_i[6] = {0, 1, 2, 3, 4, 5};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][2] = {{0, 1}, {10, 11}, {20, 21}};
constexpr auto fn = fn_xy_t< T >();
auto m01 = make_matrix_v< T >(2_CS, 3_RS, T(), maker::heap);
auto m02 = make_matrix_v< T >(2_CD, 3_RS, T(), maker::heap);
auto m03 = make_matrix_v< T >(2_CS, 3_RD, T(), maker::heap);
auto m04 = make_matrix_v< T >(2_CD, 3_RD, T(), maker::heap);
auto m05 = make_matrix_v< T >(dim_pair(2_CS, 3_RS), T(), maker::heap);
auto m06 = make_matrix_v< T >(dim_pair(2_CD, 3_RS), T(), maker::heap);
auto m07 = make_matrix_v< T >(dim_pair(2_CS, 3_RD), T(), maker::heap);
auto m08 = make_matrix_v< T >(dim_pair(2_CD, 3_RD), T(), maker::heap);
auto m09 = make_matrix_v(2_CS, 3_RS, T(7), maker::heap);
auto m10 = make_matrix_v(2_CD, 3_RS, T(7), maker::heap);
auto m11 = make_matrix_v(2_CS, 3_RD, T(7), maker::heap);
auto m12 = make_matrix_v(2_CD, 3_RD, T(7), maker::heap);
auto m13 = make_matrix_v(dim_pair(2_CS, 3_RS), T(7), maker::heap);
auto m14 = make_matrix_v(dim_pair(2_CD, 3_RS), T(7), maker::heap);
auto m15 = make_matrix_v(dim_pair(2_CS, 3_RD), T(7), maker::heap);
auto m16 = make_matrix_v(dim_pair(2_CD, 3_RD), T(7), maker::heap);
auto m17 = make_matrix< T >(2_CS, 3_RS, {{0, 1}, {2, 3}, {4, 5}},
maker::heap);
auto m18 = make_matrix< T >(2_CD, 3_RS, {{0, 1}, {2, 3}, {4, 5}},
maker::heap);
auto m19 = make_matrix< T >(2_CS, 3_RD, {{0, 1}, {2, 3}, {4, 5}},
maker::heap);
auto m20 = make_matrix< T >(2_CD, 3_RD, {{0, 1}, {2, 3}, {4, 5}},
maker::heap);
auto m21 = make_matrix(2_CS, 3_RS, ref_i, maker::heap);
auto m22 = make_matrix(2_CD, 3_RS, ref_i, maker::heap);
auto m23 = make_matrix(2_CS, 3_RD, ref_i, maker::heap);
auto m24 = make_matrix(2_CD, 3_RD, ref_i, maker::heap);
auto m25 = make_matrix_fn(2_CS, 3_RS, fn, maker::heap);
auto m26 = make_matrix_fn(2_CD, 3_RS, fn, maker::heap);
auto m27 = make_matrix_fn(2_CS, 3_RD, fn, maker::heap);
auto m28 = make_matrix_fn(2_CD, 3_RD, fn, maker::heap);
auto m29 = make_matrix_fn(dim_pair(2_CS, 3_RS), fn, maker::heap);
auto m30 = make_matrix_fn(dim_pair(2_CD, 3_RS), fn, maker::heap);
auto m31 = make_matrix_fn(dim_pair(2_CS, 3_RD), fn, maker::heap);
auto m32 = make_matrix_fn(dim_pair(2_CD, 3_RD), fn, maker::heap);
auto m33 = make_matrix_i(2_CS, 3_RS, init_p, maker::heap);
auto m34 = make_matrix_i(2_CD, 3_RS, init_p, maker::heap);
auto m35 = make_matrix_i(2_CS, 3_RD, init_p, maker::heap);
auto m36 = make_matrix_i(2_CD, 3_RD, init_p, maker::heap);
auto m37 = make_matrix_i(dim_pair(2_CS, 3_RS), init_p, maker::heap);
auto m38 = make_matrix_i(dim_pair(2_CD, 3_RS), init_p, maker::heap);
auto m39 = make_matrix_i(dim_pair(2_CS, 3_RD), init_p, maker::heap);
auto m40 = make_matrix_i(dim_pair(2_CD, 3_RD), init_p, maker::heap);
auto m41 = make_matrix< T >({{0, 1}, {2, 3}, {4, 5}}, maker::heap);
auto m42 = make_matrix(ref_i, maker::heap);
auto m43 = make_matrix(
{{T(0), T(1)}, {T(2), T(3)}, {T(4), T(5)}}, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m18) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m19) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m22) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m23) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m24) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m26) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m27) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m28) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m29) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m30) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m31) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m32) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m34) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m35) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m36) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m37) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m38) == id< heap_matrix< T, 0_C, 3_R > >));
BOOST_TEST((rt_id(m39) == id< heap_matrix< T, 2_C, 0_R > >));
BOOST_TEST((rt_id(m40) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m41) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m42) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST((rt_id(m43) == id< heap_matrix< T, 2_C, 3_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_0));
BOOST_TEST(check(m08, ref_0));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_v));
BOOST_TEST(check(m14, ref_v));
BOOST_TEST(check(m15, ref_v));
BOOST_TEST(check(m16, ref_v));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_i));
BOOST_TEST(check(m22, ref_i));
BOOST_TEST(check(m23, ref_i));
BOOST_TEST(check(m24, ref_i));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_f));
BOOST_TEST(check(m28, ref_f));
BOOST_TEST(check(m29, ref_f));
BOOST_TEST(check(m30, ref_f));
BOOST_TEST(check(m31, ref_f));
BOOST_TEST(check(m32, ref_f));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m36, ref_i));
BOOST_TEST(check(m37, ref_i));
BOOST_TEST(check(m38, ref_i));
BOOST_TEST(check(m39, ref_i));
BOOST_TEST(check(m40, ref_i));
BOOST_TEST(check(m41, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_heap_matrix_3x2, T, types){
constexpr T ref_0[2][3] = {{0, 0, 0}, {0, 0, 0}};
constexpr T ref_v[2][3] = {{7, 7, 7}, {7, 7, 7}};
constexpr T ref_i[2][3] = {{0, 1, 2}, {3, 4, 5}};
static constexpr T init_i[6] = {0, 1, 2, 3, 4, 5};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[2][3] = {{0, 1, 2}, {10, 11, 12}};
constexpr auto fn = fn_xy_t< T >();
auto m01 = make_matrix_v< T >(3_CS, 2_RS, T(), maker::heap);
auto m02 = make_matrix_v< T >(3_CD, 2_RS, T(), maker::heap);
auto m03 = make_matrix_v< T >(3_CS, 2_RD, T(), maker::heap);
auto m04 = make_matrix_v< T >(3_CD, 2_RD, T(), maker::heap);
auto m05 = make_matrix_v< T >(dim_pair(3_CS, 2_RS), T(), maker::heap);
auto m06 = make_matrix_v< T >(dim_pair(3_CD, 2_RS), T(), maker::heap);
auto m07 = make_matrix_v< T >(dim_pair(3_CS, 2_RD), T(), maker::heap);
auto m08 = make_matrix_v< T >(dim_pair(3_CD, 2_RD), T(), maker::heap);
auto m09 = make_matrix_v(3_CS, 2_RS, T(7), maker::heap);
auto m10 = make_matrix_v(3_CD, 2_RS, T(7), maker::heap);
auto m11 = make_matrix_v(3_CS, 2_RD, T(7), maker::heap);
auto m12 = make_matrix_v(3_CD, 2_RD, T(7), maker::heap);
auto m13 = make_matrix_v(dim_pair(3_CS, 2_RS), T(7), maker::heap);
auto m14 = make_matrix_v(dim_pair(3_CD, 2_RS), T(7), maker::heap);
auto m15 = make_matrix_v(dim_pair(3_CS, 2_RD), T(7), maker::heap);
auto m16 = make_matrix_v(dim_pair(3_CD, 2_RD), T(7), maker::heap);
auto m17 = make_matrix< T >
(3_CS, 2_RS, {{0, 1, 2}, {3, 4, 5}}, maker::heap);
auto m18 = make_matrix< T >
(3_CD, 2_RS, {{0, 1, 2}, {3, 4, 5}}, maker::heap);
auto m19 = make_matrix< T >
(3_CS, 2_RD, {{0, 1, 2}, {3, 4, 5}}, maker::heap);
auto m20 = make_matrix< T >
(3_CD, 2_RD, {{0, 1, 2}, {3, 4, 5}}, maker::heap);
auto m21 = make_matrix(3_CS, 2_RS, ref_i, maker::heap);
auto m22 = make_matrix(3_CD, 2_RS, ref_i, maker::heap);
auto m23 = make_matrix(3_CS, 2_RD, ref_i, maker::heap);
auto m24 = make_matrix(3_CD, 2_RD, ref_i, maker::heap);
auto m25 = make_matrix_fn(3_CS, 2_RS, fn, maker::heap);
auto m26 = make_matrix_fn(3_CD, 2_RS, fn, maker::heap);
auto m27 = make_matrix_fn(3_CS, 2_RD, fn, maker::heap);
auto m28 = make_matrix_fn(3_CD, 2_RD, fn, maker::heap);
auto m29 = make_matrix_fn(dim_pair(3_CS, 2_RS), fn, maker::heap);
auto m30 = make_matrix_fn(dim_pair(3_CD, 2_RS), fn, maker::heap);
auto m31 = make_matrix_fn(dim_pair(3_CS, 2_RD), fn, maker::heap);
auto m32 = make_matrix_fn(dim_pair(3_CD, 2_RD), fn, maker::heap);
auto m33 = make_matrix_i(3_CS, 2_RS, init_p, maker::heap);
auto m34 = make_matrix_i(3_CD, 2_RS, init_p, maker::heap);
auto m35 = make_matrix_i(3_CS, 2_RD, init_p, maker::heap);
auto m36 = make_matrix_i(3_CD, 2_RD, init_p, maker::heap);
auto m37 = make_matrix_i(dim_pair(3_CS, 2_RS), init_p, maker::heap);
auto m38 = make_matrix_i(dim_pair(3_CD, 2_RS), init_p, maker::heap);
auto m39 = make_matrix_i(dim_pair(3_CS, 2_RD), init_p, maker::heap);
auto m40 = make_matrix_i(dim_pair(3_CD, 2_RD), init_p, maker::heap);
auto m41 = make_matrix< T >({{0, 1, 2}, {3, 4, 5}}, maker::heap);
auto m42 = make_matrix(ref_i, maker::heap);
auto m43 = make_matrix(
{{T(0), T(1), T(2)}, {T(3), T(4), T(5)}}, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m18) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m19) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m22) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m23) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m24) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m26) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m27) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m28) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m29) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m30) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m31) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m32) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m34) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m35) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m36) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m37) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m38) == id< heap_matrix< T, 0_C, 2_R > >));
BOOST_TEST((rt_id(m39) == id< heap_matrix< T, 3_C, 0_R > >));
BOOST_TEST((rt_id(m40) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m41) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m42) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST((rt_id(m43) == id< heap_matrix< T, 3_C, 2_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_0));
BOOST_TEST(check(m08, ref_0));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_v));
BOOST_TEST(check(m14, ref_v));
BOOST_TEST(check(m15, ref_v));
BOOST_TEST(check(m16, ref_v));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_i));
BOOST_TEST(check(m22, ref_i));
BOOST_TEST(check(m23, ref_i));
BOOST_TEST(check(m24, ref_i));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_f));
BOOST_TEST(check(m28, ref_f));
BOOST_TEST(check(m29, ref_f));
BOOST_TEST(check(m30, ref_f));
BOOST_TEST(check(m31, ref_f));
BOOST_TEST(check(m32, ref_f));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m36, ref_i));
BOOST_TEST(check(m37, ref_i));
BOOST_TEST(check(m38, ref_i));
BOOST_TEST(check(m39, ref_i));
BOOST_TEST(check(m40, ref_i));
BOOST_TEST(check(m41, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_heap_matrix_1x3, T, types){
constexpr T ref_0[3][1] = {{0}, {0}, {0}};
constexpr T ref_v[3][1] = {{7}, {7}, {7}};
constexpr T ref_i[3][1] = {{0}, {1}, {2}};
constexpr T ref_i_vec[3] = {0, 1, 2};
static constexpr T init_i[3] = {0, 1, 2};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][1] = {{0}, {10}, {20}};
constexpr auto fn_xy = fn_xy_t< T >();
constexpr auto fn_i = fn_x_t< T >();
auto m01 = make_matrix_v< T >(1_CS, 3_RS, T(), maker::heap);
auto m02 = make_vector_v< T >(3_RS, T(), maker::heap);
auto m03 = make_matrix_v< T >(1_CS, 3_RD, T(), maker::heap);
auto m04 = make_vector_v< T >(3_RD, T(), maker::heap);
auto m05 = make_matrix_v< T >(dim_pair(1_CS, 3_RS), T(), maker::heap);
auto m06 = make_matrix_v< T >(dim_pair(1_CS, 3_RD), T(), maker::heap);
auto m07 = make_matrix_v(1_CS, 3_RS, T(7), maker::heap);
auto m08 = make_vector_v(3_RS, T(7), maker::heap);
auto m09 = make_matrix_v(1_CS, 3_RD, T(7), maker::heap);
auto m10 = make_vector_v(3_RD, T(7), maker::heap);
auto m11 = make_matrix_v(dim_pair(1_CS, 3_RS), T(7), maker::heap);
auto m12 = make_matrix_v(dim_pair(1_CS, 3_RD), T(7), maker::heap);
auto m13 = make_matrix< T >(1_CS, 3_RS, {{0}, {1}, {2}}, maker::heap);
auto m14 = make_vector< T >(3_RS, {0, 1, 2}, maker::heap);
auto m15 = make_matrix< T >(1_CS, 3_RD, {{0}, {1}, {2}}, maker::heap);
auto m16 = make_vector< T >(3_RD, {0, 1, 2}, maker::heap);
auto m17 = make_matrix(1_CS, 3_RS, ref_i, maker::heap);
auto m18 = make_vector(3_RS, ref_i_vec, maker::heap);
auto m19 = make_matrix(1_CS, 3_RD, ref_i, maker::heap);
auto m20 = make_vector(3_RD, ref_i_vec, maker::heap);
auto m21 = make_matrix_fn(1_CS, 3_RS, fn_xy, maker::heap);
auto m22 = make_vector_fn(3_RS, fn_i, maker::heap);
auto m23 = make_matrix_fn(1_CS, 3_RD, fn_xy, maker::heap);
auto m24 = make_vector_fn(3_RD, fn_i, maker::heap);
auto m25 = make_matrix_fn(dim_pair(1_CS, 3_RS), fn_xy, maker::heap);
auto m26 = make_matrix_fn(dim_pair(1_CS, 3_RD), fn_xy, maker::heap);
auto m27 = make_matrix_i(1_CS, 3_RS, init_p, maker::heap);
auto m28 = make_vector_i(3_RS, init_p, maker::heap);
auto m29 = make_matrix_i(1_CS, 3_RD, init_p, maker::heap);
auto m30 = make_vector_i(3_RD, init_p, maker::heap);
auto m31 = make_matrix_i(dim_pair(1_CS, 3_RS), init_p, maker::heap);
auto m32 = make_matrix_i(dim_pair(1_CS, 3_RD), init_p, maker::heap);
auto m33 = make_matrix< T >({{0}, {1}, {2}}, maker::heap);
auto m34 = make_matrix(ref_i, maker::heap);
auto m35 = make_matrix({{T(0)}, {T(1)}, {T(2)}}, maker::heap);
auto m42 = make_col_vector< T >({0, 1, 2}, maker::heap);
auto m43 = make_col_vector(ref_i_vec, maker::heap);
auto m44 = make_col_vector({T(0), T(1), T(2)}, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m16) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m17) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m18) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m19) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m20) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m21) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m22) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m23) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m24) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m25) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m26) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m27) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m28) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m29) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m30) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m31) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m32) == id< heap_matrix< T, 1_C, 0_R > >));
BOOST_TEST((rt_id(m33) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m34) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m35) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m42) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m43) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST((rt_id(m44) == id< heap_matrix< T, 1_C, 3_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_v));
BOOST_TEST(check(m08, ref_v));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
BOOST_TEST(check(m16, ref_i));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_f));
BOOST_TEST(check(m22, ref_f));
BOOST_TEST(check(m23, ref_f));
BOOST_TEST(check(m24, ref_f));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_i));
BOOST_TEST(check(m28, ref_i));
BOOST_TEST(check(m29, ref_i));
BOOST_TEST(check(m30, ref_i));
BOOST_TEST(check(m31, ref_i));
BOOST_TEST(check(m32, ref_i));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
BOOST_TEST(check(m44, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_heap_matrix_3x1, T, types){
constexpr T ref_0[1][3] = {{0, 0, 0}};
constexpr T ref_v[1][3] = {{7, 7, 7}};
constexpr T ref_i[1][3] = {{0, 1, 2}};
constexpr T ref_i_vec[3] = {0, 1, 2};
static constexpr T init_i[3] = {0, 1, 2};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[1][3] = {{0, 1, 2}};
constexpr auto fn_xy = fn_xy_t< T >();
constexpr auto fn_i = fn_y_t< T >();
auto m01 = make_matrix_v< T >(3_CS, 1_RS, T(), maker::heap);
auto m02 = make_vector_v< T >(3_CS, T(), maker::heap);
auto m03 = make_matrix_v< T >(3_CD, 1_RS, T(), maker::heap);
auto m04 = make_vector_v< T >(3_CD, T(), maker::heap);
auto m05 = make_matrix_v< T >(dim_pair(3_CS, 1_RS), T(), maker::heap);
auto m06 = make_matrix_v< T >(dim_pair(3_CD, 1_RS), T(), maker::heap);
auto m07 = make_matrix_v(3_CS, 1_RS, T(7), maker::heap);
auto m08 = make_vector_v(3_CS, T(7), maker::heap);
auto m09 = make_matrix_v(3_CD, 1_RS, T(7), maker::heap);
auto m10 = make_vector_v(3_CD, T(7), maker::heap);
auto m11 = make_matrix_v(dim_pair(3_CS, 1_RS), T(7), maker::heap);
auto m12 = make_matrix_v(dim_pair(3_CD, 1_RS), T(7), maker::heap);
auto m13 = make_matrix< T >(3_CS, 1_RS, {{0, 1, 2}}, maker::heap);
auto m14 = make_vector< T >(3_CS, {0, 1, 2}, maker::heap);
auto m15 = make_matrix< T >(3_CD, 1_RS, {{0, 1, 2}}, maker::heap);
auto m16 = make_vector< T >(3_CD, {0, 1, 2}, maker::heap);
auto m17 = make_matrix(3_CS, 1_RS, ref_i, maker::heap);
auto m18 = make_vector(3_CS, ref_i_vec, maker::heap);
auto m19 = make_matrix(3_CD, 1_RS, ref_i, maker::heap);
auto m20 = make_vector(3_CD, ref_i_vec, maker::heap);
auto m21 = make_matrix_fn(3_CS, 1_RS, fn_xy, maker::heap);
auto m22 = make_vector_fn(3_CS, fn_i, maker::heap);
auto m23 = make_matrix_fn(3_CD, 1_RS, fn_xy, maker::heap);
auto m24 = make_vector_fn(3_CD, fn_i, maker::heap);
auto m25 = make_matrix_fn(dim_pair(3_CS, 1_RS), fn_xy, maker::heap);
auto m26 = make_matrix_fn(dim_pair(3_CD, 1_RS), fn_xy, maker::heap);
auto m27 = make_matrix_i(3_CS, 1_RS, init_p, maker::heap);
auto m28 = make_vector_i(3_CS, init_p, maker::heap);
auto m29 = make_matrix_i(3_CD, 1_RS, init_p, maker::heap);
auto m30 = make_vector_i(3_CD, init_p, maker::heap);
auto m31 = make_matrix_i(dim_pair(3_CS, 1_RS), init_p, maker::heap);
auto m32 = make_matrix_i(dim_pair(3_CD, 1_RS), init_p, maker::heap);
auto m33 = make_matrix< T >({{0, 1, 2}}, maker::heap);
auto m34 = make_matrix(ref_i, maker::heap);
auto m35 = make_matrix({{T(0), T(1), T(2)}}, maker::heap);
auto m42 = make_row_vector< T >({0, 1, 2}, maker::heap);
auto m43 = make_row_vector(ref_i_vec, maker::heap);
auto m44 = make_row_vector({T(0), T(1), T(2)}, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m16) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m17) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m18) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m19) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m20) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m21) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m22) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m23) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m24) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m25) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m26) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m27) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m28) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m29) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m30) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m31) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m32) == id< heap_matrix< T, 0_C, 1_R > >));
BOOST_TEST((rt_id(m33) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m34) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m35) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m42) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m43) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST((rt_id(m44) == id< heap_matrix< T, 3_C, 1_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_0));
BOOST_TEST(check(m07, ref_v));
BOOST_TEST(check(m08, ref_v));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_v));
BOOST_TEST(check(m12, ref_v));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
BOOST_TEST(check(m16, ref_i));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_i));
BOOST_TEST(check(m20, ref_i));
BOOST_TEST(check(m21, ref_f));
BOOST_TEST(check(m22, ref_f));
BOOST_TEST(check(m23, ref_f));
BOOST_TEST(check(m24, ref_f));
BOOST_TEST(check(m25, ref_f));
BOOST_TEST(check(m26, ref_f));
BOOST_TEST(check(m27, ref_i));
BOOST_TEST(check(m28, ref_i));
BOOST_TEST(check(m29, ref_i));
BOOST_TEST(check(m30, ref_i));
BOOST_TEST(check(m31, ref_i));
BOOST_TEST(check(m32, ref_i));
BOOST_TEST(check(m33, ref_i));
BOOST_TEST(check(m34, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
BOOST_TEST(check(m44, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_heap_matrix_1x1, T, types){
constexpr T ref_0[1][1] = {{0}};
constexpr T ref_v[1][1] = {{7}};
constexpr T ref_i[1][1] = {{0}};
constexpr T ref_i_vec[1] = {0};
static constexpr T init_i[1] = {0};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[1][1] = {{0}};
constexpr auto fn_xy = fn_xy_t< T >();
constexpr auto fn_x = fn_x_t< T >();
constexpr auto fn_y = fn_y_t< T >();
auto m01 = make_matrix_v< T >(1_CS, 1_RS, T(), maker::heap);
auto m02 = make_vector_v< T >(1_CS, T(), maker::heap);
auto m03 = make_vector_v< T >(1_RS, T(), maker::heap);
auto m04 = make_matrix_v< T >(dim_pair(1_CS, 1_RS), T(), maker::heap);
auto m05 = make_matrix_v< T >(1_DS, T(), maker::heap);
auto m06 = make_matrix_v(1_CS, 1_RS, T(7), maker::heap);
auto m07 = make_vector_v(1_CS, T(7), maker::heap);
auto m08 = make_vector_v(1_RS, T(7), maker::heap);
auto m09 = make_matrix_v(dim_pair(1_CS, 1_RS), T(7), maker::heap);
auto m10 = make_matrix_v(1_DS, T(7), maker::heap);
auto m11 = make_matrix< T >(1_CS, 1_RS, {{0}}, maker::heap);
auto m12 = make_vector< T >(1_CS, {0}, maker::heap);
auto m13 = make_vector< T >(1_RS, {0}, maker::heap);
auto m14 = make_matrix< T >(1_DS, {{0}}, maker::heap);
auto m15 = make_matrix(1_CS, 1_RS, ref_i, maker::heap);
auto m16 = make_vector(1_CS, ref_i_vec, maker::heap);
auto m17 = make_vector(1_RS, ref_i_vec, maker::heap);
auto m18 = make_matrix(1_DS, ref_i, maker::heap);
auto m19 = make_matrix_fn(1_CS, 1_RS, fn_xy, maker::heap);
auto m20 = make_vector_fn(1_CS, fn_x, maker::heap);
auto m21 = make_vector_fn(1_RS, fn_y, maker::heap);
auto m22 = make_matrix_fn(dim_pair(1_CS, 1_RS), fn_xy, maker::heap);
auto m23 = make_matrix_fn(1_DS, fn_xy, maker::heap);
auto m24 = make_matrix_i(1_CS, 1_RS, init_p, maker::heap);
auto m25 = make_vector_i(1_CS, init_p, maker::heap);
auto m26 = make_vector_i(1_RS, init_p, maker::heap);
auto m27 = make_matrix_i(dim_pair(1_CS, 1_RS), init_p, maker::heap);
auto m28 = make_matrix_i(1_DS, init_p, maker::heap);
auto m29 = make_matrix< T >({{0}}, maker::heap);
auto m30 = make_matrix(ref_i, maker::heap);
auto m31 = make_matrix({{T(0)}}, maker::heap);
auto m35 = make_col_vector< T >({0}, maker::heap);
auto m36 = make_col_vector(ref_i_vec, maker::heap);
auto m37 = make_col_vector({T(0)}, maker::heap);
auto m41 = make_row_vector< T >({0}, maker::heap);
auto m42 = make_row_vector(ref_i_vec, maker::heap);
auto m43 = make_row_vector({T(0)}, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m16) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m17) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m18) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m19) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m20) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m21) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m22) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m23) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m24) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m25) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m26) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m27) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m28) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m29) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m30) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m31) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m35) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m36) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m37) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m41) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m42) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST((rt_id(m43) == id< heap_matrix< T, 1_C, 1_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_0));
BOOST_TEST(check(m04, ref_0));
BOOST_TEST(check(m05, ref_0));
BOOST_TEST(check(m06, ref_v));
BOOST_TEST(check(m07, ref_v));
BOOST_TEST(check(m08, ref_v));
BOOST_TEST(check(m09, ref_v));
BOOST_TEST(check(m10, ref_v));
BOOST_TEST(check(m11, ref_i));
BOOST_TEST(check(m12, ref_i));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
BOOST_TEST(check(m16, ref_i));
BOOST_TEST(check(m17, ref_i));
BOOST_TEST(check(m18, ref_i));
BOOST_TEST(check(m19, ref_f));
BOOST_TEST(check(m20, ref_f));
BOOST_TEST(check(m21, ref_f));
BOOST_TEST(check(m22, ref_f));
BOOST_TEST(check(m23, ref_f));
BOOST_TEST(check(m24, ref_i));
BOOST_TEST(check(m25, ref_i));
BOOST_TEST(check(m26, ref_i));
BOOST_TEST(check(m27, ref_i));
BOOST_TEST(check(m28, ref_i));
BOOST_TEST(check(m29, ref_i));
BOOST_TEST(check(m30, ref_i));
BOOST_TEST(check(m31, ref_i));
BOOST_TEST(check(m35, ref_i));
BOOST_TEST(check(m36, ref_i));
BOOST_TEST(check(m37, ref_i));
BOOST_TEST(check(m41, ref_i));
BOOST_TEST(check(m42, ref_i));
BOOST_TEST(check(m43, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_diag_heap_matrix, T, types){
constexpr T ref_0[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
constexpr T ref_v[3][3] = {{7, 0, 0}, {0, 7, 0}, {0, 0, 7}};
constexpr T ref_i[3][3] = {{0, 0, 0}, {0, 1, 0}, {0, 0, 2}};
constexpr T ref_i_vec[3] = {0, 1, 2};
static constexpr T init_i[3] = {0, 1, 2};
constexpr auto init_p = mitrax::begin(init_i);
constexpr T ref_f[3][3] = {{0, 0, 0}, {0, 11, 0}, {0, 0, 22}};
constexpr auto fn = fn_i_t< T >();
auto m01 = make_diag_matrix_v< T >(3_DS, T(), maker::heap);
auto m02 = make_diag_matrix_v< T >(3_DD, T(), maker::heap);
auto m03 = make_diag_matrix_v(3_DS, T(7), maker::heap);
auto m04 = make_diag_matrix_v(3_DD, T(7), maker::heap);
auto m05 = make_diag_matrix< T >(3_DS, {0, 1, 2}, maker::heap);
auto m06 = make_diag_matrix< T >(3_DD, {0, 1, 2}, maker::heap);
auto m07 = make_diag_matrix(3_DS, ref_i_vec, maker::heap);
auto m08 = make_diag_matrix(3_DD, ref_i_vec, maker::heap);
auto m09 = make_diag_matrix_fn(3_DS, fn, maker::heap);
auto m10 = make_diag_matrix_fn(3_DD, fn, maker::heap);
auto m11 = make_diag_matrix_i(3_DS, init_p, maker::heap);
auto m12 = make_diag_matrix_i(3_DD, init_p, maker::heap);
auto m13 = make_diag_matrix< T >({0, 1, 2}, maker::heap);
auto m14 = make_diag_matrix({T(0), T(1), T(2)}, maker::heap);
auto m15 = make_diag_matrix(ref_i_vec, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m05) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m06) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m07) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m08) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m09) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m10) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m11) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m12) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST((rt_id(m13) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m14) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m15) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST(check(m03, ref_v));
BOOST_TEST(check(m04, ref_v));
BOOST_TEST(check(m05, ref_i));
BOOST_TEST(check(m06, ref_i));
BOOST_TEST(check(m07, ref_i));
BOOST_TEST(check(m08, ref_i));
BOOST_TEST(check(m09, ref_f));
BOOST_TEST(check(m10, ref_f));
BOOST_TEST(check(m11, ref_i));
BOOST_TEST(check(m12, ref_i));
BOOST_TEST(check(m13, ref_i));
BOOST_TEST(check(m14, ref_i));
BOOST_TEST(check(m15, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_identity_heap_matrix, T, types){
constexpr T ref_i[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
auto m01 = make_identity_matrix< T >(3_DS, maker::heap);
auto m02 = make_identity_matrix< T >(3_DD, maker::heap);
BOOST_TEST((rt_id(m01) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m02) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m01, ref_i));
BOOST_TEST(check(m02, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_default_constructor, T, types){
constexpr T ref_0[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
stack_matrix< T, 3_C, 3_R > m01;
heap_matrix< T, 3_C, 3_R > m02;
heap_matrix< T, 3_C, 0_R > m03;
heap_matrix< T, 0_C, 3_R > m04;
heap_matrix< T, 0_C, 0_R > m05;
BOOST_TEST(check(m01, ref_0));
BOOST_TEST(check(m02, ref_0));
BOOST_TEST((m03.dims() == dim_pair(3_CS, 0_RD)));
BOOST_TEST((m04.dims() == dim_pair(0_CD, 3_RS)));
BOOST_TEST((m05.dims() == dim_pair(0_CD, 0_RD)));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_copy_constructor_heap, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
auto m01 = make_matrix(3_CS, 3_RS, ref_i, maker::heap);
auto m02 = make_matrix(3_CD, 3_RD, ref_i, maker::heap);
auto m03 = m01;
auto m04 = m02;
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_move_constructor_heap, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
auto m01 = make_matrix(3_CS, 3_RS, ref_i, maker::heap);
auto m02 = make_matrix(3_CD, 3_RD, ref_i, maker::heap);
auto m03 = std::move(m01);
auto m04 = std::move(m02);
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_copy_assignment_heap, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
auto m01 = make_matrix(3_CS, 3_RS, ref_i, maker::heap);
auto m02 = make_matrix(3_CD, 3_RD, ref_i, maker::heap);
auto m03 = make_matrix_v(3_CS, 3_RS, T(), maker::heap);
// also assign dimensions
auto m04 = make_matrix_v(0_CD, 0_RD, T(), maker::heap);
m03 = m01;
m04 = m02;
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_move_assignment_heap, T, types){
constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
auto m01 = make_matrix(3_CS, 3_RS, ref_i, maker::heap);
auto m02 = make_matrix(3_CD, 3_RD, ref_i, maker::heap);
auto m03 = make_matrix_v(3_CS, 3_RS, T(), maker::heap);
// also move dimensions
auto m04 = make_matrix_v(0_CD, 0_RD, T(), maker::heap);
m03 = std::move(m01);
m04 = std::move(m02);
BOOST_TEST((rt_id(m03) == id< heap_matrix< T, 3_C, 3_R > >));
BOOST_TEST((rt_id(m04) == id< heap_matrix< T, 0_C, 0_R > >));
BOOST_TEST(check(m03, ref_i));
BOOST_TEST(check(m04, ref_i));
}
BOOST_AUTO_TEST_SUITE_END()
| 39.50752
| 80
| 0.642513
|
bebuch
|
6ad15169a9175292dc8d45aab821b47f0f16bdb5
| 8,307
|
hpp
|
C++
|
include/byom/dynamic_view.hpp
|
purpleKarrot/BYOM
|
1de5f53a1185b37676d76399bd67ff9e08ad828a
|
[
"0BSD"
] | 2
|
2015-12-02T15:02:06.000Z
|
2015-12-03T22:41:19.000Z
|
include/byom/dynamic_view.hpp
|
purpleKarrot/BYOM
|
1de5f53a1185b37676d76399bd67ff9e08ad828a
|
[
"0BSD"
] | null | null | null |
include/byom/dynamic_view.hpp
|
purpleKarrot/BYOM
|
1de5f53a1185b37676d76399bd67ff9e08ad828a
|
[
"0BSD"
] | null | null | null |
// Copyright (c) 2015, Daniel Pfeifer <daniel@pfeifer-mail.de>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifndef BYOM_DYNAMIC_VIEW_HPP
#define BYOM_DYNAMIC_VIEW_HPP
#include <string>
#include <memory>
#include <functional>
#include <type_traits>
#include <stdexcept>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
namespace byom {
class dynamic_view;
using visit_function =
std::function<void(dynamic_view const&, dynamic_view const&)>;
template <typename T, typename Enable = void>
struct ext;
class dynamic_view
{
template <typename T>
using no_copy_ctor = typename std::enable_if<!std::is_same<
typename std::remove_reference<T>::type, dynamic_view>::value>::type;
public:
template <typename T, typename Enable = no_copy_ctor<T>>
dynamic_view(T&& t)
: dynamic_view(std::forward<T>(t), std::is_lvalue_reference<T>())
{
}
template <typename T>
dynamic_view(T* t)
{
new (storage()) local_model_t<T*>(t);
}
template <typename T>
dynamic_view(T const* t)
{
new (storage()) local_model_t<T const*>(t);
}
dynamic_view(dynamic_view const& x)
{
x.object().clone(storage());
}
dynamic_view(dynamic_view&& x)
{
x.object().move_clone(storage());
}
~dynamic_view()
{
object().~concept_t();
}
dynamic_view& operator=(dynamic_view&& x) = delete;
dynamic_view& operator=(dynamic_view const& x) = delete;
public:
bool empty() const
{
return object().empty();
}
dynamic_view at(std::string const& n) const &
{
return object().at(n);
}
dynamic_view at(std::string const& n) const &&
{
auto member = object().at(n);
if (object().owned() && !member.object().owned()) {
throw std::invalid_argument{ "dangling reference" };
}
return member;
}
void for_each(visit_function const& v) const
{
object().for_each(v);
}
template <typename T>
T get() const
{
return cast_helper<T>::cast(object());
}
friend std::ostream& operator<<(std::ostream& os, dynamic_view const& self)
{
self.object().print(os);
return os;
}
private:
struct concept_t
{
virtual ~concept_t() = default;
virtual void clone(void* storage) const = 0;
virtual void move_clone(void* storage) = 0;
virtual bool owned() const = 0;
virtual const std::type_info& type() const = 0;
virtual void const* data() const = 0;
virtual bool empty() const = 0;
virtual dynamic_view at(std::string const& n) const = 0;
virtual void for_each(visit_function const& v) const = 0;
virtual unsigned long long int to_integral() const = 0;
virtual long double to_floating_point() const = 0;
virtual std::string to_string() const = 0;
virtual void print(std::ostream& os) const = 0;
};
template <template <typename> class Derived, typename T>
struct model_base_t : concept_t
{
const std::type_info& type() const override
{
return typeid(T);
}
void const* data() const override
{
return &get();
}
bool empty() const override
{
return ext<T>::empty_impl(get());
}
dynamic_view at(std::string const& n) const override
{
return ext<T>::at_impl(get(), n);
}
void for_each(visit_function const& v) const override
{
ext<T>::for_each_impl(get(), v);
}
unsigned long long int to_integral() const override
{
return ext<T>::to_integral(get());
}
long double to_floating_point() const override
{
return ext<T>::to_floating_point(get());
}
std::string to_string() const override
{
return ext<T>::to_string(get());
}
void print(std::ostream& os) const override
{
ext<T>::print_impl(os, get());
}
T const& get() const
{
return static_cast<Derived<T> const*>(this)->get();
}
};
template <typename T>
struct cref_model_t : model_base_t<cref_model_t, T>
{
cref_model_t(T const& x)
: object(x)
{
}
void clone(void* storage) const override
{
new (storage) cref_model_t(object);
}
void move_clone(void* storage) override
{
clone(storage);
}
bool owned() const override
{
return false;
}
T const& get() const
{
return object;
}
T const& object;
};
template <typename T>
struct local_model_t : model_base_t<local_model_t, T>
{
local_model_t(T x)
: object(std::move(x))
{
}
void clone(void* storage) const override
{
new (storage) local_model_t(object);
}
bool owned() const override
{
return true;
}
void move_clone(void* storage) override
{
new (storage) local_model_t(std::move(object));
}
T const& get() const
{
return object;
}
T object;
};
template <typename T>
struct remote_model_t : model_base_t<remote_model_t, T>
{
remote_model_t(T x)
: object(std::make_unique<T const>(std::move(x)))
{
}
void clone(void* storage) const override
{
new (storage) remote_model_t(get());
}
void move_clone(void* storage) override
{
new (storage) remote_model_t(std::move(*this));
}
bool owned() const override
{
return true;
}
T const& get() const
{
return *object;
}
std::unique_ptr<T const> object;
};
private:
template <typename T, typename Enable = void>
struct cast_helper
{
static T cast(concept_t const& object)
{
if (object.type() != typeid(T)) {
throw std::bad_cast{ "bad cast" };
}
return *reinterpret_cast<T const*>(object.data());
}
};
template <typename T>
struct cast_helper<T,
typename std::enable_if<std::is_integral<T>::value>::type>
{
static T cast(concept_t const& object)
{
return static_cast<T>(object.to_integral());
}
};
template <typename T>
struct cast_helper<
T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{
static T cast(concept_t const& object)
{
return static_cast<T>(object.to_floating_point());
}
};
template <typename T>
struct cast_helper<
T, typename std::enable_if<std::is_same<T, std::string>::value>::type>
{
static T cast(concept_t const& object)
{
return object.to_string();
}
};
private:
template <typename T>
dynamic_view(T&& t, std::true_type)
{
using model = cref_model_t<typename std::decay<T>::type>;
static_assert(sizeof(model) <= sizeof(data), "size mismatch");
new (storage()) model(t);
}
template <typename T>
dynamic_view(T&& t, std::false_type)
{
using local_type = local_model_t<typename std::decay<T>::type>;
using remote_type = remote_model_t<typename std::decay<T>::type>;
using use_local_type =
boost::mpl::bool_<(sizeof(local_type) <= sizeof(data)) &&
(std::is_nothrow_copy_constructible<T>::value ||
std::is_nothrow_move_constructible<T>::value)>;
using model =
typename boost::mpl::if_<use_local_type, local_type, remote_type>::type;
static_assert(sizeof(model) <= sizeof(data), "size mismatch");
new (storage()) model(std::move(t));
}
private:
concept_t& object()
{
return *static_cast<concept_t*>(storage());
}
concept_t const& object() const
{
return *static_cast<concept_t const*>(storage());
}
void* storage()
{
return &data;
}
void const* storage() const
{
return &data;
}
double data[2];
};
} // namespace byom
#endif /* BYOM_DYNAMIC_VIEW_HPP */
| 22.152
| 79
| 0.633081
|
purpleKarrot
|
6ad4c1c00212ff4bd747090827d0434244f4f36b
| 826
|
cpp
|
C++
|
engine/source/engine/_gl.cpp
|
n4n0lix/Kerosene
|
cd65f5e4b374a91259e22d41153f44c141d79af3
|
[
"0BSD"
] | 2
|
2016-01-17T03:35:39.000Z
|
2019-12-23T15:04:47.000Z
|
engine/source/engine/_gl.cpp
|
n4n0lix/Kerosene
|
cd65f5e4b374a91259e22d41153f44c141d79af3
|
[
"0BSD"
] | null | null | null |
engine/source/engine/_gl.cpp
|
n4n0lix/Kerosene
|
cd65f5e4b374a91259e22d41153f44c141d79af3
|
[
"0BSD"
] | 2
|
2016-03-23T09:13:14.000Z
|
2019-12-23T15:04:53.000Z
|
#include "stdafx.h"
#include "_gl.h"
#ifdef GL_DEBUG
std::string gl_err_to_string(GLenum err) {
switch (err) {
case GL_INVALID_ENUM: return "Invalid enum.";
case GL_INVALID_VALUE: return "Invalid value.";
case GL_INVALID_OPERATION: return "Invalid operation.";
case GL_STACK_OVERFLOW: return "Stack overflow.";
case GL_STACK_UNDERFLOW: return "Stack underflow.";
case GL_OUT_OF_MEMORY: return "Out of memory.";
case GL_INVALID_FRAMEBUFFER_OPERATION: return "Invalid framebuffer operation.";
case GL_CONTEXT_LOST: return "Context lost.";
case GL_TABLE_TOO_LARGE: return "Table too large.";
}
return "UNKOWN";
}
#endif
#ifdef GL_MOCK
std::map<std::string, std::uint32_t> GLMock::INVOCATIONS = std::map<std::string, std::uint32_t>();
#endif
| 31.769231
| 98
| 0.688862
|
n4n0lix
|
6ad65654e57b79d98b1d94f06e1ccac699c33c72
| 5,057
|
cpp
|
C++
|
applications/command_line_tools/simple_embedding_viewer.cpp
|
kevlim83/High-Dimensional-Inspector
|
1ad9cdf7712fb497c88051bdff32ce27350433ed
|
[
"MIT"
] | 68
|
2017-10-05T16:18:21.000Z
|
2022-03-22T14:35:48.000Z
|
applications/command_line_tools/simple_embedding_viewer.cpp
|
kevlim83/High-Dimensional-Inspector
|
1ad9cdf7712fb497c88051bdff32ce27350433ed
|
[
"MIT"
] | 8
|
2018-04-27T20:52:00.000Z
|
2020-01-17T12:28:35.000Z
|
applications/command_line_tools/simple_embedding_viewer.cpp
|
kevlim83/High-Dimensional-Inspector
|
1ad9cdf7712fb497c88051bdff32ce27350433ed
|
[
"MIT"
] | 18
|
2017-10-31T13:09:05.000Z
|
2020-07-20T16:50:53.000Z
|
/*
*
* Copyright (c) 2014, Nicola Pezzotti (Delft University of Technology)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Delft University of Technology.
* 4. Neither the name of the Delft University of Technology nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY NICOLA PEZZOTTI ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL NICOLA PEZZOTTI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
#include "hdi/dimensionality_reduction/tsne.h"
#include "hdi/utils/cout_log.h"
#include "hdi/utils/log_helper_functions.h"
#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QIcon>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include "hdi/visualization/scatterplot_canvas_qobj.h"
#include "hdi/visualization/scatterplot_drawer_fixed_color.h"
int main(int argc, char *argv[])
{
try{
QApplication app(argc, argv);
QIcon icon;
icon.addFile(":/hdi16.png");
icon.addFile(":/hdi32.png");
icon.addFile(":/hdi64.png");
icon.addFile(":/hdi128.png");
icon.addFile(":/hdi256.png");
app.setWindowIcon(icon);
QCoreApplication::setApplicationName("Simple Embedding Viewer");
QCoreApplication::setApplicationVersion("0.1");
QCommandLineParser parser;
parser.setApplicationDescription("Point-based visualization of a 2D embedding");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("embedding", QCoreApplication::translate("main", "Embedding."));
// Process the actual command line arguments given by the user
parser.process(app);
const QStringList args = parser.positionalArguments();
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
if(args.size()!=1){
std::cout << "Not enough arguments!" << std::endl;
return -1;
}
std::ifstream input_file (args[0].toStdString(), std::ios::in|std::ios::binary|std::ios::ate);
const unsigned int num_data_points = input_file.tellg()/sizeof(float)/2;
std::vector<float> data(num_data_points*2);
std::vector<uint32_t> flags(num_data_points);
input_file.seekg (0, std::ios::beg);
input_file.read (reinterpret_cast<char*>(data.data()), sizeof(float) * data.size()*2);
input_file.close();
float min_x(std::numeric_limits<float>::max());
float max_x(-std::numeric_limits<float>::max());
float min_y(std::numeric_limits<float>::max());
float max_y(-std::numeric_limits<float>::max());
for(int i = 0; i < num_data_points; ++i){
min_x = std::min(min_x,data[i*2]);
max_x = std::max(max_x,data[i*2]);
min_y = std::min(min_y,data[i*2+1]);
max_y = std::max(max_y,data[i*2+1]);
}
auto tr = QVector2D(max_x,max_y);
auto bl = QVector2D(min_x,min_y);
auto offset = (tr-bl)*0.25;
hdi::viz::ScatterplotCanvas viewer;
viewer.setBackgroundColors(qRgb(240,240,240),qRgb(200,200,200));
viewer.setSelectionColor(qRgb(50,50,50));
viewer.resize(500,500);
viewer.show();
viewer.setTopRightCoordinates(tr+offset);
viewer.setBottomLeftCoordinates(bl-offset);
hdi::viz::ScatterplotDrawerFixedColor drawer;
drawer.initialize(viewer.context());
drawer.setData(data.data(), flags.data(), num_data_points);
drawer.setAlpha(0.5);
drawer.setPointSize(5);
viewer.addDrawer(&drawer);
return app.exec();
}
catch(std::logic_error& ex){ std::cout << "Logic error: " << ex.what();}
catch(std::runtime_error& ex){ std::cout << "Runtime error: " << ex.what();}
catch(...){ std::cout << "An unknown error occurred";}
}
| 39.20155
| 98
| 0.688946
|
kevlim83
|
6ad7c09502500ceda52db13e0edc73b64938d9d3
| 6,975
|
hpp
|
C++
|
framework/mcrouter/tcp/private/ServerServiceEvent.hpp
|
Ali-Nasrolahi/areg-sdk
|
4fbc2f2644220196004a31672a697a864755f0b6
|
[
"Apache-2.0"
] | 70
|
2021-07-20T11:26:16.000Z
|
2022-03-27T11:17:43.000Z
|
framework/mcrouter/tcp/private/ServerServiceEvent.hpp
|
Ali-Nasrolahi/areg-sdk
|
4fbc2f2644220196004a31672a697a864755f0b6
|
[
"Apache-2.0"
] | 32
|
2021-07-31T05:20:44.000Z
|
2022-03-20T10:11:52.000Z
|
framework/mcrouter/tcp/private/ServerServiceEvent.hpp
|
Ali-Nasrolahi/areg-sdk
|
4fbc2f2644220196004a31672a697a864755f0b6
|
[
"Apache-2.0"
] | 40
|
2021-11-02T09:45:38.000Z
|
2022-03-27T11:17:46.000Z
|
#pragma once
/************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file mcrouter/tcp/private/ServerServiceEvent.hpp
* \ingroup AREG Asynchronous Event-Driven Communication Framework
* \author Artak Avetyan
* \brief AREG Platform Server Service Event
************************************************************************/
/************************************************************************
* Include files.
************************************************************************/
#include "areg/base/GEGlobal.h"
#include "areg/component/TEEvent.hpp"
#include "areg/base/RemoteMessage.hpp"
//////////////////////////////////////////////////////////////////////////
// ServerServiceEventData class declaration
//////////////////////////////////////////////////////////////////////////
/**
* \brief The routing service event data. Used for communication with
* message router.
**/
class ServerServiceEventData
{
//////////////////////////////////////////////////////////////////////////
// Types and constants
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief The list of commands for server connection service
**/
typedef enum class E_ServerServiceCommands
{
CMD_StartService //!< Sent to start message router connection service
, CMD_StopService //!< Sent to stop message router connection service
, CMD_ServiceSendMsg //!< Sent to notify to sent messages to connected client
, CMD_ServiceReceivedMsg //!< Sent to notify received message from connected client
} eServerServiceCommands;
/**
* \brief Converts ServerServiceEventData:eServerServiceCommands values to string.
**/
static inline const char * getString( ServerServiceEventData::eServerServiceCommands cmdService );
//////////////////////////////////////////////////////////////////////////
// Constructors / Destructor
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Initializes server connection service event data, sets command.
* \param cmdService The command to set in event data.
**/
explicit ServerServiceEventData( ServerServiceEventData::eServerServiceCommands cmdService );
/**
* \brief Initializes server connection service event data, sets command and message data buffer.
* \param cmdService The command to set in event data.
* \param msgService The message data buffer to initialize.
**/
ServerServiceEventData( ServerServiceEventData::eServerServiceCommands cmdService, const RemoteMessage & msgService );
/**
* \brief Copies the event data from given source.
* \param source The source to copy data.
**/
ServerServiceEventData( const ServerServiceEventData & source );
/**
* \brief Moves the event data from given source.
* \param source The source to move data.
**/
ServerServiceEventData( ServerServiceEventData && source ) noexcept;
/**
* \brief Destructor.
**/
~ServerServiceEventData( void ) = default;
//////////////////////////////////////////////////////////////////////////
// Operators and attributes
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Copies event data from given source.
* \param source The source to copy data.
**/
ServerServiceEventData & operator = ( const ServerServiceEventData & source );
/**
* \brief Moves event data from given source.
* \param source The source to move data.
**/
ServerServiceEventData & operator = ( ServerServiceEventData && source ) noexcept;
/**
* \brief Returns command saved in event data.
**/
inline ServerServiceEventData::eServerServiceCommands getCommand( void ) const;
/**
* \brief Returns message data buffer object saved in event data.
**/
inline const RemoteMessage & getMessage( void ) const;
//////////////////////////////////////////////////////////////////////////
// Member variables
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief The command of server service event.
**/
ServerServiceEventData::eServerServiceCommands mServiceCommand;
/**
* \brief The message data buffer saved in service event.
**/
mutable RemoteMessage mMessageData;
//////////////////////////////////////////////////////////////////////////////
// Forbidden calls
//////////////////////////////////////////////////////////////////////////////
private:
ServerServiceEventData( void ) = delete;
};
//////////////////////////////////////////////////////////////////////////
// ServerServiceEvent and IEServerServiceEventConsumer declaration
//////////////////////////////////////////////////////////////////////////
//!< Declaration of ServerServiceEvent event and IEServerServiceEventConsumer consumer classes
DECLARE_EVENT(ServerServiceEventData, ServerServiceEvent, IEServerServiceEventConsumer)
//////////////////////////////////////////////////////////////////////////////
// ServerServiceEventData class inline functions implementation
//////////////////////////////////////////////////////////////////////////////
inline ServerServiceEventData::eServerServiceCommands ServerServiceEventData::getCommand( void ) const
{
return mServiceCommand;
}
inline const RemoteMessage & ServerServiceEventData::getMessage( void ) const
{
return mMessageData;
}
inline const char * ServerServiceEventData::getString( ServerServiceEventData::eServerServiceCommands cmdService )
{
switch ( cmdService )
{
case ServerServiceEventData::eServerServiceCommands::CMD_StartService:
return "ServerServiceEventData::CMD_StartService";
case ServerServiceEventData::eServerServiceCommands::CMD_StopService:
return "ServerServiceEventData::CMD_StopService";
case ServerServiceEventData::eServerServiceCommands::CMD_ServiceSendMsg:
return "ServerServiceEventData::CMD_ServiceSendMsg";
case ServerServiceEventData::eServerServiceCommands::CMD_ServiceReceivedMsg:
return "ServerServiceEventData::CMD_ServiceReceivedMsg";
default:
return "ERR: Unexpected ServerServiceEventData::eServerServiceCommands value!!!";
}
}
| 42.018072
| 122
| 0.558566
|
Ali-Nasrolahi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.