text
stringlengths 5
1.04M
|
|---|
/// @ref gtx_type_trait
/// @file glm/gtx/type_trait.hpp
///
/// @see core (dependence)
///
/// @defgroup gtx_type_trait GLM_GTX_type_trait
/// @ingroup gtx
///
/// Include <glm/gtx/type_trait.hpp> to use the features of this extension.
///
/// Defines traits for each type.
#pragma once
#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)
# ifndef GLM_ENABLE_EXPERIMENTAL
# pragma message("GLM: GLM_GTX_type_trait is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it.")
# else
# pragma message("GLM: GLM_GTX_type_trait extension included")
# endif
#endif
// Dependency:
#include "../detail/qualifier.hpp"
#include "../gtc/quaternion.hpp"
#include "../gtx/dual_quaternion.hpp"
namespace legion::core::math
{
/// @addtogroup gtx_type_trait
/// @{
template<typename T>
struct type
{
static bool const is_vec = false;
static bool const is_mat = false;
static bool const is_quat = false;
static length_t const components = 0;
static length_t const cols = 0;
static length_t const rows = 0;
};
template<length_t L, typename T, qualifier Q>
struct type<vec<L, T, Q> >
{
static bool const is_vec = true;
static bool const is_mat = false;
static bool const is_quat = false;
static length_t const components = L;
};
template<length_t C, length_t R, typename T, qualifier Q>
struct type<mat<C, R, T, Q> >
{
static bool const is_vec = false;
static bool const is_mat = true;
static bool const is_quat = false;
static length_t const components = C;
static length_t const cols = C;
static length_t const rows = R;
};
template<typename T, qualifier Q>
struct type<qua<T, Q> >
{
static bool const is_vec = false;
static bool const is_mat = false;
static bool const is_quat = true;
static length_t const components = 4;
};
template<typename T, qualifier Q>
struct type<tdualquat<T, Q> >
{
static bool const is_vec = false;
static bool const is_mat = false;
static bool const is_quat = true;
static length_t const components = 8;
};
/// @}
}//namespace legion::core::math
#include "type_trait.inl"
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin developers
// Copyright (c) 2017-2020 The PIVX developers
// Copyright (c) 2020-2021 The TimelockCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifdef HAVE_CONFIG_H
#include "config/timelockcoin-config.h"
#endif
#include "netbase.h"
#include "hash.h"
#include "sync.h"
#include "uint256.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#include <atomic>
#ifdef HAVE_GETADDRINFO_A
#include <netdb.h>
#endif
#ifndef WIN32
#if HAVE_INET_PTON
#include <arpa/inet.h>
#endif
#include <fcntl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/thread.hpp>
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Settings
static proxyType proxyInfo[NET_MAX];
static proxyType nameProxy;
static RecursiveMutex cs_proxyInfos;
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
bool fNameLookup = false;
// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
enum Network ParseNetwork(std::string net)
{
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor" || net == "onion") return NET_TOR;
return NET_UNROUTABLE;
}
std::string GetNetworkName(enum Network net)
{
switch (net) {
case NET_IPV4:
return "ipv4";
case NET_IPV6:
return "ipv6";
case NET_TOR:
return "onion";
default:
return "";
}
}
void SplitHostPort(std::string in, int& portOut, std::string& hostOut)
{
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':', colon - 1) != in.npos);
if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
int32_t n;
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
portOut = n;
}
}
if (in.size() > 0 && in[0] == '[' && in[in.size() - 1] == ']')
hostOut = in.substr(1, in.size() - 2);
else
hostOut = in;
}
bool static LookupIntern(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
#ifdef HAVE_GETADDRINFO_A
struct in_addr ipv4_addr;
#ifdef HAVE_INET_PTON
if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
struct in6_addr ipv6_addr;
if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
vIP.push_back(CNetAddr(ipv6_addr));
return true;
}
#else
ipv4_addr.s_addr = inet_addr(pszName);
if (ipv4_addr.s_addr != INADDR_NONE) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
#endif
#endif
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
aiHint.ai_family = AF_UNSPEC;
#ifdef WIN32
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo* aiRes = NULL;
#ifdef HAVE_GETADDRINFO_A
struct gaicb gcb, *query = &gcb;
memset(query, 0, sizeof(struct gaicb));
gcb.ar_name = pszName;
gcb.ar_request = &aiHint;
int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
if (nErr)
return false;
do {
// Should set the timeout limit to a resonable value to avoid
// generating unnecessary checking call during the polling loop,
// while it can still response to stop request quick enough.
// 2 seconds looks fine in our situation.
struct timespec ts = {2, 0};
gai_suspend(&query, 1, &ts);
boost::this_thread::interruption_point();
nErr = gai_error(query);
if (0 == nErr)
aiRes = query->ar_result;
} while (nErr == EAI_INPROGRESS);
#else
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
#endif
if (nErr)
return false;
struct addrinfo* aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) {
if (aiTrav->ai_family == AF_INET) {
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
if (aiTrav->ai_family == AF_INET6) {
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
std::string strHost(pszName);
if (strHost.empty())
return false;
if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) {
strHost = strHost.substr(1, strHost.size() - 2);
}
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
bool LookupHost(const char* pszName, CNetAddr& addr, bool fAllowLookup)
{
std::vector<CNetAddr> vIP;
LookupHost(pszName, vIP, 1, fAllowLookup);
if (vIP.empty())
return false;
addr = vIP.front();
return true;
}
bool Lookup(const char* pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char* pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
CService LookupNumeric(const char* pszName, int portDefault)
{
CService addr;
// "1.2:345" will fail to resolve the ip, but will still set the port.
// If the ip fails to resolve, re-init the result.
if (!Lookup(pszName, addr, portDefault, false))
addr = CService();
return addr;
}
struct timeval MillisToTimeval(int64_t nTimeout)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
enum class IntrRecvError {
OK,
Timeout,
Disconnected,
NetworkError,
Interrupted
};
/**
* Read bytes from socket. This will either read the full number of bytes requested
* or return False on error or timeout.
* This function can be interrupted by boost thread interrupt.
*
* @param data Buffer to receive into
* @param len Length of data to receive
* @param timeout Timeout in milliseconds for receive operation
*
* @note This function requires that hSocket is in non-blocking mode.
*/
static IntrRecvError InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
{
int64_t curTime = GetTimeMillis();
int64_t endTime = curTime + timeout;
// Maximum time to wait in one select call. It will take up until this time (in millis)
// to break off in case of an interruption.
const int64_t maxWait = 1000;
while (len > 0 && curTime < endTime) {
ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
if (ret > 0) {
len -= ret;
data += ret;
} else if (ret == 0) { // Unexpected disconnection
return IntrRecvError::Disconnected;
} else { // Other error or blocking
int nErr = WSAGetLastError();
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
if (!IsSelectableSocket(hSocket)) {
return IntrRecvError::NetworkError;
}
struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
if (nRet == SOCKET_ERROR) {
return IntrRecvError::NetworkError;
}
} else {
return IntrRecvError::NetworkError;
}
}
boost::this_thread::interruption_point();
curTime = GetTimeMillis();
}
return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
}
struct ProxyCredentials
{
std::string username;
std::string password;
};
/** Connect using SOCKS5 (as described in RFC1928) */
bool static Socks5(std::string strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
{
IntrRecvError recvr;
LogPrintf("SOCKS5 connecting %s\n", strDest);
if (strDest.size() > 255) {
CloseSocket(hSocket);
return error("Hostname too long");
}
// Accepted authentication methods
std::vector<uint8_t> vSocks5Init;
vSocks5Init.push_back(0x05);
if (auth) {
vSocks5Init.push_back(0x02); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
} else {
vSocks5Init.push_back(0x01); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
}
ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5Init.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to initialize");
}
if (pchRet1[1] == 0x02 && auth) {
// Perform username/password authentication (as described in RFC1929)
std::vector<uint8_t> vAuth;
vAuth.push_back(0x01);
if (auth->username.size() > 255 || auth->password.size() > 255)
return error("Proxy username or password too long");
vAuth.push_back(auth->username.size());
vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
vAuth.push_back(auth->password.size());
vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vAuth.size()) {
CloseSocket(hSocket);
return error("Error sending authentication to proxy");
}
LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
char pchRetA[2];
if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
CloseSocket(hSocket);
return error("Error reading proxy authentication response");
}
if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
CloseSocket(hSocket);
return error("Proxy authentication unsuccesful");
}
} else if (pchRet1[1] == 0x00) {
// Perform no authentication
} else {
CloseSocket(hSocket);
return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
}
std::vector<uint8_t> vSocks5;
vSocks5.push_back(0x05); // VER protocol version
vSocks5.push_back(0x01); // CMD CONNECT
vSocks5.push_back(0x00); // RSV Reserved
vSocks5.push_back(0x03); // ATYP DOMAINNAME
vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
vSocks5.push_back((port >> 8) & 0xFF);
vSocks5.push_back((port >> 0) & 0xFF);
ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
CloseSocket(hSocket);
if (recvr == IntrRecvError::Timeout) {
/* If a timeout happens here, this effectively means we timed out while connecting
* to the remote node. This is very common for Tor, so do not print an
* error message. */
return false;
} else {
return error("Error while reading proxy response");
}
}
if (pchRet2[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00) {
CloseSocket(hSocket);
switch (pchRet2[1]) {
case 0x01:
return error("Proxy error: general failure");
case 0x02:
return error("Proxy error: connection not allowed");
case 0x03:
return error("Proxy error: network unreachable");
case 0x04:
return error("Proxy error: host unreachable");
case 0x05:
return error("Proxy error: connection refused");
case 0x06:
return error("Proxy error: TTL expired");
case 0x07:
return error("Proxy error: protocol error");
case 0x08:
return error("Proxy error: address type not supported");
default:
return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00) {
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3]) {
case 0x01:
recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
case 0x04:
recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
case 0x03: {
recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
if (recvr != IntrRecvError::OK) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
int nRecv = pchRet3[0];
recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
break;
}
default:
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
if (recvr != IntrRecvError::OK) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
LogPrintf("SOCKS5 connected %s\n", strDest);
return true;
}
bool static ConnectSocketDirectly(const CService& addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
#ifdef SO_NOSIGPIPE
int set = 1;
// Different way of disabling SIGPIPE on BSD
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
// Set to non-blocking
if (!SetSocketNonBlocking(hSocket, true))
return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
// WSAEINVAL is here because some legacy version of winsock uses it
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
struct timeval timeout = MillisToTimeval(nTimeout);
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0) {
LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString());
CloseSocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR) {
LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
if (nRet != 0) {
LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
CloseSocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, const proxyType &addrProxy)
{
assert(net >= 0 && net < NET_MAX);
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
proxyInfo[net] = addrProxy;
return true;
}
bool GetProxy(enum Network net, proxyType& proxyInfoOut)
{
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
if (!proxyInfo[net].IsValid())
return false;
proxyInfoOut = proxyInfo[net];
return true;
}
bool SetNameProxy(const proxyType &addrProxy)
{
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
nameProxy = addrProxy;
return true;
}
bool GetNameProxy(proxyType &nameProxyOut)
{
LOCK(cs_proxyInfos);
if (!nameProxy.IsValid())
return false;
nameProxyOut = nameProxy;
return true;
}
bool HaveNameProxy()
{
LOCK(cs_proxyInfos);
return nameProxy.IsValid();
}
bool IsProxy(const CNetAddr& addr)
{
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (addr == (CNetAddr)proxyInfo[i].proxy)
return true;
}
return false;
}
static bool ConnectThroughProxy(const proxyType &proxy, const std::string strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
if (outProxyConnectionFailed)
*outProxyConnectionFailed = true;
return false;
}
// do socks negotiation
if (proxy.randomize_credentials) {
ProxyCredentials random_auth;
static std::atomic_int counter;
random_auth.username = random_auth.password = strprintf("%i", counter++);
if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
return false;
} else {
if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
proxyType proxy;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
if (GetProxy(addrDest.GetNetwork(), proxy))
return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
else // no proxy needed (none set for target network)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
}
bool ConnectSocketByName(CService& addr, SOCKET& hSocketRet, const char* pszDest, int portDefault, int nTimeout, bool* outProxyConnectionFailed)
{
std::string strDest;
int port = portDefault;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
SplitHostPort(std::string(pszDest), port, strDest);
proxyType nameProxy;
GetNameProxy(nameProxy);
std::vector<CService> addrResolved;
if (Lookup(strDest.c_str(), addrResolved, port, fNameLookup && !HaveNameProxy(), 256)) {
if (addrResolved.size() > 0) {
addr = addrResolved[GetRand(addrResolved.size())];
return ConnectSocket(addr, hSocketRet, nTimeout);
}
}
addr = CService();
if (!HaveNameProxy())
return false;
return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
}
bool LookupSubNet(const char* pszName, CSubNet& ret)
{
std::string strSubnet(pszName);
size_t slash = strSubnet.find_last_of('/');
std::vector<CNetAddr> vIP;
std::string strAddress = strSubnet.substr(0, slash);
if (LookupHost(strAddress.c_str(), vIP, 1, false))
{
CNetAddr network = vIP[0];
if (slash != strSubnet.npos) {
std::string strNetmask = strSubnet.substr(slash + 1);
int32_t n;
// IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax
ret = CSubNet(network, n);
return ret.IsValid();
} else // If not a valid number, try full netmask syntax
{
// Never allow lookup for netmask
if (LookupHost(strNetmask.c_str(), vIP, 1, false)) {
ret = CSubNet(network, vIP[0]);
return ret.IsValid();
}
}
} else {
ret = CSubNet(network);
return ret.IsValid();
}
}
return false;
}
#ifdef WIN32
std::string NetworkErrorString(int err)
{
char buf[256];
buf[0] = 0;
if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, sizeof(buf), NULL)) {
return strprintf("%s (%d)", buf, err);
} else {
return strprintf("Unknown error (%d)", err);
}
}
#else
std::string NetworkErrorString(int err)
{
char buf[256];
const char* s = buf;
buf[0] = 0;
/* Too bad there are two incompatible implementations of the
* thread-safe strerror. */
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
return strprintf("%s (%d)", s, err);
}
#endif
bool CloseSocket(SOCKET& hSocket)
{
if (hSocket == INVALID_SOCKET)
return false;
#ifdef WIN32
int ret = closesocket(hSocket);
#else
int ret = close(hSocket);
#endif
hSocket = INVALID_SOCKET;
return ret != SOCKET_ERROR;
}
bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
{
if (fNonBlocking) {
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
} else {
#ifdef WIN32
u_long nZero = 0;
if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
}
return true;
}
|
#include "cavs/midend/edge.h"
using std::string;
namespace midend {
Edge::Edge(const string& name, Scope* s)
: name_(name), located_(s), isDynamicEnabled_(false) {
located_->AddEdge(this);
}
inline string Edge::scoped_name() const {
return located_->scoped_name() + ":" + name();
}
void Edge::AddDst(Node* node) {
dsts_.push_back(node);
if (node->scope() == scope())
same_scoped_dsts_.push_back(node);
}
DataType Edge::dtype() const {
CHECK(src_size() > 0 && src(0)->IsSingleNode());
return dynamic_cast<SingleNode*>(src(0))->dtype();
}
void Edge::AddSource(Node* node) {
//we loose the constraint to gradients.
//In the lstm cases, one tensor should be
//transmitted to two or more operators, and therefore
//the gradients come from two or more operators
CHECK(isVariable() || isGradient() || srcs_.empty())
<< node->debug_info()
<< debug_info();
srcs_.push_back(node);
if (node->scope() == scope())
same_scoped_srcs_.push_back(node);
}
void Edge::AddControlDependency(const Node* n) {
CHECK(n->scope() == scope());
control_dependency_on_me_.push_back(const_cast<Node*>(n));
}
string Edge::debug_info() const {
string ret = "\nname:\t" + scoped_name() +
"\nshape:\t" + shape().DebugString() +
"scope:\t" + located_->name() +
"\tsrcs_size:\t" + std::to_string(src_size()) +
"\ndsts_size:\t" + std::to_string(dst_size());
for (int i = 0; i < src_size(); i++)
ret += "\nsrc[" + std::to_string(i) + "]:\t" + src(i)->debug_info();
for (int i = 0; i < dst_size(); i++)
ret += "\ndst[" + std::to_string(i) + "]:\t" + dst(i)->debug_info();
return ret;
}
} //namespace midend
|
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "Core/Config/Engine.Config.h"
#ifdef GRAPHICS_API_VULKAN
#include "Engine/Platforms/Vulkan/110/Vk1BaseModule.h"
#include "Engine/Platforms/Vulkan/110/Vk1SamplerCache.h"
#include "Engine/Platforms/Vulkan/VulkanObjectsConstructor.h"
#include "Engine/Platforms/Public/Tools/SamplerUtils.h"
namespace Engine
{
namespace PlatformVK
{
//
// Vulkan Sampler
//
class Vk1Sampler final : public Vk1BaseModule
{
// types
private:
using SupportedMessages_t = Vk1BaseModule::SupportedMessages_t::Append< MessageListFrom<
GpuMsg::GetSamplerDescription,
GpuMsg::GetVkSamplerID
> >;
using SupportedEvents_t = Vk1BaseModule::SupportedEvents_t;
// constants
private:
static const TypeIdList _eventTypes;
// variables
private:
SamplerDescription _descr;
vk::VkSampler _samplerId;
// methods
public:
Vk1Sampler (UntypedID_t, GlobalSystemsRef gs, const CreateInfo::GpuSampler &ci);
~Vk1Sampler ();
SamplerDescription const& GetDescription () const { return _descr; }
// message handlers
private:
bool _Compose (const ModuleMsg::Compose &);
bool _Delete (const ModuleMsg::Delete &);
bool _GetVkSamplerID (const GpuMsg::GetVkSamplerID &);
bool _GetSamplerDescription (const GpuMsg::GetSamplerDescription &);
private:
bool _IsCreated () const;
bool _CreateSampler ();
void _DestroySampler ();
};
//-----------------------------------------------------------------------------
const TypeIdList Vk1Sampler::_eventTypes{ UninitializedT< SupportedEvents_t >() };
/*
=================================================
constructor
=================================================
*/
Vk1Sampler::Vk1Sampler (UntypedID_t id, GlobalSystemsRef gs, const CreateInfo::GpuSampler &ci) :
Vk1BaseModule( gs, ModuleConfig{ id, UMax }, &_eventTypes ),
_descr( ci.descr ),
_samplerId( VK_NULL_HANDLE )
{
SetDebugName( "Vk1Sampler" );
_SubscribeOnMsg( this, &Vk1Sampler::_OnModuleAttached_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_OnModuleDetached_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_AttachModule_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_DetachModule_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_FindModule_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_ModulesDeepSearch_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_Link_Impl );
_SubscribeOnMsg( this, &Vk1Sampler::_Compose );
_SubscribeOnMsg( this, &Vk1Sampler::_Delete );
_SubscribeOnMsg( this, &Vk1Sampler::_OnManagerChanged );
_SubscribeOnMsg( this, &Vk1Sampler::_GetVkSamplerID );
_SubscribeOnMsg( this, &Vk1Sampler::_GetSamplerDescription );
_SubscribeOnMsg( this, &Vk1Sampler::_GetDeviceInfo );
_SubscribeOnMsg( this, &Vk1Sampler::_GetVkDeviceInfo );
_SubscribeOnMsg( this, &Vk1Sampler::_GetVkPrivateClasses );
ASSERT( _ValidateMsgSubscriptions< SupportedMessages_t >() );
_AttachSelfToManager( _GetGPUThread( ci.gpuThread ), UntypedID_t(0), true );
}
/*
=================================================
destructor
=================================================
*/
Vk1Sampler::~Vk1Sampler ()
{
ASSERT( not _IsCreated() );
}
/*
=================================================
_Compose
=================================================
*/
bool Vk1Sampler::_Compose (const ModuleMsg::Compose &msg)
{
if ( _IsComposedState( GetState() ) )
return true; // already composed
CHECK_ERR( GetState() == EState::Linked );
CHECK_COMPOSING( _CreateSampler() );
_SendForEachAttachments( msg );
// very paranoic check
CHECK( _ValidateAllSubscriptions() );
CHECK( _SetState( EState::ComposedImmutable ) );
_SendUncheckedEvent( ModuleMsg::AfterCompose{} );
return true;
}
/*
=================================================
_Delete
=================================================
*/
bool Vk1Sampler::_Delete (const ModuleMsg::Delete &msg)
{
_DestroySampler();
return Module::_Delete_Impl( msg );
}
/*
=================================================
_GetVkSamplerID
=================================================
*/
bool Vk1Sampler::_GetVkSamplerID (const GpuMsg::GetVkSamplerID &msg)
{
ASSERT( _IsCreated() );
msg.result.Set( _samplerId );
return true;
}
/*
=================================================
_GetSamplerDescription
=================================================
*/
bool Vk1Sampler::_GetSamplerDescription (const GpuMsg::GetSamplerDescription &msg)
{
msg.result.Set( _descr );
return true;
}
/*
=================================================
_IsCreated
=================================================
*/
bool Vk1Sampler::_IsCreated () const
{
return _samplerId != VK_NULL_HANDLE;
}
/*
=================================================
_CreateSampler
=================================================
*/
bool Vk1Sampler::_CreateSampler ()
{
using namespace vk;
CHECK_ERR( not _IsCreated() );
const bool unnorm_coords = (_descr.AddressMode().x == EAddressMode::ClampUnnorm) or
(_descr.AddressMode().y == EAddressMode::ClampUnnorm);
VkSamplerCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
info.flags = 0;
info.magFilter = EFilter::IsMagLinear( _descr.Filter() ) ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
info.minFilter = EFilter::IsMinLinear( _descr.Filter() ) ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
info.mipmapMode = EFilter::IsMipmapLinear( _descr.Filter() ) ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
info.addressModeU = Vk1Enum( _descr.AddressMode().x );
info.addressModeV = Vk1Enum( _descr.AddressMode().y );
info.addressModeW = Vk1Enum( _descr.AddressMode().z );
info.borderColor = Vk1Enum( _descr.BorderColor() );
if ( not unnorm_coords )
{
info.mipLodBias = 0.0f; // TODO
info.minLod = 0.0f; // TODO
info.maxLod = 1024.0f; // TODO
info.compareEnable = _descr.CompareOp() != ECompareFunc::None;
info.compareOp = info.compareEnable ? Vk1Enum( _descr.CompareOp() ) : VK_COMPARE_OP_ALWAYS;
const uint aniso = EFilter::GetAnisotropic( _descr.Filter() );
info.anisotropyEnable = aniso > 0;
info.maxAnisotropy = float(aniso); // TODO
}
info.unnormalizedCoordinates = unnorm_coords;
VK_CHECK( vkCreateSampler( GetVkDevice(), &info, null, OUT &_samplerId ) );
GetDevice()->SetObjectName( ReferenceCast<uint64_t>(_samplerId), GetDebugName(), EGpuObject::Sampler );
return true;
}
/*
=================================================
_DestroySampler
=================================================
*/
void Vk1Sampler::_DestroySampler ()
{
using namespace vk;
auto dev = GetVkDevice();
if ( dev != VK_NULL_HANDLE and _samplerId != VK_NULL_HANDLE )
{
vkDestroySampler( dev, _samplerId, null );
}
_samplerId = VK_NULL_HANDLE;
_descr = Uninitialized;
}
//-----------------------------------------------------------------------------
/*
=================================================
SearchableSampler
=================================================
*/
inline bool Vk1SamplerCache::SearchableSampler::operator == (const SearchableSampler &right) const { return samp->GetDescription() == right.samp->GetDescription(); }
inline bool Vk1SamplerCache::SearchableSampler::operator > (const SearchableSampler &right) const { return samp->GetDescription() > right.samp->GetDescription(); }
//-----------------------------------------------------------------------------
/*
=================================================
SamplerSearch
=================================================
*/
inline bool Vk1SamplerCache::SamplerSearch::operator == (const SearchableSampler &right) const { return descr == right.samp->GetDescription(); }
inline bool Vk1SamplerCache::SamplerSearch::operator > (const SearchableSampler &right) const { return descr > right.samp->GetDescription(); }
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
Vk1SamplerCache::Vk1SamplerCache (Ptr<Vk1Device> dev) :
Vk1BaseObject( dev )
{
_samplers.Reserve( 16 );
}
/*
=================================================
Create
=================================================
*/
Vk1SamplerCache::Vk1SamplerPtr Vk1SamplerCache::Create (ModuleMsg::UntypedID_t id, GlobalSystemsRef gs, const CreateInfo::GpuSampler &ci)
{
SamplerDescription descr = ci.descr;
PlatformTools::SamplerUtils::ValidateDescription( INOUT descr, GetMaxAnisotropyLevel() );
// find cached sampler
Samplers_t::const_iterator iter;
if ( _samplers.CustomSearch().Find( SamplerSearch( descr ), OUT iter ) and
iter->samp->GetState() == Module::EState::ComposedImmutable )
{
return iter->samp;
}
// create new sampler
CreateInfo::GpuSampler create_info;
create_info.gpuThread = ci.gpuThread;
create_info.descr = descr;
auto result = New< Vk1Sampler >( id, gs, create_info );
ModuleUtils::Initialize({ result });
CHECK_ERR( result->GetState() == Module::EState::ComposedImmutable );
_samplers.Add( SearchableSampler( result ) );
return result;
}
/*
=================================================
Destroy
=================================================
*/
void Vk1SamplerCache::Destroy ()
{
for (auto& sampler : _samplers) {
sampler.samp->Send( ModuleMsg::Delete{} );
}
_samplers.Clear();
}
} // PlatformVK
//-----------------------------------------------------------------------------
namespace Platforms
{
ModulePtr VulkanObjectsConstructor::CreateVk1Sampler (ModuleMsg::UntypedID_t id, GlobalSystemsRef gs, const CreateInfo::GpuSampler &ci)
{
ModulePtr mod;
CHECK_ERR( mod = gs->parallelThread->GetModuleByMsg< ModuleMsg::MessageListFrom< GpuMsg::GetVkPrivateClasses >>() );
GpuMsg::GetVkPrivateClasses req_classes;
mod->Send( req_classes );
CHECK_ERR( req_classes.result and req_classes.result->samplerCache );
return req_classes.result->samplerCache->Create( id, gs, ci );
}
} // Platforms
} // Engine
#endif // GRAPHICS_API_VULKAN
|
// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>
#include <keystore.h>
#include <policy/policy.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/interpreter.h>
#include <script/sign.h>
#include <script/ismine.h>
#include <uint256.h>
#include <test/test_bitcoin.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup)
static CScript
sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction, int whichIn)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL, FORKID_NONE, 0, SigVersion::BASE);
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
for (const CKey &key : keys)
{
std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
}
return result;
}
BOOST_AUTO_TEST_CASE(multisig_verify)
{
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
ScriptError err;
CKey key[4];
CAmount amount = 0;
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CMutableTransaction txTo[3]; // Spending transaction
for (int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
std::vector<CKey> keys;
CScript s;
// Test a AND b:
keys.assign(1,key[0]);
keys.push_back(key[1]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK(VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
for (int i = 0; i < 4; i++)
{
keys.assign(1,key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 1: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
keys.assign(1,key[1]);
keys.push_back(key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 2: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
// Test a OR b:
for (int i = 0; i < 4; i++)
{
keys.assign(1,key[i]);
s = sign_multisig(a_or_b, keys, txTo[1], 0);
if (i == 0 || i == 1)
{
BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
else
{
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
}
s.clear();
s << OP_0 << OP_1;
BOOST_CHECK(!VerifyScript(s, a_or_b, nullptr, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err));
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
keys.assign(1,key[i]);
keys.push_back(key[j]);
s = sign_multisig(escrow, keys, txTo[2], 0);
if (i < j && i < 3 && j < 3)
{
BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, nullptr, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 1: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
else
{
BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, nullptr, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 2: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
}
}
BOOST_AUTO_TEST_CASE(multisig_IsStandard)
{
CKey key[4];
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
txnouttype whichType;
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_and_b, whichType));
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_or_b, whichType));
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(escrow, whichType));
CScript one_of_four;
one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG;
BOOST_CHECK(!::IsStandard(one_of_four, whichType));
CScript malformed[6];
malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG;
malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG;
malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey());
for (int i = 0; i < 6; i++)
BOOST_CHECK(!::IsStandard(malformed[i], whichType));
}
BOOST_AUTO_TEST_CASE(multisig_Sign)
{
// Test SignSignature() (and therefore the version of Solver() that signs transactions)
CBasicKeyStore keystore;
CKey key[4];
for (int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CMutableTransaction txTo[3]; // Spending transaction
for (int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
for (int i = 0; i < 3; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0, SIGHASH_ALL), strprintf("SignSignature %d", i));
}
}
BOOST_AUTO_TEST_SUITE_END()
|
//===-test_or_bcast3v2d_popart.cc-----------------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
// clang-format off
// Testing CXX Code Gen using ODLA API on popart
// RUN: %halo_compiler -target cxx -o %data_path/test_or_bcast3v2d/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_or_bcast3v2d/test_data_set_0/input_0.pb
// RUN: %halo_compiler -target cxx -o %data_path/test_or_bcast3v2d/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_or_bcast3v2d/test_data_set_0/output_0.pb
// RUN: %halo_compiler -target cxx -o %data_path/test_or_bcast3v2d/test_data_set_0/input_1.cc -x onnx -emit-data-as-c %data_path/test_or_bcast3v2d/test_data_set_0/input_1.pb
// RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_or_bcast3v2d/model.onnx -o %t.cc
// RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include
// RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_or_bcast3v2d/test_data_set_0 %odla_link %device_link -lodla_popart -o %t_popart.exe -Wno-deprecated-declarations
// RUN: %t_popart.exe 0.0001 0 popart %data_path/test_or_bcast3v2d | FileCheck %s
// CHECK: Result Pass
// clang-format on
#include "test_or_bcast3v2d_popart.cc.tmp.main.cc.in"
|
/*
* Ausgangstreiber für ESP32-Fischertechnik-Anbindung
* Autor: Johannes Marquart
*
* modified by: F.J.P
* date: 2020-10-27
*/
#include "ft_ESP32_IOobjects.h"
int PORT_M_PWM[MOTOR_QTY]; // = {};//Output-Pins Motor-Drehzahl
int PORT_IN[DAIN_QTY]; //Input-Pins Ditital/Analog
bool ISMAXI = false;
/* ====================================================================================================================== */
/* i2c SDA = PIN 21, SCL = PIN 22 */
SX1509 sx1509Object;
/* led strip, connected to pin LED_PIN */
Adafruit_NeoPixel * led_strip = new Adafruit_NeoPixel(LED_QTY, LED_PIN, NEO_GRB + NEO_KHZ800);
/* ====================================================================================================================== */
CheckMaxiExtension::CheckMaxiExtension() {
mAddress = SX1509_I2C_ADDRESS;
mBoard = "";
}
CheckMaxiExtension::CheckMaxiExtension(byte address) {
mAddress = address;
mBoard = "";
}
bool CheckMaxiExtension::CheckMaxi() {
delay(1500); //etwas warten, damit I2C möglich ist (ansonsten Kommunikationsprobleme)
if (!sx1509Object.begin(SX1509_I2C_ADDRESS)) //starten des SX1509 mit SX1509-I²C-Adresse, wenn false (Fehler erkannt -> kein SX1509 angeschlossen)
{
Serial.println("[io] SX1509-Object could not be initialized.");
mBoard = "MINI";
ISMAXI = false;
Serial.println("[io] mini board activated");
//Zuweisung Ports
for (int i = 0; i < MOTOR_QTY; i++)
{
PORT_M_PWM[i] = MINI_PORT_M_PWM[i];
}
for (int i = 0; i < DAIN_QTY; i++)
{
PORT_IN[i] = MINI_PORT_IN[i];
}
return false;
}
else //wenn true (SX1509 angeschlossen)
{
Serial.println("[io] SX1509-Object initialized.");
sx1509Object.clock(INTERNAL_CLOCK_2MHZ, 4); //Einrichten der Frequenz
Serial.println("[io] maxi board activated");
mBoard = "MAXI";
ISMAXI = true;
//Zuweisung Ports
for (int i = 0; i < MOTOR_QTY; i++)
{
PORT_M_PWM[i] = MAXI_PORT_M_PWM[i];
}
for (int i = 0; i < DAIN_QTY; i++)
{
PORT_IN[i] = MAXI_PORT_IN[i];
}
return true;
}
}
/* ====================================================================================================================== */
Motor::Motor() {
//Abschalten des Motortreibers, welcher von diesem Objekt versorgt wird.
//Evtl. noch undefinierte Pins können so kein falsches Signal an den Motortreiber geben
pinMode(PIN_M_INH, OUTPUT);
digitalWrite(PIN_M_INH, LOW);
mMotorNr = 0;
mPortNrPWM = 0;
mPortNrDir = 0;
mDirectionMode = 1;
mDrehzahl = 0;
}
Motor::Motor(unsigned int motorNr) {
//Abschalten des Motortreibers, evtl. noch undefinierte Pins können so kein falsches Signal an den Motortreiber geben
pinMode(PIN_M_INH, OUTPUT);
digitalWrite(PIN_M_INH, LOW);
//Initialisieren des Motorobjektes
mMotorNr = motorNr;
mPortNrPWM = 0;
mPortNrDir = 0;
mDirectionMode = 2;
mDrehzahl = 0;
/*
if (ISMAXI)
{
mPortNrDir = SX1509_PORT_M_DIR[mMotorNr];
}
else
{
mPortNrDir = PORT_M_DIR[mMotorNr];
}
*/
// mPortNrPWM = PORT_M_PWM[mMotorNr];
// //Zuweisen PWM-Generator zu Pin. Generator 0,2,4,6 für Drehzahl
// ledcAttachPin(mPortNrPWM, mMotorNr*2); //Pin-Nr für Drehzahl, PWM-Generator Nr
// ledcSetup(mMotorNr*2, 21700, 8); //PWM-Generator Nr, 21.7 kHz PWM, 8-bit resolution (0..255)
// ledcWrite(mMotorNr*2, 0); //frühzeitiges Definieren des PWM-Generators (PWM-Generator Nr., PWM-Wert (0..255))
// // Zuweisen der Direction
// if (ISMAXI)
// {
// sx1509Object.digitalWrite(mPortNrDir, 1);
// }
// else
// {
// //Zuweisen PWM-Generator zu Pin. Generator 1,3,5,7 für Richtung
// ledcAttachPin(mPortNrDir, (mMotorNr*2)+1); //Pin-Nr für Richtungsangabe, PWM-Generator Nr
// ledcSetup(mMotorNr*2+1, 21700, 8);
// ledcWrite(mMotorNr*2+1,255); //frühzeitiges Definieren des Dir-Pins
// }
}
void Motor::setMaxi(bool pMaxi) {
mPortNrPWM = PORT_M_PWM[mMotorNr];
if (pMaxi)
{
//Zuweisen PWM-Generator zu Pin. Generator 0, 1, 2, 3 für Drehzahl
ledcAttachPin(mPortNrPWM, mMotorNr); //Pin-Nr für Drehzahl, PWM-Generator Nr
ledcSetup(mMotorNr, 21700, 8); //PWM-Generator Nr, 21.7 kHz PWM, 8-bit resolution (0..255)
ledcWrite(mMotorNr, 0); //frühzeitiges Definieren des PWM-Generators (PWM-Generator Nr., PWM-Wert (0..255))
mPortNrDir = SX1509_PORT_M_DIR[mMotorNr];
sx1509Object.digitalWrite(mPortNrDir, 1);
}
else
{
//Zuweisen PWM-Generator zu Pin. Generator 0,2,4,6 für Drehzahl
ledcAttachPin(mPortNrPWM, mMotorNr*2); //Pin-Nr für Drehzahl, PWM-Generator Nr
ledcSetup(mMotorNr*2, 21700, 8); //PWM-Generator Nr, 21.7 kHz PWM, 8-bit resolution (0..255)
ledcWrite(mMotorNr*2, 0); //frühzeitiges Definieren des PWM-Generators (PWM-Generator Nr., PWM-Wert (0..255))
mPortNrDir = PORT_M_DIR[mMotorNr];
//Zuweisen PWM-Generator zu Pin. Generator 1,3,5,7 für Richtung
ledcAttachPin(mPortNrDir, (mMotorNr*2)+1); //Pin-Nr für Richtungsangabe, PWM-Generator Nr
ledcSetup((mMotorNr*2)+1, 21700, 8);
ledcWrite((mMotorNr*2)+1, 255); //frühzeitiges Definieren des Dir-Pins
}
}
void Motor::setValues(unsigned char directionMode, unsigned int drehzahl) {
/*
* mDirectionMode:
* 0 -> right
* 1 -> left
* 2 -> brake
*/
mDirectionMode = directionMode;
mDrehzahl = drehzahl;
digitalWrite(PIN_M_INH, LOW);
Serial.print("[io] Motor " + (String)mMotorNr);
Serial.print(" dreht in Richtung " + (String)mDirectionMode);
Serial.println(" mit Drehzahl " + (String)mDrehzahl);
//Berechnen der PWM-Werte
int drehzahl_pwm;
if (mDrehzahl < 1) {
drehzahl_pwm = 0; //170
} else if (mDrehzahl > 49) {
drehzahl_pwm = 255;
} else {
drehzahl_pwm = 170 + mDrehzahl * (85 / 50); //170+mDrehzahl*85/8
Serial.println("Drehzahl PWM: " + (String)drehzahl_pwm);
}
//Zuweisen der Richtung an den richtigen Pin entsprechend der Motornr.
// mDirectionMode == 1 -> right
if (mDirectionMode == 1) {
//digitalWrite(mPortNrDir, HIGH);
if (ISMAXI) {
sx1509Object.digitalWrite(mPortNrDir, 1); //Richtungspin wird auf HIGH - Rechtslauf gesetzt
}
if(mMotorNr==0 || mMotorNr==2) {
analogWrite(PORT_M_0[1],0);
analogWrite(PORT_M_0[0],drehzahl_pwm);
} else if (mMotorNr==1 || mMotorNr==3) {
analogWrite(PORT_M_1[1],0);
analogWrite(PORT_M_1[0],drehzahl_pwm);
}
}
// mDirectionMode == 1 -> right
else if (mDirectionMode == 0) {
//digitalWrite(mPortNrDir, LOW);
if (ISMAXI) {
sx1509Object.digitalWrite(mPortNrDir, 0); //Richtungspin wird auf LOW - Linkslauf gesetzt
}
if (mMotorNr==0 ||mMotorNr==2) {
analogWrite(PORT_M_0[0],0);
analogWrite(PORT_M_0[1],drehzahl_pwm);
} else if (mMotorNr==1 || mMotorNr==3) {
analogWrite(PORT_M_1[0],0);
analogWrite(PORT_M_1[1],drehzahl_pwm);
}
}
// mDirectionMode == 2 -> brake
else {
digitalWrite(PIN_M_INH, HIGH); //Einschalten Motortreiber
if(mMotorNr==0 || mMotorNr==2) {
analogWrite(PORT_M_0[1], -1);
analogWrite(PORT_M_0[0], -1);
} else if (mMotorNr==1 || mMotorNr==3) {
analogWrite(PORT_M_1[1], -1);
analogWrite(PORT_M_1[0], -1);
}
}
digitalWrite(PIN_M_INH, HIGH); //Einschalten Motortreiber
//Serial.print(" raw: DirPin: " + (String)mPortNrDir);
//Serial.print(mPortNrDir);
//Serial.print(" PWMPin: " + (String)mPortNrPWM);
//Serial.print(mPortNrPWM);
//Serial.println(" Val: " + (String)drehzahl_pwm);
//Serial.println(drehzahl_pwm);
}
void Motor::reRun() {
if(mDrehzahl > 0)
{
setValues(mDirectionMode, mDrehzahl);
}
}
/* ====================================================================================================================== */
CServoMotor::CServoMotor() {
mMotorNr = 0;
mPortNrPWM = 0;
mMinDuty = 4;
mMaxDuty = 11;
mRelDuty = 0;
}
CServoMotor::CServoMotor(unsigned int motorNr, unsigned int dutyCycle) {
mPortNrPWM = 13;
//init of servomotor-object
mMotorNr = motorNr;
//mPinNrPWM = PIN_M_PWM[motorNr];
mMinDuty = 11; //minimal real DutyCycle in %
mMaxDuty = 4; //maximal real DutyCycle in %
mRelDuty = dutyCycle < 100 ? dutyCycle : 100; //limiting maximum value to 100(%)
//mLedcChannel = 4; //channel 4 - servo only used at mini-board -> only channels 0..3 are used by motors
mLedcChannel=10;
ledcAttachPin(mPortNrPWM, mLedcChannel); //Pin-Nr für Drehzahl, PWM-Generator Nr
ledcSetup(mLedcChannel, 50, 12); //PWM-Generator Nr, 50 Hz PWM, 12-bit resolution (0..255)
}
void CServoMotor::setMaxi(bool pMaxi) {
mPortNrPWM = 13;// PORT_M_PWM[mMotorNr];
if (pMaxi)
{
//Servomotoren funktionieren noch nicht am Maxi-Board
}
else
{
//Zuweisen PWM-Generator zu Pin. Generator 0,2,4,6 für Drehzahl
ledcAttachPin(mPortNrPWM, mLedcChannel); //Pin-Nr für Drehzahl, PWM-Generator Nr
ledcSetup(mLedcChannel, 50, 12); //PWM-Generator Nr, 50 Hz PWM, 12-bit resolution (0..255)
ledcWrite(mLedcChannel, (4095 * (100 * mMinDuty + (mMaxDuty - mMinDuty) * mRelDuty)) / 10000); //early set of pin -> servo moves to given duty-cycle
}
}
void CServoMotor::setValues(unsigned int dutyCycle) {
if (!ISMAXI)
{
mRelDuty = dutyCycle < 100 ? dutyCycle : 100; //limiting maximum value to 100(%)
Serial.print("[io] Servo ");
Serial.print(mMotorNr);
Serial.print(" auf Pos ");
Serial.println(mRelDuty);
//analogWrite(mPortNrPWM, (4095 * (100 * mMinDuty + (mMaxDuty - mMinDuty) * mRelDuty)) / 10000);
ledcWrite(mLedcChannel, (4095 * (100 * mMinDuty + (mMaxDuty - mMinDuty) * mRelDuty)) / 10000); //calculate real duty-cycle for servos: 0%rel = 4%, 100%rel = 11%
}
}
void CServoMotor::reRun() {
if (!ISMAXI)
{
//analogWrite(mPortNrPWM, (4095 * (100 * mMinDuty + (mMaxDuty - mMinDuty) * mRelDuty)) / 10000);
ledcWrite(mLedcChannel, (4095 * (100 * mMinDuty + (mMaxDuty - mMinDuty) * mRelDuty)) / 10000);
}
}
/* ====================================================================================================================== */
void led_init() {
/* initialize led strip */
pinMode(LED_PIN,OUTPUT);
led_strip->begin();
led_strip->show();
}
void led_clear() {
/* clear buffer (pixel information) and update through show() */
led_strip->clear();
led_strip->show();
}
void led_reset(String &option, array<Led, LED_QTY> &ledArray) {
if(option == "A") {
for(int i=0; i < LED_QTY; i++) {
ledArray.at(i).setValues(0, 0); //Ausgang zur 0 setzen
}
Serial.println("[io] Setze alle LEDs zurueck ...");
} else {
ledArray.at(option.toInt()).setValues(0, 0);
Serial.println("[io] Setze LED" + option + " zurueck ...");
}
}
void led_update(array<Led, LED_QTY> &ledArray) {
for(int i=0; i < LED_QTY; i++) {
ledArray[i].reRun();
}
/* update led strip */
led_strip->show();
}
void led_update(Led ledArray[]) {
/* update led strip */
led_strip->clear();
for(int i=0; i < LED_QTY; i++) {
ledArray[i].reRun();
}
led_strip->show();
}
Led::Led() {
//Abschalten des Ledntreibers, welcher von diesem Objekt versorgt wird und setzen der default Werte
mLedNr = 0;
mColor = 0; // -> RED
mColorName = "RED";
mBrightness = 0;
mColorRGB[0] = 255;
mColorRGB[1] = 0;
mColorRGB[2] = 0;
}
Led::Led(unsigned int ledNr) {
//Initialisieren des Led-objektes
mLedNr = ledNr;
mColor = 0; // -> Off
mColorName = "RED";
mBrightness = 0;
mColorRGB[0] = 255;
mColorRGB[1] = 0;
mColorRGB[2] = 0;
}
void Led::setMaxi(bool pMaxi) {
/* TODO */
}
void Led::setValues(int brightness, int ledColor) {
mColor = ledColor;
mBrightness = brightness;
setLedRGBColorByIdentifier(ledColor, brightness);
Serial.print("[io] led " + (String)mLedNr + " leuchtet mit Helligkeit ");
Serial.print(mBrightness);
Serial.println(" und Farbe " + getRGBColorName());
led_strip->setPixelColor(mLedNr,mColorRGB[0],mColorRGB[1],mColorRGB[2]);
}
void Led::reRun() {
if(mBrightness > 0) {
led_strip->setPixelColor(mLedNr,mColorRGB[0],mColorRGB[1],mColorRGB[2]);
}
}
void Led::setLedRGBColorByIdentifier(int colorNumber, int brigthness) {
mColorRGB[0] = 0;
mColorRGB[1] = 0;
mColorRGB[2] = 0;
if(brigthness >= 0 && brigthness < 256) {
switch(colorNumber) {
case 0:
mColorName = "Off";
mColorRGB[0] = 0;
mColorRGB[1] = 0;
mColorRGB[2] = 0;
break;
case 1:
mColorName = "RED";
mColorRGB[0] = brigthness;
break;
case 2:
mColorName = "GREEN";
mColorRGB[1] = brigthness;
break;
case 3:
mColorName = "BLUE";
mColorRGB[2] = brigthness;
break;
default:
mColorName = "RED";
mColorRGB[0] = 255;
break;
}
} else {
mColorName = "RED";
mColorRGB[0] = 255;
}
}
String Led::getRGBColorName() {
return mColorName;
}
/* ====================================================================================================================== */
// ===== ENCODERSTEUERUNG
// Für ISR müssen einige Elemente global definiert werden:
// Interrupt-Service-Routinen ==> Hochzählen der Encoder-Zähler
// Folgende Variablen müssen (leider) in der c++-Datei deklariert werden.
// Andernfalls kommt es zu include-Fehlern.
// Die Absolut-Encoderzähler werden zur Bestimmung der Reglerabweichung verwendet
// und zur Erkennung, ob der Roboter die gewünschte Strecke gefahren ist.
int encPosAbs0;
int encPosAbs1;
// Variablen zur Entprellung der Lichtschrankensignale
int64_t time_ISREnc0[2];
int64_t time_ISREnc1[2];
// Interrupt-Service-Routinen zur Flankenzählung der Encoder
void ISREnc0() {
// Entprellen: Prüfen, ob seit letztem Schritt mind. 5ms vergangen sind
time_ISREnc0[0] = esp_timer_get_time();
if(time_ISREnc0[0] - time_ISREnc0[1] > 2000) {
// Zähler inkrementieren und Zeit speichern
encPosAbs0++;
time_ISREnc0[1] = time_ISREnc0[0];
}
}
void ISREnc1() {
// Entprellen: Prüfen, ob seit letztem Schritt mind. 5ms vergangen sind
time_ISREnc1[0] = esp_timer_get_time();
if(time_ISREnc1[0] - time_ISREnc1[1] > 2000) {
// Zähler inkrementieren und Zeit speichern
encPosAbs1++;
time_ISREnc1[1] = time_ISREnc1[0];
}
}
// Konstruktor
CEncoderStrecke::CEncoderStrecke() {}
// Beide Encoder aktivieren ==> Impulse werden gezählt
// Zusätzlich alle erforderlichen Variablen zurücksetzen
void CEncoderStrecke::enableInterrupts() {
// Variablen zurücksetzen
// Encoder-Zähler und Entprell-Zeiten zurücksetzen
encPosAbs0 = 0;
encPosAbs1 = 0;
time_ISREnc0[1] = 0;
time_ISREnc1[1] = 0;
// Abtastzeit für den Regler zurücksetzen
time_ReglerInt[0] = esp_timer_get_time();
// Reglervariablen zurücksetzen
integrierer = 0;
RegAbweichung[0] = 0;
RegStellgr[0] = 0;
RegStellgr[1] = 0;
diff[0] = 0;
// Encoderpins konfigurieren, Interrupts hinzufügen
pinMode(PIN_ENCODER_0, INPUT);
pinMode(PIN_ENCODER_1, INPUT);
attachInterrupt(PIN_ENCODER_0, ISREnc0, RISING);
attachInterrupt(PIN_ENCODER_1, ISREnc1, RISING);
Serial.println("Beide Encoder aktiv");
}
// Beide Encoder deaktivieren ==> es werden keine weiteren Impulse gezählt
void CEncoderStrecke::disableInterrupts() {
// Interrupts deaktivieren
detachInterrupt(PIN_ENCODER_0);
detachInterrupt(PIN_ENCODER_1);
Serial.println("Beide Encoder deaktiviert");
}
void CEncoderStrecke::enableMotors() {
// Motortreiber muss bereits aktiv sein, bevor die Reglerfunktion gestartet wird:
pinMode(PIN_M_INH, OUTPUT); // Pin konfigurieren
digitalWrite(PIN_M_INH, HIGH); // Einschalten Motortreiber
// PWM-Basiswert setzen (Basisgeschwindigkeit des Roboters)
// Motoren zunächst stoppen
setMotorSpeed(0.0f, 0.0f);
// PWM-Kanäle einrichten: Kanal0 für Motor0, Kanal1 für Motor1
ledcSetup(0, 1000, 8);
ledcSetup(1, 1000, 8);
}
void CEncoderStrecke::disableMotors() {
// Motoren stoppen
setMotorSpeed(0.0f, 0.0f);
// Motortreiber ausschalten
digitalWrite(PIN_M_INH, LOW); //Ausschalten Motortreiber
}
// Reglerfunktion: Ausgehend von der aktuellen Rotationsgeschwindigkeit wird die nächste
// Stellgröße für den jeweiligen Motor berechnet und anschließend auf den Motor gegeben.
// Die Sollposition (in cm) wird übergeben. Ist der Return-Wert true, so wurde die Sollposition
// erreicht. Bei false wurde die Position noch nicht erreicht.
bool CEncoderStrecke::reglerStrecke(int posSoll, int richtung) {
// Sollposition von cm in Impulse umrechnen
int anzImpulse = lround(posSoll*1.818);
// Prüfen, ob Sollposition erreicht ==> Regler stoppen
if(encPosAbs0 >= anzImpulse || encPosAbs1 >= anzImpulse) {
// Motoren stoppen
RegStellgr[0] = 0.0f;
RegStellgr[1] = 0.0f;
setMotorSpeed(RegStellgr[0], RegStellgr[1]);
// Die Sollposition der Encoder ist erreicht ==> true zurückgeben und
// Reglerfunktion sofort beenden
return true;
}
// alte Proportionalanteile weiterschieben (für D-Anteil)
RegAbweichung[1] = RegAbweichung[0];
// PROPORTIONALANTEIL der Reglerabweichung bestimmen
RegAbweichung[0] = encPosAbs0 - encPosAbs1;
// Abtastzeiten für die Integrierer weiterschieben: time_ReglerInt[neueZeit,alteZeit]
time_ReglerInt[1] = time_ReglerInt[0]; // alte Zeit weiterschieben
time_ReglerInt[0] = esp_timer_get_time(); // aktuelle Zeit zwischenspeichern
// Zeitdifferenz des Abtastschritts berechnen (in sec)
double timediff = (time_ReglerInt[0] - time_ReglerInt[1])/1000000.0;
// Fehlerüberprüfung: die Zeitdifferenz wird nur verwendet, wenn sie im richtigen Bereich
// (0 bis 2 Sekunden) liegt. Andernfalls ignorieren.
if(timediff < 2.0 && timediff > 0.0) {
// Bei Stellgrößenbeschränkung: Integrierer anhalten (Anti-Windup)
if(RegStellgr[0] > -254.9 && RegStellgr[0] < 254.9 && RegStellgr[1] > -254.9 && RegStellgr[1] < 254.9) {
integrierer += (timediff*RegAbweichung[0]);
}
// DIFFERENZIALANTEIL: Regelabweichung ableiten
diff[1] = diff[0];
diff[0] = (RegAbweichung[0] - RegAbweichung[1] + (TF_ENC - timediff)*diff[1])/TF_ENC;
}
else { // Fehlerausgabe
Serial.print("Abtastzeitdifferenz fehlerhaft: ");
Serial.println(timediff);
}
// P-I-D-Anteile summieren und Stellgröße berechnen (aktuell wird der D-Anteil nicht verwendet,
// da er zu erhöhten Schwingungen führt)
if(richtung == 0) { // vorwärts fahren
RegStellgr[0] = PWM0 - P_ENC*RegAbweichung[0] - 1.0/TN_ENC*integrierer;// - TV_ENC*diff[0];
RegStellgr[1] = PWM0 + P_ENC*RegAbweichung[0] + 1.0/TN_ENC*integrierer;// + TV_ENC*diff[0];
}
else if(richtung == 1) { // rückwärts fahren
RegStellgr[0] = -PWM0 + P_ENC*RegAbweichung[0] + 1.0/TN_ENC*integrierer;// + TV_ENC*diff[0];
RegStellgr[1] = -PWM0 - P_ENC*RegAbweichung[0] - 1.0/TN_ENC*integrierer;// - TV_ENC*diff[0];
}
// PWM-Signal auf die Motoren geben
setMotorSpeed(RegStellgr[0], RegStellgr[1]);
// die Sollposition der Encoder ist momentan noch nicht erreicht
// ==> false zurückgeben
return false;
}
// Reglerfunktion für die Winkelfahrt: Der Roboter dreht sich um einen bestimmten Winkel nach
// rechts oder links
bool CEncoderStrecke::reglerWinkel(int winkelSoll, int richtung) {
// Winkel in Encoderimpulse umrechnen: 2 Umdrehungen (720° entsprechen 172 Radimpulsen)
int anzImpulse = lround(winkelSoll*0.23889);
// Prüfen, ob Sollposition erreicht
if(encPosAbs0 >= anzImpulse || encPosAbs1 >= anzImpulse) {
// Motoren stoppen
RegStellgr[0] = 0.0f;
RegStellgr[1] = 0.0f;
setMotorSpeed(RegStellgr[0], RegStellgr[1]);
// Die Sollposition der Encoder ist erreicht ==> true zurückgeben und
// Reglerfunktion sofort beenden
return true;
}
// alte Proportionalanteile weiterschieben (für D-Anteil)
RegAbweichung[1] = RegAbweichung[0];
// PROPORTIONALANTEIL der Reglerabweichung bestimmen
RegAbweichung[0] = encPosAbs0 - encPosAbs1;
// Abtastzeiten für die Integrierer weiterschieben: time_ReglerInt[neueZeit,alteZeit]
time_ReglerInt[1] = time_ReglerInt[0]; // alte Zeit weiterschieben
time_ReglerInt[0] = esp_timer_get_time(); // aktuelle Zeit zwischenspeichern
// Zeitdifferenz des Abtastschritts berechnen (in sec)
double timediff = (time_ReglerInt[0] - time_ReglerInt[1])/1000000.0;
// Fehlerüberprüfung: die Zeitdifferenz wird nur verwendet, wenn sie im richtigen Bereich
// (0 bis 2 Sekunden) liegt. Andernfalls ignorieren.
if(timediff < 2.0 && timediff > 0.0) {
// Bei Stellgrößenbeschränkung: Integrierer anhalten (Anti-Windup)
if(RegStellgr[0] > -254.9 && RegStellgr[0] < 254.9 && RegStellgr[1] > -254.9 && RegStellgr[1] < 254.9) {
integrierer += (timediff*RegAbweichung[0]);
}
// DIFFERENZIALANTEIL: Regelabweichung ableiten
diff[1] = diff[0];
diff[0] = (RegAbweichung[0] - RegAbweichung[1] + (TF_ENC - timediff)*diff[1])/TF_ENC;
}
else { // Fehlerausgabe
Serial.print("Abtastzeitdifferenz fehlerhaft: ");
Serial.println(timediff);
}
// P-I-D-Anteile summieren und Stellgröße berechnen (aktuell wird der D-Anteil nicht verwendet,
// da er zu erhöhten Schwingungen führt)
// Die Variable "richtung" ist 0 bei links und 1 bei rechts
// bei links: M1 positive Drehrichtung und M0 negative Drehrichtung
if(richtung == 0) { // M1 positiv, M0 negative Drehrichtung
RegStellgr[0] = -PWM0 + P_ENC*RegAbweichung[0] + 1.0/TN_ENC*integrierer;// + TV_ENC*diff[0];
RegStellgr[1] = PWM0 + P_ENC*RegAbweichung[0] + 1.0/TN_ENC*integrierer;// + TV_ENC*diff[0];
}
else if(richtung == 1) { // M1 negativ, M0 positive Drehrichtung
RegStellgr[0] = PWM0 - P_ENC*RegAbweichung[0] - 1.0/TN_ENC*integrierer;// - TV_ENC*diff[0];
RegStellgr[1] = -PWM0 - P_ENC*RegAbweichung[0] - 1.0/TN_ENC*integrierer;// - TV_ENC*diff[0];
}
else {
Serial.println("Fehler: falsche Richtungsvorgabe!");
}
// PWM-Signal auf die Motoren geben
setMotorSpeed(RegStellgr[0], RegStellgr[1]);
// die Sollposition der Encoder ist momentan noch nicht erreicht
// ==> false zurückgeben
return false;
}
// setMotorSpeed: setzt die Rotationsgeschwindigkeit für beide Motoren (zwischen -255 und +255)
// ein negatives Vorzeichen bedeutet eine Umkehr der Drehrichtung
void CEncoderStrecke::setMotorSpeed(float speedM0, float speedM1) {
// Motortreiber muss bereits aktiv sein: Vor dem ersten Aufruf dieser Funktion:
// pinMode(PIN_M_INH, OUTPUT);
// digitalWrite(PIN_M_INH, HIGH); //Einschalten Motortreiber
// // und bereits PWM-Kanäle einrichten:
// ledcSetup(0, 1000, 8);
// ledcSetup(1, 1000, 8);
if (speedM0 > 0.0f) {
if (speedM0 >= 254.9f) {
// Motor läuft mit maximaler Geschwindigkeit
ledcDetachPin(PORT_M_0[0]);
ledcDetachPin(PORT_M_0[1]);
pinMode(PORT_M_0[0], OUTPUT);
pinMode(PORT_M_0[1], OUTPUT);
digitalWrite(PORT_M_0[0], LOW);
digitalWrite(PORT_M_0[1], HIGH);
}
else if(speedM0 >= 0.01f) {
// PWM konfigurieren
ledcDetachPin(PORT_M_0[0]);
ledcAttachPin(PORT_M_0[1], 0);
ledcWrite(0, speedM0);
pinMode(PORT_M_0[0], OUTPUT);
digitalWrite(PORT_M_0[0], LOW);
}
else {
// Motor ausschalten
ledcDetachPin(PORT_M_0[0]);
ledcDetachPin(PORT_M_0[1]);
digitalWrite(PORT_M_0[0], LOW);
digitalWrite(PORT_M_0[1], LOW);
}
} else {
if (speedM0 <= -254.9f) {
// Motor läuft mit maximaler Geschwindigkeit
ledcDetachPin(PORT_M_0[0]);
ledcDetachPin(PORT_M_0[1]);
pinMode(PORT_M_0[0], OUTPUT);
pinMode(PORT_M_0[1], OUTPUT);
digitalWrite(PORT_M_0[0], HIGH);
digitalWrite(PORT_M_0[1], LOW);
}
else if(speedM0 <= -0.01f) {
// PWM konfigurieren
ledcDetachPin(PORT_M_0[1]);
ledcAttachPin(PORT_M_0[0], 0);
ledcWrite(0, -speedM0);
pinMode(PORT_M_0[1], OUTPUT);
digitalWrite(PORT_M_0[1], LOW);
}
else {
// Motor ausschalten
ledcDetachPin(PORT_M_0[0]);
ledcDetachPin(PORT_M_0[1]);
digitalWrite(PORT_M_0[0], LOW);
digitalWrite(PORT_M_0[1], LOW);
}
}
if (speedM1 > 0.0f) {
if (speedM1 >= 254.9f) {
// Motor läuft mit maximaler Geschwindigkeit
ledcDetachPin(PORT_M_1[0]);
ledcDetachPin(PORT_M_1[1]);
pinMode(PORT_M_1[0], OUTPUT);
pinMode(PORT_M_1[1], OUTPUT);
digitalWrite(PORT_M_1[0], LOW);
digitalWrite(PORT_M_1[1], HIGH);
}
else if(speedM1 >= 0.01f) {
// PWM konfigurieren
ledcDetachPin(PORT_M_1[0]);
ledcAttachPin(PORT_M_1[1], 1);
ledcWrite(1, speedM1);
pinMode(PORT_M_1[0], OUTPUT);
digitalWrite(PORT_M_1[0], LOW);
}
else {
// Motor ausschalten
ledcDetachPin(PORT_M_1[0]);
ledcDetachPin(PORT_M_1[1]);
digitalWrite(PORT_M_1[0], LOW);
digitalWrite(PORT_M_1[1], LOW);
}
} else {
if (speedM1 <= -254.9f) {
// Motor läuft mit maximaler Geschwindigkeit
ledcDetachPin(PORT_M_1[0]);
ledcDetachPin(PORT_M_1[1]);
pinMode(PORT_M_1[0], OUTPUT);
pinMode(PORT_M_1[1], OUTPUT);
digitalWrite(PORT_M_1[0], HIGH);
digitalWrite(PORT_M_1[1], LOW);
}
else if(speedM1 <= -0.01f) {
// PWM konfigurieren
ledcDetachPin(PORT_M_1[1]);
ledcAttachPin(PORT_M_1[0], 1);
ledcWrite(1, -speedM1);
pinMode(PORT_M_1[1], OUTPUT);
digitalWrite(PORT_M_1[1], LOW);
}
else {
// Motor ausschalten
ledcDetachPin(PORT_M_1[0]);
ledcDetachPin(PORT_M_1[1]);
digitalWrite(PORT_M_1[0], LOW);
digitalWrite(PORT_M_1[1], LOW);
}
}
}
/* ====================================================================================================================== */
DigitalAnalogIn::DigitalAnalogIn() {
mInputNummer = 0;
}
DigitalAnalogIn::DigitalAnalogIn(unsigned int inputNummer) {
mInputNummer = inputNummer;
// if (ISMAXI)
// {
// mInputPortNr = SX1509_PORT_DIO_PWMO[mInputNummer];
// }
// else
// {
// mInputPortNr = PORT_IN[mInputNummer];
// }
}
void DigitalAnalogIn::setMaxi(bool pMaxi) {
if (pMaxi)
{
mInputPortNr = SX1509_PORT_DIO_PWMO[mInputNummer];
currentPinMode = INPUT_PULLUP;
sx1509Object.pinMode(mInputPortNr, currentPinMode);
}
else
{
mInputPortNr = PORT_IN[mInputNummer];
currentPinMode = INPUT_PULLUP;
pinMode(mInputPortNr, currentPinMode);
}
}
unsigned int DigitalAnalogIn::getValueDigital() {
bool eingabe;
if (ISMAXI)
{
if (INPUT_PULLUP != currentPinMode)
{
sx1509Object.pinMode(mInputPortNr, INPUT_PULLUP); //Pin-Modus einrichten: Input mit Pull-Up Widerstand
}
eingabe = !sx1509Object.digitalRead(mInputPortNr); //Inverse Logik: Schalter gedrückt = 1 (= Port liegt auf Masse)
}
else
{
ledcDetachPin(mInputPortNr); //für den Fall, dass eine PWM auf dem Pin eingerichtet ist, wird diese vor einer Abfrage von dem Pin getrennt
if (INPUT_PULLUP != currentPinMode)
{
pinMode(mInputPortNr, INPUT_PULLUP); //Pin-Modus einrichten: Input mit Pull-Up Widerstand
}
eingabe = !digitalRead(mInputPortNr); //Inverse Logik: Schalter gedrückt = 1 (= Port liegt auf Masse)
}
return (unsigned int) eingabe;
}
unsigned int DigitalAnalogIn::getValueAnalog() {
unsigned int eingabe;
if (ISMAXI)
{
if (INPUT != currentPinMode)
{
sx1509Object.pinMode(mInputPortNr, INPUT); //Pin-Modus einrichten: Input ohne Pull-Up Widerstand
}
eingabe = sx1509Object.digitalRead(mInputPortNr);
}
else
{
if (INPUT != currentPinMode)
{
pinMode(mInputPortNr, INPUT); //Pin-Modus einrichten: Input ohne Pull-Up Widerstand
}
eingabe = analogRead(mInputPortNr);
}
return eingabe;
}
void DigitalAnalogIn::setValueDigital(bool ledLevel) {
if (ISMAXI)
{
sx1509Object.pinMode(mInputPortNr, OUTPUT); //Pin_Modus einrichten: Output
}
else
{
pinMode(mInputPortNr, OUTPUT); //Pin_Modus einrichten: Output
}
Serial.print("[io] Setze LED ");
Serial.print(mInputNummer);
Serial.print(" auf ");
if (ledLevel)
{
if (ISMAXI)
{
sx1509Object.digitalWrite(mInputPortNr, HIGH); //Pin auf HIGH setzen
}
else
{
digitalWrite(mInputPortNr, HIGH); //Pin auf HIGH setzen
}
Serial.println(" HIGH");
}
else
{
if (ISMAXI)
{
sx1509Object.digitalWrite(mInputPortNr, LOW); //Pin auf LOW setzen
}
else
{
digitalWrite(mInputPortNr, LOW); //Pin auf LOW setzen
}
Serial.println(" LOW");
}
}
/* ====================================================================================================================== */
/***
*
*
* FOLGENDER ABSCHNITT IST NICHT IMPLEMENTIERT IN DER QUEUE
*
*
//#ifdef MAXI
//DigitalIO_PWMout::DigitalIO_PWMout()
//{
//#ifdef DEBUG
// Serial.println("Ctor DIO_PWMO N/A");
//#endif // DEBUG
//
//
// //Serial.println("DigitalIO_PWMout mit parameterlosem Ctor initialisiert");
// mIONumber = 0;
//}
//
//DigitalIO_PWMout::DigitalIO_PWMout(byte io, byte inOut)
//{
//#ifdef DEBUG
// Serial.println("Ctor DIO_PWMO " + io);
//#endif // DEBUG
//
//
// mIONumber = io;
// mDirection = inOut;
//
// mIOPin = SX1509_PORT_DIO_PWMO[io];
//
// sx1509Object.pinMode(mIOPin, mDirection);
//}
//
//unsigned int DigitalIO_PWMout::getValue()
//{
// //if input is configured as INPUT (no pull up) return value as is
// if (mDirection == INPUT) {
// unsigned int ret = sx1509Object.digitalRead(mIOPin);
//
// return ret;
// }
//
// //if input is configured as INPUT_PULLUP return inverted value
// if (mDirection != INPUT_PULLUP) {
// sx1509Object.pinMode(mIOPin, INPUT);
// delay(20);
// sx1509Object.digitalWrite(mIOPin, HIGH);
// mDirection = INPUT_PULLUP;
// Serial.println("SX1509 IO Output wurde in 'getValue' zu Input (Pullup) geändert, IONumber: " + mIONumber);
// Serial.println("IOPin: " + mIOPin);
// }
// if (sx1509Object.digitalRead(mIOPin) != 0) {
// return 0;
// }
// else {
// return 1;
// }
// return sx1509Object.digitalRead(mIOPin);
//}
//
//
//void DigitalIO_PWMout::setValueDig(bool val)
//{
// if (mDirection != OUTPUT) {
// sx1509Object.pinMode(mIOPin, OUTPUT);
// mDirection = OUTPUT;
// Serial.println("SX1509 IO Input wurde in 'setValueDig' zu Output geändert, IONumber: " + mIONumber);
// Serial.println("IOPin: " + mIOPin);
// }
//
// if (val)
// sx1509Object.digitalWrite(mIOPin, HIGH);
// else
// sx1509Object.digitalWrite(mIOPin, LOW);
//}
//
//void DigitalIO_PWMout::setPWM(unsigned char pwmVal)
//{
// if (mDirection != OUTPUT) {
// sx1509Object.pinMode(mIOPin, OUTPUT);
// mDirection = OUTPUT;
// Serial.println("SX1509 IO Input wurde in 'setPWM' zu Output geändert, IONumber: " + mIONumber);
// Serial.println("IOPin: " + mIOPin);
// }
//
// sx1509Object.analogWrite(mIOPin, pwmVal);
//}
//
//#endif
*/
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/ink/FullScreenLayer.hpp>
namespace RED4ext
{
namespace ink {
struct HUDLayer : ink::FullScreenLayer
{
static constexpr const char* NAME = "inkHUDLayer";
static constexpr const char* ALIAS = NAME;
uint8_t unk148[0x1C0 - 0x148]; // 148
};
RED4EXT_ASSERT_SIZE(HUDLayer, 0x1C0);
} // namespace ink
} // namespace RED4ext
|
// wce/imm.h
#include "stdafx.h"
// Functions
// Stubs
Stub(ImmSIPanelState); // ret: BOOL; args: UINT dwCmd, LPVOID pValue
Stub(ImmSetHotKey_WCECL);
|
#ifndef CSLIBS_NDT_MAP_WEIGHTED_OCCUPANCY_GRIDMAP_HPP
#define CSLIBS_NDT_MAP_WEIGHTED_OCCUPANCY_GRIDMAP_HPP
#include <cslibs_ndt/map/generic_map.hpp>
#include <cslibs_ndt/common/weighted_occupancy_distribution.hpp>
namespace cslibs_ndt {
namespace map {
template <tags::option option_t,
std::size_t Dim,
typename T,
template <typename, typename, typename...> class backend_t>
class EIGEN_ALIGN16 Map<option_t,Dim,WeightedOccupancyDistribution,T,backend_t> :
public GenericMap<option_t,Dim,WeightedOccupancyDistribution,T,backend_t>
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
using allocator_t = Eigen::aligned_allocator<Map<option_t,Dim,WeightedOccupancyDistribution,T,backend_t>>;
using ConstPtr = std::shared_ptr<const Map<option_t,Dim,WeightedOccupancyDistribution,T,backend_t>>;
using Ptr = std::shared_ptr<Map<option_t,Dim,WeightedOccupancyDistribution,T,backend_t>>;
using base_t = GenericMap<option_t,Dim,WeightedOccupancyDistribution,T,backend_t>;
using typename base_t::pose_t;
using typename base_t::transform_t;
using typename base_t::point_t;
using typename base_t::pointcloud_t;
using typename base_t::index_t;
using typename base_t::index_list_t;
using typename base_t::distribution_t;
using typename base_t::distribution_storage_t;
using typename base_t::distribution_storage_ptr_t;
using typename base_t::distribution_storage_array_t;
using typename base_t::distribution_bundle_t;
using typename base_t::distribution_const_bundle_t;
using typename base_t::distribution_bundle_storage_t;
using typename base_t::distribution_bundle_storage_ptr_t;
using inverse_sensor_model_t = cslibs_gridmaps::utility::InverseModel<T>;
using default_iterator_t = typename map::traits<Dim,T>::default_iterator_t;
using base_t::base_t;
inline Map(const base_t &other) : base_t(other) { }
inline Map(base_t &&other) : base_t(other) { }
template <typename line_iterator_t = default_iterator_t>
inline void insert(const typename cslibs_math::linear::Pointcloud<point_t>::ConstPtr &points,
const pose_t &points_origin = pose_t())
{
return insert<line_iterator_t>(points->begin(), points->end(), points_origin);
}
template <typename line_iterator_t = default_iterator_t, typename iterator_t>
inline void insert(const iterator_t& points_begin,
const iterator_t& points_end,
const pose_t &points_origin = pose_t())
{
using dist_t = typename distribution_t::distribution_t;
std::map<index_t, dist_t> updates;
for (auto p = points_begin; p != points_end; ++p) {
if (p->isNormal()) {
const point_t pw = points_origin * *p;
if (pw.isNormal()) {
point_t pm;
index_t bi;
if (this->toBundleIndex(pw, pm, bi))
updates[bi].add(pm);
}
}
}
std::unordered_map<index_t,T> updates_free;
const auto& start = this->m_T_w_ * points_origin.translation();
for (const auto& pair : updates) {
const index_t& i = pair.first;
const dist_t& d = pair.second;
const auto& w = d.getWeight();
updateOccupied(i, d);
line_iterator_t it(start, point_t(d.getMean()), this->bundle_resolution_);
while (!it.done()) {
const index_t& bi = it();
if (this->valid(bi))
updates_free[bi] += w;
++it;
}
}
for (const auto& pair : updates)
updates_free.erase(pair.first);
for (const auto& pair : updates_free)
updateFree(pair.first, pair.second);
}
template <typename line_iterator_t = default_iterator_t>
inline void insertVisible(const typename cslibs_math::linear::Pointcloud<point_t>::ConstPtr &points,
const pose_t &points_origin,
const typename inverse_sensor_model_t::Ptr &ivm,
const typename inverse_sensor_model_t::Ptr &ivm_visibility)
{
return insertVisible<line_iterator_t>(points->begin(), points->end(), points_origin, ivm, ivm_visibility);
}
template <typename line_iterator_t = default_iterator_t, typename iterator_t>
inline void insertVisible(const iterator_t &points_begin,
const iterator_t &points_end,
const pose_t &points_origin,
const typename inverse_sensor_model_t::Ptr &ivm,
const typename inverse_sensor_model_t::Ptr &ivm_visibility)
{
if (!ivm || !ivm_visibility) {
std::cout << "[WeightedOccupancyGridmap]: Cannot evaluate visibility, using model-free update rule instead!" << std::endl;
return insert(points_begin, points_end, points_origin);
}
using dist_t = typename distribution_t::distribution_t;
std::map<index_t, dist_t> updates;
for (auto p = points_begin; p != points_end; ++p) {
if (p->isNormal()) {
const point_t pw = points_origin * *p;
if (pw.isNormal()) {
point_t pm;
index_t bi;
if (this->toBundleIndex(pw, pm, bi))
updates[bi].add(pm);
}
}
}
std::unordered_map<index_t,T> updates_free;
const auto& start = this->m_T_w_ * points_origin.translation();
const index_t start_bi = this->toBundleIndex(points_origin.translation());
auto current_visibility = [this, &ivm, &start_bi, &ivm_visibility, &points_origin](const index_t &bi, const point_t& end) {
auto generate_occlusion_index = [&bi,&start_bi](const std::size_t& counter) {
index_t retval = bi;
retval[counter] += ((bi[counter] > start_bi[counter]) ? -1 : 1);
return retval;
};
auto occupancy = [this, &ivm, &points_origin, &end](const index_t &occ_bi) {
const distribution_bundle_t *bundle = this->get(occ_bi);
T retval = T(0.);
if (bundle) {
for (std::size_t i=0; i<this->bin_count; ++i) {
retval += this->div_count * bundle->at(i)->getOccupancy(ivm);
}
}
return retval;
};
T occlusion_prob = T(1.);
for (std::size_t i=0; i<Dim; ++i) {
const index_t test_index = generate_occlusion_index(i);
if (this->valid(test_index))
occlusion_prob = std::min(occlusion_prob, occupancy(test_index));
}
return ivm_visibility->getProbFree() * occlusion_prob +
ivm_visibility->getProbOccupied() * (T(1.) - occlusion_prob);
};
for (const auto& pair : updates) {
const index_t& i = pair.first;
const dist_t& d = pair.second;
T visibility = T(1.);
const auto& end = point_t(d.getMean());
const auto& w = d.getWeight();
line_iterator_t it(start, end, this->bundle_resolution_);
while (!it.done()) {
const index_t& bi = it();
if ((visibility *= current_visibility(bi,end)) < ivm_visibility->getProbPrior())
return;
if (this->valid(bi))
updates_free[bi] += w;
++it;
}
if ((visibility *= current_visibility(i,end)) >= ivm_visibility->getProbPrior()) {
updateOccupied(i, d);
}
}
for (const auto& pair : updates)
updates_free.erase(pair.first);
for (const auto& pair : updates_free)
updateFree(pair.first, pair.second);
}
/*
inline T sample(const point_t &p,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
point_t pm;
const index_t& i = this->toBundleIndex(p, pm);
return sample(pm, i, ivm);
}
inline T sample(const point_t &p,
const index_t &bi,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
if (!ivm)
throw std::runtime_error("[WeightedOccupancyGridmap]: inverse model not set");
if (!this->valid(bi))
return T();
distribution_bundle_t *bundle = this->bundle_storage_->get(bi);
return sample(p, bundle, ivm);
}
inline T sample(const point_t &p,
const distribution_bundle_t* bundle,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
if (!ivm)
throw std::runtime_error("[WeightedOccupancyGridmap]: inverse model not set");
auto sample = [&p, &ivm] (const distribution_t *d) {
auto do_sample = [&p, &ivm, &d]() {
const auto &handle = d;
return handle->getDistribution() ?
handle->getDistribution()->sample(p) * handle->getOccupancy(ivm) : T();
};
return d ? do_sample() : T();
};
auto evaluate = [this, &p, &bundle, &sample]() {
T retval = T();
for (std::size_t i=0; i<this->bin_count; ++i)
retval += this->div_count * sample(bundle->at(i));
return retval;
};
return bundle ? evaluate() : T();
}
*/
inline T sampleNonNormalized(const point_t &p,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
point_t pm;
const index_t& i = this->toBundleIndex(p, pm);
return sampleNonNormalized(pm, i, ivm);
}
inline T sampleNonNormalized(const point_t &p,
const index_t &bi,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
if (!ivm)
throw std::runtime_error("[WeightedOccupancyGridmap]: inverse model not set");
if (!this->valid(bi))
return T();
distribution_bundle_t *bundle = this->bundle_storage_->get(bi);
return sampleNonNormalized(p, bundle, ivm);
}
inline T sampleNonNormalized(const point_t &p,
const distribution_bundle_t* bundle,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
if (!ivm)
throw std::runtime_error("[WeightedOccupancyGridmap]: inverse model not set");
auto sample = [&p, &ivm] (const distribution_t *d) {
auto do_sample = [&p, &ivm, &d]() {
const auto &handle = d;
return handle->getDistribution() ?
handle->getDistribution()->sampleNonNormalized(p) * handle->getOccupancy(ivm) : T();
};
return d ? do_sample() : T();
};
auto evaluate = [this, &p, &bundle, &sample]() {
T retval = T();
for (std::size_t i=0; i<this->bin_count; ++i)
retval += this->div_count * sample(bundle->at(i));
return retval;
};
return bundle ? evaluate() : T();
}
inline T sampleNonNormalizedBilinear(const point_t &p,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
point_t pm;
const index_t& i = this->toBundleIndex(p, pm);
return sampleNonNormalizedBilinear(pm, i, ivm);
}
inline T sampleNonNormalizedBilinear(const point_t &p,
const index_t &bi,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
if (!ivm)
throw std::runtime_error("[WeightedOccupancyGridMap]: inverse model not set");
if (!this->valid(bi))
return T();
distribution_bundle_t *bundle = this->bundle_storage_->get(bi);
const auto& weights = utility::get_bilinear_interpolation_weights(bi,p,this->bundle_resolution_inv_);
return sampleNonNormalizedBilinear(p, weights, bundle, ivm);
}
inline T sampleNonNormalizedBilinear(const point_t &p,
const std::array<T,Dim> &weights,
const distribution_bundle_t* bundle,
const typename inverse_sensor_model_t::Ptr &ivm) const
{
if (!ivm)
throw std::runtime_error("[WeightedOccupancyGridMap]: inverse model not set");
auto sample = [&p, &ivm] (const distribution_t *d) {
auto do_sample = [&p, &ivm, &d]() {
const auto &handle = d;
return handle->getDistribution() ?
handle->getDistribution()->sampleNonNormalized(p) * handle->getOccupancy(ivm) : T(0.0);
};
return d ? do_sample() : T();
};
auto evaluate = [this, &p, &weights, &bundle, &sample]() {
T retval = T();
for (std::size_t i=0; i<this->bin_count; ++i)
retval += utility::to_bilinear_interpolation_weight(weights,i) * sample(bundle->at(i));
return retval;
};
return bundle ? evaluate() : T();
}
protected:
virtual inline bool expandDistribution(const distribution_t* d) const override
{
return d && d->getDistribution() && d->getDistribution()->getSampleCount() > 0;
}
inline void updateFree(const index_t &bi,
const T &w) const
{
distribution_bundle_t *bundle = this->getAllocate(bi);
for (std::size_t i=0; i<this->bin_count; ++i)
bundle->at(i)->updateFree(w);
}
inline void updateOccupied(const index_t &bi,
const typename distribution_t::distribution_t &d) const
{
distribution_bundle_t *bundle = this->getAllocate(bi);
for (std::size_t i=0; i<this->bin_count; ++i)
bundle->at(i)->updateOccupied(d);
}
};
}
}
#endif // CSLIBS_NDT_MAP_WEIGHTED_OCCUPANCY_GRIDMAP_HPP
|
#include "global.h"
#include "ActorUtil.h"
#include "CodeDetector.h"
#include "CommonMetrics.h"
#include "Foreach.h"
#include "Game.h"
#include "GameConstantsAndTypes.h"
#include "GameManager.h"
#include "GameSoundManager.h"
#include "ScoreManager.h"
#include "GameState.h"
#include "InputMapper.h"
#include "MenuTimer.h"
#include "StageStats.h"
#include "PlayerState.h"
#include "PrefsManager.h"
#include "ProfileManager.h"
#include "RageLog.h"
#include "RageTextureManager.h"
#include "ScreenManager.h"
#include "ScreenSelectMusic.h"
#include "SongManager.h"
#include "StatsManager.h"
#include "Steps.h"
#include "StepsUtil.h"
#include "Style.h"
#include "PlayerState.h"
#include "CommonMetrics.h"
#include "ImageCache.h"
#include "ScreenPrompt.h"
#include "Song.h"
#include "InputEventPlus.h"
#include "OptionsList.h"
#include "ProfileManager.h"
#include "RageFileManager.h"
#include "RageInput.h"
#include "ScreenPrompt.h"
#include "ScreenTextEntry.h"
#include "ProfileManager.h"
#include "DownloadManager.h"
#include "GamePreferences.h"
#include "PlayerAI.h"
#include "PlayerOptions.h"
static const char* SelectionStateNames[] = { "SelectingSong",
"SelectingSteps",
"Finalized" };
XToString(SelectionState);
/** @brief The maximum number of digits for the ScoreDisplay. */
const int NUM_SCORE_DIGITS = 9;
#define SHOW_OPTIONS_MESSAGE_SECONDS \
THEME->GetMetricF(m_sName, "ShowOptionsMessageSeconds")
static const ThemeMetric<int> HARD_COMMENT_METER("ScreenSelectMusic",
"HardCommentMeter");
AutoScreenMessage(SM_AllowOptionsMenuRepeat);
AutoScreenMessage(SM_SongChanged);
AutoScreenMessage(SM_SortOrderChanging);
AutoScreenMessage(SM_SortOrderChanged);
AutoScreenMessage(SM_BackFromPlayerOptions);
AutoScreenMessage(SM_ConfirmDeleteSong);
AutoScreenMessage(SM_BackFromNamePlaylist);
static RString g_sCDTitlePath;
static bool g_bWantFallbackCdTitle;
static bool g_bCDTitleWaiting = false;
static RString g_sBannerPath;
static bool g_bBannerWaiting = false;
static bool g_bSampleMusicWaiting = false;
static RageTimer g_StartedLoadingAt(RageZeroTimer);
static RageTimer g_ScreenStartedLoadingAt(RageZeroTimer);
RageTimer g_CanOpenOptionsList(RageZeroTimer);
static LocalizedString PERMANENTLY_DELETE("ScreenSelectMusic",
"PermanentlyDelete");
REGISTER_SCREEN_CLASS(ScreenSelectMusic);
void
ScreenSelectMusic::Init()
{
g_ScreenStartedLoadingAt.Touch();
if (PREFSMAN->m_sTestInitialScreen.Get() == m_sName) {
GAMESTATE->m_PlayMode.Set(PLAY_MODE_REGULAR);
GAMESTATE->SetCurrentStyle(
GAMEMAN->GameAndStringToStyle(GAMEMAN->GetDefaultGame(), "versus"),
PLAYER_INVALID);
GAMESTATE->JoinPlayer(PLAYER_1);
GAMESTATE->SetMasterPlayerNumber(PLAYER_1);
}
if (GamePreferences::m_AutoPlay == PC_REPLAY)
GamePreferences::m_AutoPlay.Set(PC_HUMAN);
if (GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerController == PC_REPLAY)
GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerController = PC_HUMAN;
IDLE_COMMENT_SECONDS.Load(m_sName, "IdleCommentSeconds");
SAMPLE_MUSIC_DELAY_INIT.Load(m_sName, "SampleMusicDelayInit");
SAMPLE_MUSIC_DELAY.Load(m_sName, "SampleMusicDelay");
SAMPLE_MUSIC_LOOPS.Load(m_sName, "SampleMusicLoops");
SAMPLE_MUSIC_PREVIEW_MODE.Load(m_sName, "SampleMusicPreviewMode");
SAMPLE_MUSIC_FALLBACK_FADE_IN_SECONDS.Load(
m_sName, "SampleMusicFallbackFadeInSeconds");
SAMPLE_MUSIC_FADE_OUT_SECONDS.Load(m_sName, "SampleMusicFadeOutSeconds");
DO_ROULETTE_ON_MENU_TIMER.Load(m_sName, "DoRouletteOnMenuTimer");
ROULETTE_TIMER_SECONDS.Load(m_sName, "RouletteTimerSeconds");
ALIGN_MUSIC_BEATS.Load(m_sName, "AlignMusicBeat");
CODES.Load(m_sName, "Codes");
MUSIC_WHEEL_TYPE.Load(m_sName, "MusicWheelType");
SELECT_MENU_AVAILABLE.Load(m_sName, "SelectMenuAvailable");
MODE_MENU_AVAILABLE.Load(m_sName, "ModeMenuAvailable");
USE_OPTIONS_LIST.Load(m_sName, "UseOptionsList");
USE_PLAYER_SELECT_MENU.Load(m_sName, "UsePlayerSelectMenu");
SELECT_MENU_NAME.Load(m_sName, "SelectMenuScreenName");
OPTIONS_LIST_TIMEOUT.Load(m_sName, "OptionsListTimeout");
SELECT_MENU_CHANGES_DIFFICULTY.Load(m_sName, "SelectMenuChangesDifficulty");
TWO_PART_SELECTION.Load(m_sName, "TwoPartSelection");
TWO_PART_CONFIRMS_ONLY.Load(m_sName, "TwoPartConfirmsOnly");
TWO_PART_TIMER_SECONDS.Load(m_sName, "TwoPartTimerSeconds");
WRAP_CHANGE_STEPS.Load(m_sName, "WrapChangeSteps");
NULL_SCORE_STRING.Load(m_sName, "NullScoreString");
PLAY_SOUND_ON_ENTERING_OPTIONS_MENU.Load(m_sName,
"PlaySoundOnEnteringOptionsMenu");
// To allow changing steps with gamebuttons -DaisuMaster
CHANGE_STEPS_WITH_GAME_BUTTONS.Load(m_sName, "ChangeStepsWithGameButtons");
CHANGE_GROUPS_WITH_GAME_BUTTONS.Load(m_sName,
"ChangeGroupsWithGameButtons");
m_GameButtonPreviousSong = INPUTMAPPER->GetInputScheme()->ButtonNameToIndex(
THEME->GetMetric(m_sName, "PreviousSongButton"));
m_GameButtonNextSong = INPUTMAPPER->GetInputScheme()->ButtonNameToIndex(
THEME->GetMetric(m_sName, "NextSongButton"));
// Ask for those only if changing steps with gamebuttons is allowed
// -DaisuMaster
if (CHANGE_STEPS_WITH_GAME_BUTTONS) {
m_GameButtonPreviousDifficulty =
INPUTMAPPER->GetInputScheme()->ButtonNameToIndex(
THEME->GetMetric(m_sName, "PreviousDifficultyButton"));
m_GameButtonNextDifficulty =
INPUTMAPPER->GetInputScheme()->ButtonNameToIndex(
THEME->GetMetric(m_sName, "NextDifficultyButton"));
}
// same here but for groups -DaisuMaster
if (CHANGE_GROUPS_WITH_GAME_BUTTONS) {
m_GameButtonPreviousGroup =
INPUTMAPPER->GetInputScheme()->ButtonNameToIndex(
THEME->GetMetric(m_sName, "PreviousGroupButton"));
m_GameButtonNextGroup =
INPUTMAPPER->GetInputScheme()->ButtonNameToIndex(
THEME->GetMetric(m_sName, "NextGroupButton"));
}
FOREACH_ENUM(PlayerNumber, p)
{
m_bSelectIsDown[p] = false; // used by UpdateSelectButton
m_bAcceptSelectRelease[p] = false;
}
ScreenWithMenuElements::Init();
this->SubscribeToMessage(Message_PlayerJoined);
// Cache these values
// Marking for change -- Midiman (why? -aj)
m_sSectionMusicPath = THEME->GetPathS(m_sName, "section music");
m_sSortMusicPath = THEME->GetPathS(m_sName, "sort music");
m_sRouletteMusicPath = THEME->GetPathS(m_sName, "roulette music");
m_sRandomMusicPath = THEME->GetPathS(m_sName, "random music");
m_sLoopMusicPath = THEME->GetPathS(m_sName, "loop music");
m_sFallbackCDTitlePath = THEME->GetPathG(m_sName, "fallback cdtitle");
m_TexturePreload.Load(m_sFallbackCDTitlePath);
// load banners
if (PREFSMAN->m_ImageCache != IMGCACHE_OFF) {
m_TexturePreload.Load(
Banner::SongBannerTexture(THEME->GetPathG("Banner", "all music")));
m_TexturePreload.Load(Banner::SongBannerTexture(
THEME->GetPathG("Common", "fallback banner")));
m_TexturePreload.Load(
Banner::SongBannerTexture(THEME->GetPathG("Banner", "roulette")));
m_TexturePreload.Load(
Banner::SongBannerTexture(THEME->GetPathG("Banner", "random")));
m_TexturePreload.Load(
Banner::SongBannerTexture(THEME->GetPathG("Banner", "mode")));
}
// Load low-res banners and backgrounds if needed.
IMAGECACHE->Demand("Banner");
// build the playlist groups here, songmanager's init from disk can't
// because profiles aren't loaded until after that's done -mina
SONGMAN->MakeSongGroupsFromPlaylists();
m_MusicWheel.SetName("MusicWheel");
m_MusicWheel.Load(MUSIC_WHEEL_TYPE);
LOAD_ALL_COMMANDS_AND_SET_XY(m_MusicWheel);
this->AddChild(&m_MusicWheel);
if (USE_OPTIONS_LIST) {
FOREACH_PlayerNumber(p)
{
m_OptionsList[p].SetName("OptionsList" + PlayerNumberToString(p));
m_OptionsList[p].Load("OptionsList", p);
m_OptionsList[p].SetDrawOrder(100);
ActorUtil::LoadAllCommands(m_OptionsList[p], m_sName);
this->AddChild(&m_OptionsList[p]);
}
m_OptionsList[PLAYER_1].Link(&m_OptionsList[PLAYER_2]);
m_OptionsList[PLAYER_2].Link(&m_OptionsList[PLAYER_1]);
}
// this is loaded SetSong and TweenToSong
m_Banner.SetName("Banner");
LOAD_ALL_COMMANDS_AND_SET_XY(m_Banner);
this->AddChild(&m_Banner);
m_sprCDTitleFront.SetName("CDTitle");
m_sprCDTitleFront.Load(THEME->GetPathG(m_sName, "fallback cdtitle"));
LOAD_ALL_COMMANDS_AND_SET_XY(m_sprCDTitleFront);
COMMAND(m_sprCDTitleFront, "Front");
this->AddChild(&m_sprCDTitleFront);
m_sprCDTitleBack.SetName("CDTitle");
m_sprCDTitleBack.Load(THEME->GetPathG(m_sName, "fallback cdtitle"));
LOAD_ALL_COMMANDS_AND_SET_XY(m_sprCDTitleBack);
COMMAND(m_sprCDTitleBack, "Back");
this->AddChild(&m_sprCDTitleBack);
FOREACH_ENUM(PlayerNumber, p)
{
m_sprHighScoreFrame[p].Load(
THEME->GetPathG(m_sName, ssprintf("ScoreFrame P%d", p + 1)));
m_sprHighScoreFrame[p]->SetName(ssprintf("ScoreFrameP%d", p + 1));
LOAD_ALL_COMMANDS_AND_SET_XY(m_sprHighScoreFrame[p]);
this->AddChild(m_sprHighScoreFrame[p]);
m_textHighScore[p].SetName(ssprintf("ScoreP%d", p + 1));
m_textHighScore[p].LoadFromFont(THEME->GetPathF(m_sName, "score"));
LOAD_ALL_COMMANDS_AND_SET_XY(m_textHighScore[p]);
this->AddChild(&m_textHighScore[p]);
}
RageSoundLoadParams SoundParams;
SoundParams.m_bSupportPan = true;
m_soundStart.Load(THEME->GetPathS(m_sName, "start"));
m_soundDifficultyEasier.Load(
THEME->GetPathS(m_sName, "difficulty easier"), false, &SoundParams);
m_soundDifficultyHarder.Load(
THEME->GetPathS(m_sName, "difficulty harder"), false, &SoundParams);
m_soundOptionsChange.Load(THEME->GetPathS(m_sName, "options"));
m_soundLocked.Load(THEME->GetPathS(m_sName, "locked"));
this->SortByDrawOrder();
}
void
ScreenSelectMusic::BeginScreen()
{
g_ScreenStartedLoadingAt.Touch();
m_timerIdleComment.GetDeltaTime();
SONGMAN->MakeSongGroupsFromPlaylists();
SONGMAN->SetFavoritedStatus(
PROFILEMAN->GetProfile(PLAYER_1)->FavoritedCharts);
SONGMAN->SetHasGoal(PROFILEMAN->GetProfile(PLAYER_1)->goalmap);
if (CommonMetrics::AUTO_SET_STYLE) {
GAMESTATE->SetCompatibleStylesForPlayers();
}
if (GAMESTATE->GetCurrentStyle(PLAYER_INVALID) == NULL) {
LOG->Trace("The Style has not been set. A theme must set the Style "
"before loading ScreenSelectMusic.");
// Instead of crashing, set the first compatible style.
vector<StepsType> vst;
GAMEMAN->GetStepsTypesForGame(GAMESTATE->m_pCurGame, vst);
const Style* pStyle = GAMEMAN->GetFirstCompatibleStyle(
GAMESTATE->m_pCurGame, GAMESTATE->GetNumSidesJoined(), vst[0]);
if (pStyle == NULL) {
LOG->Warn(ssprintf("No compatible styles for %s with %d player%s.",
GAMESTATE->m_pCurGame->m_szName,
GAMESTATE->GetNumSidesJoined(),
GAMESTATE->GetNumSidesJoined() == 1 ? "" : "s") +
"Returning to title menu.");
SCREENMAN->SetNewScreen("ScreenTitleMenu");
}
GAMESTATE->SetCurrentStyle(pStyle, PLAYER_INVALID);
}
if (GAMESTATE->m_PlayMode == PlayMode_Invalid) {
// Instead of crashing here, let's just set the PlayMode to regular
GAMESTATE->m_PlayMode.Set(PLAY_MODE_REGULAR);
LOG->Trace("PlayMode not set, setting as regular.");
}
FOREACH_ENUM(PlayerNumber, pn)
{
if (GAMESTATE->IsHumanPlayer(pn))
continue;
m_sprHighScoreFrame[pn]->SetVisible(false);
m_textHighScore[pn].SetVisible(false);
}
OPTIONS_MENU_AVAILABLE.Load(m_sName, "OptionsMenuAvailable");
PlayCommand("Mods");
m_MusicWheel.BeginScreen();
m_SelectionState = SelectionState_SelectingSong;
ZERO(m_bStepsChosen);
m_bGoToOptions = false;
m_bAllowOptionsMenu = m_bAllowOptionsMenuRepeat = false;
ZERO(m_iSelection);
if (USE_OPTIONS_LIST)
FOREACH_PlayerNumber(pn) m_OptionsList[pn].Reset();
AfterMusicChange();
SOUND->PlayOnceFromAnnouncer("select music intro");
if (GAMESTATE->IsPlaylistCourse()) {
GAMESTATE->isplaylistcourse = false;
SONGMAN->playlistcourse = "";
}
if (GAMESTATE->m_pCurSteps[PLAYER_1] != nullptr)
DLMAN->RequestChartLeaderBoard(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
ScreenWithMenuElements::BeginScreen();
}
ScreenSelectMusic::~ScreenSelectMusic()
{
LOG->Trace("ScreenSelectMusic::~ScreenSelectMusic()");
IMAGECACHE->Undemand("Banner");
}
// If bForce is true, the next request will be started even if it might cause a
// skip.
void
ScreenSelectMusic::CheckBackgroundRequests(bool bForce)
{
if (g_bCDTitleWaiting) {
// The CDTitle is normally very small, so we don't bother waiting to
// display it.
RString sPath;
if (!m_BackgroundLoader.IsCacheFileFinished(g_sCDTitlePath, sPath))
return;
g_bCDTitleWaiting = false;
RString sCDTitlePath = sPath;
if (sCDTitlePath.empty() || !IsAFile(sCDTitlePath))
sCDTitlePath =
g_bWantFallbackCdTitle ? m_sFallbackCDTitlePath : RString("");
if (!sCDTitlePath.empty()) {
TEXTUREMAN->DisableOddDimensionWarning();
m_sprCDTitleFront.Load(sCDTitlePath);
m_sprCDTitleBack.Load(sCDTitlePath);
TEXTUREMAN->EnableOddDimensionWarning();
}
m_BackgroundLoader.FinishedWithCachedFile(g_sCDTitlePath);
}
/* Loading the rest can cause small skips, so don't do it until the wheel
* settles. Do load if we're transitioning out, though, so we don't miss
* starting the music for the options screen if a song is selected quickly.
* Also, don't do this if the wheel is locked, since we're just bouncing
* around after selecting TYPE_RANDOM, and it'll take a while before the
* wheel will settle. */
if (!m_MusicWheel.IsSettled() && !m_MusicWheel.WheelIsLocked() && !bForce)
return;
if (g_bBannerWaiting) {
if (m_Banner.GetTweenTimeLeft() > 0)
return;
RString sPath;
bool bFreeCache = false;
if (TEXTUREMAN->IsTextureRegistered(
Sprite::SongBannerTexture(g_sBannerPath))) {
/* If the file is already loaded into a texture, it's finished,
* and we only do this to honor the HighQualTime value. */
sPath = g_sBannerPath;
} else {
if (!m_BackgroundLoader.IsCacheFileFinished(g_sBannerPath, sPath))
return;
bFreeCache = true;
}
g_bBannerWaiting = false;
m_Banner.Load(sPath, true);
if (bFreeCache)
m_BackgroundLoader.FinishedWithCachedFile(g_sBannerPath);
}
// Nothing else is going. Start the music, if we haven't yet.
if (g_bSampleMusicWaiting) {
if (g_ScreenStartedLoadingAt.Ago() < SAMPLE_MUSIC_DELAY_INIT)
return;
// Don't start the music sample when moving fast.
if (g_StartedLoadingAt.Ago() < SAMPLE_MUSIC_DELAY && !bForce)
return;
g_bSampleMusicWaiting = false;
GameSoundManager::PlayMusicParams PlayParams;
PlayParams.sFile = HandleLuaMusicFile(m_sSampleMusicToPlay);
PlayParams.pTiming = m_pSampleMusicTimingData;
PlayParams.bForceLoop = SAMPLE_MUSIC_LOOPS;
PlayParams.fStartSecond = m_fSampleStartSeconds;
PlayParams.fLengthSeconds = m_fSampleLengthSeconds;
PlayParams.fFadeOutLengthSeconds = SAMPLE_MUSIC_FADE_OUT_SECONDS;
PlayParams.bAlignBeat = ALIGN_MUSIC_BEATS;
PlayParams.bApplyMusicRate = true;
GameSoundManager::PlayMusicParams FallbackMusic;
FallbackMusic.sFile = m_sLoopMusicPath;
FallbackMusic.fFadeInLengthSeconds =
SAMPLE_MUSIC_FALLBACK_FADE_IN_SECONDS;
FallbackMusic.bAlignBeat = ALIGN_MUSIC_BEATS;
SOUND->PlayMusic(PlayParams, FallbackMusic);
MESSAGEMAN->Broadcast("PlayingSampleMusic");
//DLMAN->RequestChartLeaderBoard(GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
}
}
void
ScreenSelectMusic::Update(float fDeltaTime)
{
if (!IsTransitioning()) {
if (IDLE_COMMENT_SECONDS > 0 &&
m_timerIdleComment.PeekDeltaTime() >= IDLE_COMMENT_SECONDS) {
SOUND->PlayOnceFromAnnouncer(m_sName + " IdleComment");
m_timerIdleComment.GetDeltaTime();
}
}
ScreenWithMenuElements::Update(fDeltaTime);
CheckBackgroundRequests(false);
}
void
ScreenSelectMusic::DifferentialReload()
{
SONGMAN->DifferentialReload();
m_MusicWheel.ReloadSongList(false, "");
}
bool
ScreenSelectMusic::Input(const InputEventPlus& input)
{
// HACK: This screen eats mouse inputs if we don't check for them first.
bool mouse_evt = false;
for (int i = MOUSE_LEFT; i <= MOUSE_WHEELDOWN; i++) {
if (input.DeviceI == DeviceInput(DEVICE_MOUSE, (DeviceButton)i))
mouse_evt = true;
}
if (mouse_evt) {
return ScreenWithMenuElements::Input(input);
}
// LOG->Trace( "ScreenSelectMusic::Input()" );
// reset announcer timer
m_timerIdleComment.GetDeltaTime();
// debugging?
// I just like being able to see untransliterated titles occasionally.
if (input.DeviceI.device == DEVICE_KEYBOARD &&
input.DeviceI.button == KEY_F9) {
if (input.type != IET_FIRST_PRESS)
return false;
PREFSMAN->m_bShowNativeLanguage.Set(!PREFSMAN->m_bShowNativeLanguage);
MESSAGEMAN->Broadcast("DisplayLanguageChanged");
m_MusicWheel.RebuildWheelItems();
return true;
}
if (!IsTransitioning() && m_SelectionState != SelectionState_Finalized) {
bool bHoldingCtrl =
INPUTFILTER->IsBeingPressed(
DeviceInput(DEVICE_KEYBOARD, KEY_LCTRL)) ||
INPUTFILTER->IsBeingPressed(DeviceInput(DEVICE_KEYBOARD, KEY_RCTRL));
bool holding_shift =
INPUTFILTER->IsBeingPressed(
DeviceInput(DEVICE_KEYBOARD, KEY_LSHIFT)) ||
INPUTFILTER->IsBeingPressed(DeviceInput(DEVICE_KEYBOARD, KEY_RSHIFT));
wchar_t c = INPUTMAN->DeviceInputToChar(input.DeviceI, false);
MakeUpper(&c, 1);
if (holding_shift && bHoldingCtrl && c == 'R' &&
m_MusicWheel.IsSettled()) {
// Reload the currently selected song. -Kyz
Song* to_reload = m_MusicWheel.GetSelectedSong();
if (to_reload != nullptr) {
auto stepses = to_reload->GetAllSteps();
vector<string> oldChartkeys;
for (auto steps : stepses)
oldChartkeys.emplace_back(steps->GetChartKey());
to_reload->ReloadFromSongDir();
SONGMAN->ReconcileChartKeysForReloadedSong(to_reload,
oldChartkeys);
AfterMusicChange();
return true;
}
} else if (bHoldingCtrl && c == 'F' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
// Favorite the currently selected song. -Not Kyz
Song* fav_me_biatch = m_MusicWheel.GetSelectedSong();
if (fav_me_biatch != nullptr) {
Profile* pProfile = PROFILEMAN->GetProfile(PLAYER_1);
if (!fav_me_biatch->IsFavorited()) {
fav_me_biatch->SetFavorited(true);
pProfile->AddToFavorites(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
DLMAN->AddFavorite(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
pProfile->allplaylists.erase("Favorites");
SONGMAN->MakePlaylistFromFavorites(
pProfile->FavoritedCharts, pProfile->allplaylists);
} else {
fav_me_biatch->SetFavorited(false);
pProfile->RemoveFromFavorites(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
DLMAN->RemoveFavorite(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
}
DLMAN->RefreshFavourites();
Message msg("FavoritesUpdated");
MESSAGEMAN->Broadcast(msg);
m_MusicWheel.ChangeMusic(0);
return true;
}
} else if (bHoldingCtrl && c == 'M' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
// PermaMirror the currently selected song. -Not Kyz
Song* alwaysmirrorsmh = m_MusicWheel.GetSelectedSong();
if (alwaysmirrorsmh != nullptr) {
Profile* pProfile = PROFILEMAN->GetProfile(PLAYER_1);
if (!alwaysmirrorsmh->IsPermaMirror()) {
alwaysmirrorsmh->SetPermaMirror(true);
pProfile->AddToPermaMirror(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
} else {
alwaysmirrorsmh->SetPermaMirror(false);
pProfile->RemoveFromPermaMirror(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
}
Message msg("FavoritesUpdated");
MESSAGEMAN->Broadcast(msg);
m_MusicWheel.ChangeMusic(0);
return true;
}
} else if (bHoldingCtrl && c == 'G' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
Profile* pProfile = PROFILEMAN->GetProfile(PLAYER_1);
pProfile->AddGoal(GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
Song* asonglol = m_MusicWheel.GetSelectedSong();
if (!asonglol)
return true;
asonglol->SetHasGoal(true);
MESSAGEMAN->Broadcast("FavoritesUpdated");
m_MusicWheel.ChangeMusic(0);
return true;
} else if (bHoldingCtrl && c == 'Q' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
DifferentialReload();
return true;
} else if (bHoldingCtrl && c == 'S' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
PROFILEMAN->SaveProfile(PLAYER_1);
SCREENMAN->SystemMessage("Profile Saved");
return true;
} else if (bHoldingCtrl && c == 'P' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
ScreenTextEntry::TextEntry(
SM_BackFromNamePlaylist, "Name Playlist", "", 128);
MESSAGEMAN->Broadcast("DisplayAll");
return true;
} else if (bHoldingCtrl && c == 'A' && m_MusicWheel.IsSettled() &&
input.type == IET_FIRST_PRESS) {
if (SONGMAN->GetPlaylists().empty())
return true;
SONGMAN->GetPlaylists()[SONGMAN->activeplaylist].AddChart(
GAMESTATE->m_pCurSteps[PLAYER_1]->GetChartKey());
MESSAGEMAN->Broadcast("DisplaySinglePlaylist");
SCREENMAN->SystemMessage(
ssprintf("Added chart: %s to playlist: %s",
GAMESTATE->m_pCurSong->GetDisplayMainTitle().c_str(),
SONGMAN->activeplaylist.c_str()));
return true;
} else if (input.DeviceI.device == DEVICE_KEYBOARD && bHoldingCtrl &&
input.DeviceI.button == KEY_BACK &&
input.type == IET_FIRST_PRESS && m_MusicWheel.IsSettled()) {
// Keyboard shortcut to delete a song from disk (ctrl + backspace)
Song* songToDelete = m_MusicWheel.GetSelectedSong();
if (songToDelete && PREFSMAN->m_bAllowSongDeletion.Get()) {
m_pSongAwaitingDeletionConfirmation = songToDelete;
ScreenPrompt::Prompt(
SM_ConfirmDeleteSong,
ssprintf(PERMANENTLY_DELETE.GetValue(),
songToDelete->m_sMainTitle.c_str(),
songToDelete->GetSongDir().c_str()),
PROMPT_YES_NO);
return true;
}
}
}
if (!input.GameI.IsValid())
return false; // don't care
if (!GAMESTATE->IsHumanPlayer(input.pn))
return false;
// Check for "Press START again for options" button press
if (m_SelectionState == SelectionState_Finalized &&
input.MenuI == GAME_BUTTON_START && input.type != IET_RELEASE &&
OPTIONS_MENU_AVAILABLE.GetValue()) {
if (m_bGoToOptions)
return false; // got it already
if (!m_bAllowOptionsMenu)
return false; // not allowed
if (!m_bAllowOptionsMenuRepeat && input.type == IET_REPEAT) {
return false; // not allowed yet
}
m_bGoToOptions = true;
if (PLAY_SOUND_ON_ENTERING_OPTIONS_MENU)
m_soundStart.Play(true);
this->PlayCommand("ShowEnteringOptions");
// Re-queue SM_BeginFadingOut, since ShowEnteringOptions may have
// short-circuited animations.
this->ClearMessageQueue(SM_BeginFadingOut);
this->PostScreenMessage(SM_BeginFadingOut, this->GetTweenTimeLeft());
return true;
}
if (IsTransitioning())
return false; // ignore
// Handle unselect steps
// xxx: select button could conflict with OptionsList here -aj
if (m_SelectionState == SelectionState_SelectingSteps &&
m_bStepsChosen[input.pn] && input.MenuI == GAME_BUTTON_SELECT &&
input.type == IET_FIRST_PRESS) {
Message msg("StepsUnchosen");
msg.SetParam("Player", input.pn);
MESSAGEMAN->Broadcast(msg);
m_bStepsChosen[input.pn] = false;
return true;
}
if (m_SelectionState == SelectionState_Finalized ||
m_bStepsChosen[input.pn])
return false; // ignore
if (USE_PLAYER_SELECT_MENU) {
if (input.type == IET_RELEASE && input.MenuI == GAME_BUTTON_SELECT) {
SCREENMAN->AddNewScreenToTop(SELECT_MENU_NAME,
SM_BackFromPlayerOptions);
}
}
// handle OptionsList input
if (USE_OPTIONS_LIST) {
PlayerNumber pn = input.pn;
if (pn != PLAYER_INVALID) {
if (m_OptionsList[pn].IsOpened()) {
return m_OptionsList[pn].Input(input);
} else {
if (input.type == IET_RELEASE &&
input.MenuI == GAME_BUTTON_SELECT &&
m_bAcceptSelectRelease[pn])
m_OptionsList[pn].Open();
}
}
}
if (input.MenuI == GAME_BUTTON_SELECT && input.type != IET_REPEAT)
m_bAcceptSelectRelease[input.pn] = (input.type == IET_FIRST_PRESS);
if (SELECT_MENU_AVAILABLE && input.MenuI == GAME_BUTTON_SELECT &&
input.type != IET_REPEAT)
UpdateSelectButton(input.pn, input.type == IET_FIRST_PRESS);
if (SELECT_MENU_AVAILABLE && m_bSelectIsDown[input.pn]) {
if (input.type == IET_FIRST_PRESS && SELECT_MENU_CHANGES_DIFFICULTY) {
switch (input.MenuI) {
case GAME_BUTTON_LEFT:
ChangeSteps(input.pn, -1);
m_bAcceptSelectRelease[input.pn] = false;
break;
case GAME_BUTTON_RIGHT:
ChangeSteps(input.pn, +1);
m_bAcceptSelectRelease[input.pn] = false;
break;
case GAME_BUTTON_START:
m_bAcceptSelectRelease[input.pn] = false;
if (MODE_MENU_AVAILABLE)
m_MusicWheel.NextSort();
else
m_soundLocked.Play(true);
break;
default:
break;
}
}
if (input.type == IET_FIRST_PRESS &&
input.MenuI != GAME_BUTTON_SELECT) {
Message msg("SelectMenuInput");
msg.SetParam("Player", input.pn);
msg.SetParam(
"Button",
GameButtonToString(INPUTMAPPER->GetInputScheme(), input.MenuI));
MESSAGEMAN->Broadcast(msg);
m_bAcceptSelectRelease[input.pn] = false;
}
if (input.type == IET_FIRST_PRESS)
g_CanOpenOptionsList.Touch();
if (g_CanOpenOptionsList.Ago() > OPTIONS_LIST_TIMEOUT)
m_bAcceptSelectRelease[input.pn] = false;
return true;
}
if (m_SelectionState == SelectionState_SelectingSong &&
(input.MenuI == m_GameButtonNextSong ||
input.MenuI == m_GameButtonPreviousSong ||
input.MenuI == GAME_BUTTON_SELECT)) {
{
// If we're rouletting, hands off.
if (m_MusicWheel.IsRouletting())
return false;
bool bLeftIsDown = false;
bool bRightIsDown = false;
FOREACH_HumanPlayer(p)
{
if (m_OptionsList[p].IsOpened())
continue;
if (SELECT_MENU_AVAILABLE &&
INPUTMAPPER->IsBeingPressed(GAME_BUTTON_SELECT, p))
continue;
bLeftIsDown |= static_cast<int>(
INPUTMAPPER->IsBeingPressed(m_GameButtonPreviousSong, p));
bRightIsDown |= static_cast<int>(
INPUTMAPPER->IsBeingPressed(m_GameButtonNextSong, p));
}
bool bBothDown = bLeftIsDown && bRightIsDown;
bool bNeitherDown = !bLeftIsDown && !bRightIsDown;
if (bNeitherDown) {
// Both buttons released.
m_MusicWheel.Move(0);
} else if (bBothDown) {
m_MusicWheel.Move(0);
if (input.type == IET_FIRST_PRESS) {
if (input.MenuI == m_GameButtonPreviousSong)
m_MusicWheel.ChangeMusicUnlessLocked(-1);
else if (input.MenuI == m_GameButtonNextSong)
m_MusicWheel.ChangeMusicUnlessLocked(+1);
}
} else if (bLeftIsDown) {
if (input.type != IET_RELEASE) {
MESSAGEMAN->Broadcast("PreviousSong");
m_MusicWheel.Move(-1);
}
} else if (bRightIsDown) {
if (input.type != IET_RELEASE) {
MESSAGEMAN->Broadcast("NextSong");
m_MusicWheel.Move(+1);
}
} else {
FAIL_M("Logic bug: L/R keys in an impossible state?");
}
// Reset the repeat timer when the button is released.
// This fixes jumping when you release Left and Right after entering
// the sort code at the same if L & R aren't released at the exact
// same time.
if (input.type == IET_RELEASE) {
INPUTMAPPER->ResetKeyRepeat(m_GameButtonPreviousSong, input.pn);
INPUTMAPPER->ResetKeyRepeat(m_GameButtonNextSong, input.pn);
}
}
}
// To allow changing steps with gamebuttons, NOT WITH THE GODDAMN
// CODEDETECTOR yeah, wanted this since a while ago... -DaisuMaster
if (CHANGE_STEPS_WITH_GAME_BUTTONS) {
// Avoid any event not being first press
if (input.type != IET_FIRST_PRESS)
return false;
if (m_SelectionState == SelectionState_SelectingSong) {
if (input.MenuI == m_GameButtonPreviousDifficulty) {
ChangeSteps(input.pn, -1);
} else if (input.MenuI == m_GameButtonNextDifficulty) {
ChangeSteps(input.pn, +1);
}
}
}
// Actually I don't like to just copy and paste code because it may go
// wrong if something goes overlooked -DaisuMaster
if (CHANGE_GROUPS_WITH_GAME_BUTTONS) {
if (input.type != IET_FIRST_PRESS)
return false;
if (m_SelectionState == SelectionState_SelectingSong) {
if (input.MenuI == m_GameButtonPreviousGroup) {
RString sNewGroup = m_MusicWheel.JumpToPrevGroup();
m_MusicWheel.SelectSection(sNewGroup);
m_MusicWheel.SetOpenSection(sNewGroup);
MESSAGEMAN->Broadcast("PreviousGroup");
AfterMusicChange();
} else if (input.MenuI == m_GameButtonNextGroup) {
RString sNewGroup = m_MusicWheel.JumpToNextGroup();
m_MusicWheel.SelectSection(sNewGroup);
m_MusicWheel.SetOpenSection(sNewGroup);
MESSAGEMAN->Broadcast("NextGroup");
AfterMusicChange();
}
}
}
// two part confirms only means we can actually change songs here,
// so we need some hackery. -aj
if (TWO_PART_CONFIRMS_ONLY) {
if (m_SelectionState == SelectionState_SelectingSteps) {
if (input.MenuI == m_GameButtonPreviousSong) {
m_SelectionState = SelectionState_SelectingSong;
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
MESSAGEMAN->Broadcast("PreviousSong");
m_MusicWheel.ChangeMusicUnlessLocked(-1);
} else if (input.MenuI == m_GameButtonNextSong) {
m_SelectionState = SelectionState_SelectingSong;
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
MESSAGEMAN->Broadcast("NextSong");
m_MusicWheel.ChangeMusicUnlessLocked(+1);
}
// added an entry for difficulty change with gamebuttons
// -DaisuMaster
else if (input.MenuI == m_GameButtonPreviousDifficulty) {
m_SelectionState = SelectionState_SelectingSong;
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
ChangeSteps(input.pn, -1);
} else if (input.MenuI == m_GameButtonNextDifficulty) {
m_SelectionState = SelectionState_SelectingSong;
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
ChangeSteps(input.pn, +1);
}
// added also for groupchanges
else if (input.MenuI == m_GameButtonPreviousGroup) {
RString sNewGroup = m_MusicWheel.JumpToPrevGroup();
m_MusicWheel.SelectSection(sNewGroup);
m_MusicWheel.SetOpenSection(sNewGroup);
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
MESSAGEMAN->Broadcast("PreviousGroup");
AfterMusicChange();
} else if (input.MenuI == m_GameButtonNextGroup) {
RString sNewGroup = m_MusicWheel.JumpToNextGroup();
m_MusicWheel.SelectSection(sNewGroup);
m_MusicWheel.SetOpenSection(sNewGroup);
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
MESSAGEMAN->Broadcast("NextGroup");
AfterMusicChange();
}
}
} else {
if (m_SelectionState == SelectionState_SelectingSteps &&
input.type == IET_FIRST_PRESS && !m_bStepsChosen[input.pn]) {
if (input.MenuI == m_GameButtonNextSong ||
input.MenuI == m_GameButtonPreviousSong) {
if (input.MenuI == m_GameButtonPreviousSong) {
ChangeSteps(input.pn, -1);
} else if (input.MenuI == m_GameButtonNextSong) {
ChangeSteps(input.pn, +1);
}
} else if (
input.MenuI == GAME_BUTTON_MENUUP ||
input.MenuI ==
GAME_BUTTON_MENUDOWN) // && TWO_PART_DESELECTS_WITH_MENUUPDOWN
{
// XXX: should this be called "TwoPartCancelled"?
float fSeconds = m_MenuTimer->GetSeconds();
if (fSeconds > 10) {
Message msg("SongUnchosen");
msg.SetParam("Player", input.pn);
MESSAGEMAN->Broadcast(msg);
// unset all steps
FOREACH_ENUM(PlayerNumber, p)
m_bStepsChosen[p] = false;
m_SelectionState = SelectionState_SelectingSong;
}
}
}
}
if (input.type == IET_FIRST_PRESS && DetectCodes(input))
return true;
return ScreenWithMenuElements::Input(input);
}
bool
ScreenSelectMusic::DetectCodes(const InputEventPlus& input)
{
if (CodeDetector::EnteredPrevSteps(input.GameI.controller) &&
!CHANGE_STEPS_WITH_GAME_BUTTONS) {
ChangeSteps(input.pn, -1);
} else if (CodeDetector::EnteredNextSteps(input.GameI.controller) &&
!CHANGE_STEPS_WITH_GAME_BUTTONS) {
ChangeSteps(input.pn, +1);
} else if (CodeDetector::EnteredModeMenu(input.GameI.controller)) {
if (MODE_MENU_AVAILABLE)
m_MusicWheel.ChangeSort(SORT_MODE_MENU);
else
m_soundLocked.Play(true);
} else if (CodeDetector::EnteredNextSort(input.GameI.controller)) {
m_MusicWheel.NextSort();
} else if (CodeDetector::DetectAndAdjustMusicOptions(
input.GameI.controller)) {
m_soundOptionsChange.Play(true);
Message msg("PlayerOptionsChanged");
msg.SetParam("PlayerNumber", input.pn);
MESSAGEMAN->Broadcast(msg);
MESSAGEMAN->Broadcast("SongOptionsChanged");
} else if (CodeDetector::EnteredNextGroup(input.GameI.controller) &&
!CHANGE_GROUPS_WITH_GAME_BUTTONS) {
RString sNewGroup = m_MusicWheel.JumpToNextGroup();
m_MusicWheel.SelectSection(sNewGroup);
m_MusicWheel.SetOpenSection(sNewGroup);
MESSAGEMAN->Broadcast("NextGroup");
AfterMusicChange();
} else if (CodeDetector::EnteredPrevGroup(input.GameI.controller) &&
!CHANGE_GROUPS_WITH_GAME_BUTTONS) {
RString sNewGroup = m_MusicWheel.JumpToPrevGroup();
m_MusicWheel.SelectSection(sNewGroup);
m_MusicWheel.SetOpenSection(sNewGroup);
MESSAGEMAN->Broadcast("PreviousGroup");
AfterMusicChange();
} else if (CodeDetector::EnteredCloseFolder(input.GameI.controller)) {
RString sCurSection = m_MusicWheel.GetSelectedSection();
m_MusicWheel.SelectSection(sCurSection);
m_MusicWheel.SetOpenSection("");
AfterMusicChange();
} else {
return false;
}
return true;
}
void
ScreenSelectMusic::UpdateSelectButton(PlayerNumber pn, bool bSelectIsDown)
{
if (!SELECT_MENU_AVAILABLE || !CanChangeSong())
bSelectIsDown = false;
if (m_bSelectIsDown[pn] != bSelectIsDown) {
m_bSelectIsDown[pn] = bSelectIsDown;
Message msg(bSelectIsDown ? "SelectMenuOpened" : "SelectMenuClosed");
msg.SetParam("Player", pn);
MESSAGEMAN->Broadcast(msg);
}
}
void
ScreenSelectMusic::ChangeSteps(PlayerNumber pn, int dir)
{
LOG->Trace("ScreenSelectMusic::ChangeSteps( %d, %d )", pn, dir);
ASSERT(GAMESTATE->IsHumanPlayer(pn));
if (GAMESTATE->m_pCurSong) {
m_iSelection[pn] += dir;
if (WRAP_CHANGE_STEPS) {
wrap(m_iSelection[pn], m_vpSteps.size());
} else {
if (CLAMP(m_iSelection[pn], 0, m_vpSteps.size() - 1))
return;
}
// the user explicity switched difficulties. Update the preferred
// Difficulty and StepsType
Steps* pSteps = m_vpSteps[m_iSelection[pn]];
GAMESTATE->ChangePreferredDifficultyAndStepsType(
pn, pSteps->GetDifficulty(), pSteps->m_StepsType);
} else {
// If we're showing multiple StepsTypes in the list, don't allow
// changing the difficulty/StepsType when a non-Song, non-Course is
// selected. Changing the preferred Difficulty and StepsType by
// direction is complicated when multiple StepsTypes are being shown,
// so we don't support it.
if (CommonMetrics::AUTO_SET_STYLE)
return;
if (!GAMESTATE->ChangePreferredDifficulty(pn, dir))
return;
}
vector<PlayerNumber> vpns;
FOREACH_HumanPlayer(p)
{
if (pn == p || GAMESTATE->DifficultiesLocked()) {
m_iSelection[p] = m_iSelection[pn];
vpns.push_back(p);
}
}
AfterStepsOrTrailChange(vpns);
float fBalance = GameSoundManager::GetPlayerBalance(pn);
if (dir < 0) {
m_soundDifficultyEasier.SetProperty("Pan", fBalance);
m_soundDifficultyEasier.PlayCopy(true);
} else {
m_soundDifficultyHarder.SetProperty("Pan", fBalance);
m_soundDifficultyHarder.PlayCopy(true);
}
GAMESTATE->ForceOtherPlayersToCompatibleSteps(pn);
Message msg("ChangeSteps");
msg.SetParam("Player", pn);
msg.SetParam("Direction", dir);
MESSAGEMAN->Broadcast(msg);
}
void
ScreenSelectMusic::HandleMessage(const Message& msg)
{
if (m_bRunning && msg == Message_PlayerJoined) {
PlayerNumber master_pn = GAMESTATE->GetMasterPlayerNumber();
// The current steps may no longer be playable. If one player has double
// steps selected, they are no longer playable now that P2 has joined.
// TODO: Invalidate the CurSteps only if they are no longer playable.
// That way, after music change will clamp to the nearest in the
// StepsDisplayList.
GAMESTATE->m_pCurSteps[master_pn].SetWithoutBroadcast(NULL);
FOREACH_ENUM(PlayerNumber, p)
GAMESTATE->m_pCurSteps[p].SetWithoutBroadcast(NULL);
/* If a course is selected, it may no longer be playable.
* Let MusicWheel know about the late join. */
m_MusicWheel.PlayerJoined();
AfterMusicChange();
int iSel = 0;
PlayerNumber pn;
bool b = msg.GetParam("Player", pn);
ASSERT(b);
// load player profiles
if (GAMESTATE->HaveProfileToLoad()) {
GAMESTATE->LoadProfiles(
true); // I guess you could always load edits here...
SCREENMAN->ZeroNextUpdate(); // be kind, don't skip frames if you
// can avoid it
}
m_iSelection[pn] = iSel;
Steps* pSteps = m_vpSteps.empty() ? NULL : m_vpSteps[m_iSelection[pn]];
GAMESTATE->m_pCurSteps[pn].Set(pSteps);
}
ScreenWithMenuElements::HandleMessage(msg);
}
void
ScreenSelectMusic::HandleScreenMessage(const ScreenMessage SM)
{
if (SM == SM_AllowOptionsMenuRepeat) {
m_bAllowOptionsMenuRepeat = true;
} else if (SM == SM_MenuTimer) {
if (m_MusicWheel.IsRouletting()) {
MenuStart(InputEventPlus());
m_MenuTimer->SetSeconds(ROULETTE_TIMER_SECONDS);
m_MenuTimer->Start();
} else if (DO_ROULETTE_ON_MENU_TIMER &&
m_MusicWheel.GetSelectedSong() == NULL) {
m_MenuTimer->SetSeconds(ROULETTE_TIMER_SECONDS);
m_MenuTimer->Start();
} else {
// Finish sort changing so that the wheel can respond immediately to
// our request to choose random.
m_MusicWheel.FinishChangingSorts();
MenuStart(InputEventPlus());
}
return;
} else if (SM == SM_GoToPrevScreen) {
/* We may have stray SM_SongChanged messages from the music wheel.
* We can't handle them anymore, since the title menu (and attract
* screens) reset the game state, so just discard them. */
ClearMessageQueue();
} else if (SM == SM_BeginFadingOut) {
m_bAllowOptionsMenu = false;
if (OPTIONS_MENU_AVAILABLE && !m_bGoToOptions)
this->PlayCommand("HidePressStartForOptions");
GAMESTATE->m_bInNetGameplay = false;
this->PostScreenMessage(SM_GoToNextScreen, this->GetTweenTimeLeft());
} else if (SM == SM_GoToNextScreen) {
if (!m_bGoToOptions)
SOUND->StopMusic();
} else if (SM == SM_SongChanged) {
AfterMusicChange();
} else if (SM == SM_SortOrderChanging) // happens immediately
{
this->PlayCommand("SortChange");
} else if (SM == SM_GainFocus) {
#if !defined(WITHOUT_NETWORKING)
DLMAN->UpdateDLSpeed(false);
#endif
CodeDetector::RefreshCacheItems(CODES);
} else if (SM == SM_LoseFocus) {
CodeDetector::RefreshCacheItems(); // reset for other screens
} else if (SM == SM_ConfirmDeleteSong) {
if (ScreenPrompt::s_LastAnswer == ANSWER_YES) {
OnConfirmSongDeletion();
} else {
// need to resume the song preview that was automatically paused
m_MusicWheel.ChangeMusic(0);
}
}
if (SM == SM_BackFromNamePlaylist) {
Playlist pl;
pl.name = ScreenTextEntry::s_sLastAnswer;
if (pl.name != "") {
SONGMAN->GetPlaylists().emplace(pl.name, pl);
SONGMAN->activeplaylist = pl.name;
Message msg("DisplayAll");
MESSAGEMAN->Broadcast(msg);
}
}
ScreenWithMenuElements::HandleScreenMessage(SM);
}
bool
ScreenSelectMusic::MenuStart(const InputEventPlus& input)
{
if (input.type != IET_FIRST_PRESS)
return false;
/* If select is being pressed at the same time, this is probably an attempt
* to change the sort, not to pick a song or difficulty. If it gets here,
* the actual select press was probably hit during a tween and ignored.
* Ignore it. */
if (input.pn != PLAYER_INVALID &&
INPUTMAPPER->IsBeingPressed(GAME_BUTTON_SELECT, input.pn))
return false;
// Honor locked input for start presses.
if (m_fLockInputSecs > 0)
return false;
return SelectCurrent(input.pn);
}
bool
ScreenSelectMusic::SelectCurrent(PlayerNumber pn)
{
switch (m_SelectionState) {
case SelectionState_Finalized: {
LOG->Warn("song selection made while selectionstate_finalized");
return false;
}
case SelectionState_SelectingSong:
// If false, we don't have a selection just yet.
if (!m_MusicWheel.Select())
return false;
// a song was selected
if (m_MusicWheel.GetSelectedSong() != NULL) {
if (TWO_PART_CONFIRMS_ONLY &&
SAMPLE_MUSIC_PREVIEW_MODE ==
SampleMusicPreviewMode_StartToPreview) {
// start playing the preview music.
g_bSampleMusicWaiting = true;
CheckBackgroundRequests(true);
}
const bool bIsNew =
PROFILEMAN->IsSongNew(m_MusicWheel.GetSelectedSong());
bool bIsHard = false;
FOREACH_HumanPlayer(p)
{
if (GAMESTATE->m_pCurSteps[p] &&
GAMESTATE->m_pCurSteps[p]->GetMeter() >=
HARD_COMMENT_METER)
bIsHard = true;
}
// See if this song is a repeat.
// If we're in event mode, only check the last five songs.
bool bIsRepeat = false;
int i = 0;
if (GAMESTATE->IsEventMode())
i = max(0, int(STATSMAN->m_vPlayedStageStats.size()) - 5);
for (; i < (int)STATSMAN->m_vPlayedStageStats.size(); ++i)
if (STATSMAN->m_vPlayedStageStats[i]
.m_vpPlayedSongs.back() ==
m_MusicWheel.GetSelectedSong())
bIsRepeat = true;
if (bIsRepeat)
SOUND->PlayOnceFromAnnouncer("select music comment repeat");
else if (bIsNew)
SOUND->PlayOnceFromAnnouncer("select music comment new");
else if (bIsHard)
SOUND->PlayOnceFromAnnouncer("select music comment hard");
else
SOUND->PlayOnceFromAnnouncer(
"select music comment general");
} else {
// We haven't made a selection yet.
return false;
}
// I believe this is for those who like pump pro. -aj
MESSAGEMAN->Broadcast("SongChosen");
break;
case SelectionState_SelectingSteps: {
bool bInitiatedByMenuTimer = pn == PLAYER_INVALID;
bool bAllOtherHumanPlayersDone = true;
FOREACH_HumanPlayer(p)
{
if (p == pn)
continue;
bAllOtherHumanPlayersDone &=
static_cast<int>(m_bStepsChosen[p]);
}
bool bAllPlayersDoneSelectingSteps =
bInitiatedByMenuTimer || bAllOtherHumanPlayersDone;
if (TWO_PART_CONFIRMS_ONLY)
bAllPlayersDoneSelectingSteps = true;
if (!bAllPlayersDoneSelectingSteps) {
m_bStepsChosen[pn] = true;
m_soundStart.Play(true);
// impldiff: Pump it Up Pro uses "StepsSelected". -aj
Message msg("StepsChosen");
msg.SetParam("Player", pn);
MESSAGEMAN->Broadcast(msg);
return true;
}
} break;
}
FOREACH_ENUM(PlayerNumber, p)
{
if (!TWO_PART_SELECTION ||
m_SelectionState == SelectionState_SelectingSteps) {
if (m_OptionsList[p].IsOpened())
m_OptionsList[p].Close();
}
UpdateSelectButton(p, false);
}
m_SelectionState = GetNextSelectionState();
Message msg("Start" + SelectionStateToString(m_SelectionState));
MESSAGEMAN->Broadcast(msg);
m_soundStart.Play(true);
// If the MenuTimer has forced us to move on && TWO_PART_CONFIRMS_ONLY,
// set Selection State to finalized and move on.
if (TWO_PART_CONFIRMS_ONLY) {
if (m_MenuTimer->GetSeconds() < 1) {
m_SelectionState = SelectionState_Finalized;
}
}
if (m_SelectionState == SelectionState_Finalized) {
#if !defined(WITHOUT_NETWORKING)
DLMAN->UpdateDLSpeed(true);
#endif
m_MenuTimer->Stop();
FOREACH_HumanPlayer(p)
{
if (!m_bStepsChosen[p]) {
m_bStepsChosen[p] = true;
// Don't play start sound. We play it again below on finalized
// m_soundStart.Play(true);
Message lMsg("StepsChosen");
lMsg.SetParam("Player", p);
MESSAGEMAN->Broadcast(lMsg);
}
}
// Now that Steps have been chosen, set a Style that can play them.
GAMESTATE->SetCompatibleStylesForPlayers();
GAMESTATE->ForceSharedSidesMatch();
/* If we're currently waiting on song assets, abort all except the music
* and start the music, so if we make a choice quickly before background
* requests come through, the music will still start. */
g_bCDTitleWaiting = g_bBannerWaiting = false;
m_BackgroundLoader.Abort();
CheckBackgroundRequests(true);
if (OPTIONS_MENU_AVAILABLE) {
// show "hold START for options"
this->PlayCommand("ShowPressStartForOptions");
m_bAllowOptionsMenu = true;
/* Don't accept a held START for a little while, so it's not
* hit accidentally. Accept an initial START right away, though,
* so we don't ignore deliberate fast presses (which would be
* annoying). */
if (PREFSMAN->m_AllowHoldForOptions.Get()) {
this->PostScreenMessage(SM_AllowOptionsMenuRepeat, 0.5f);
}
StartTransitioningScreen(SM_None);
float fTime =
max(SHOW_OPTIONS_MESSAGE_SECONDS, this->GetTweenTimeLeft());
this->PostScreenMessage(SM_BeginFadingOut, fTime);
} else {
StartTransitioningScreen(SM_BeginFadingOut);
}
} else // !finalized. Set the timer for selecting difficulty and mods.
{
float fSeconds = m_MenuTimer->GetSeconds();
if (fSeconds < 10) {
m_MenuTimer->SetSeconds(TWO_PART_TIMER_SECONDS); // was 13 -aj
m_MenuTimer->Start();
}
}
return false;
}
bool
ScreenSelectMusic::MenuBack(const InputEventPlus& /* input */)
{
// Handle unselect song (ffff)
// todo: this isn't right at all. -aj
/*
if( m_SelectionState == SelectionState_SelectingSteps &&
!m_bStepsChosen[input.pn] && input.MenuI == GAME_BUTTON_BACK &&
input.type == IET_FIRST_PRESS )
{
// if a player has chosen their steps already, don't unchoose song.
FOREACH_HumanPlayer( p )
if( m_bStepsChosen[p] ) return;
// and if we get here...
Message msg("SongUnchosen");
msg.SetParam( "Player", input.pn );
MESSAGEMAN->Broadcast( msg );
m_SelectionState = SelectionState_SelectingSong;
return true;
}
*/
m_BackgroundLoader.Abort();
Cancel(SM_GoToPrevScreen);
return true;
}
void
ScreenSelectMusic::AfterStepsOrTrailChange(const vector<PlayerNumber>& vpns)
{
if (TWO_PART_CONFIRMS_ONLY &&
m_SelectionState == SelectionState_SelectingSteps) {
// if TWO_PART_CONFIRMS_ONLY, changing difficulties unsets the song. -aj
m_SelectionState = SelectionState_SelectingSong;
MESSAGEMAN->Broadcast("TwoPartConfirmCanceled");
}
FOREACH_CONST(PlayerNumber, vpns, p)
{
PlayerNumber pn = *p;
ASSERT(GAMESTATE->IsHumanPlayer(pn));
if (GAMESTATE->m_pCurSong) {
CLAMP(m_iSelection[pn], 0, m_vpSteps.size() - 1);
Song* pSong = GAMESTATE->m_pCurSong;
Steps* pSteps =
m_vpSteps.empty() ? NULL : m_vpSteps[m_iSelection[pn]];
GAMESTATE->m_pCurSteps[pn].Set(pSteps);
int iScore = 0;
if (pSteps) {
const Profile* pProfile = PROFILEMAN->GetProfile(pn);
iScore = pProfile->GetStepsHighScoreList(pSong, pSteps)
.GetTopScore()
.GetScore();
}
m_textHighScore[pn].SetText(
ssprintf("%*i", NUM_SCORE_DIGITS, iScore));
} else {
// The numbers shouldn't stay if the current selection is NULL.
m_textHighScore[pn].SetText(NULL_SCORE_STRING);
}
}
}
void
ScreenSelectMusic::SwitchToPreferredDifficulty()
{
FOREACH_HumanPlayer(pn)
{
// Find the closest match to the user's preferred difficulty and
// StepsType.
int iCurDifference = -1;
int& iSelection = m_iSelection[pn];
FOREACH_CONST(Steps*, m_vpSteps, s)
{
int i = s - m_vpSteps.begin();
// If the current steps are listed, use them.
if (GAMESTATE->m_pCurSteps[pn] == *s) {
iSelection = i;
break;
}
if (GAMESTATE->m_PreferredDifficulty[pn] != Difficulty_Invalid) {
int iDifficultyDifference = abs(
(*s)->GetDifficulty() - GAMESTATE->m_PreferredDifficulty[pn]);
int iStepsTypeDifference = 0;
if (GAMESTATE->m_PreferredStepsType != StepsType_Invalid)
iStepsTypeDifference =
abs((*s)->m_StepsType - GAMESTATE->m_PreferredStepsType);
int iTotalDifference =
iStepsTypeDifference * NUM_Difficulty + iDifficultyDifference;
if (iCurDifference == -1 || iTotalDifference < iCurDifference) {
iSelection = i;
iCurDifference = iTotalDifference;
}
}
}
CLAMP(iSelection, 0, m_vpSteps.size() - 1);
}
if (GAMESTATE->DifficultiesLocked()) {
FOREACH_HumanPlayer(p) m_iSelection[p] =
m_iSelection[GAMESTATE->GetMasterPlayerNumber()];
}
}
void
ScreenSelectMusic::AfterMusicChange()
{
if (!m_MusicWheel.IsRouletting())
m_MenuTimer->Stall();
Song* pSong = m_MusicWheel.GetSelectedSong();
GAMESTATE->m_pCurSong.Set(pSong);
if (pSong != nullptr)
GAMESTATE->m_pPreferredSong = pSong;
m_vpSteps.clear();
m_Banner.SetMovingFast(!!m_MusicWheel.IsMoving());
vector<RString> m_Artists, m_AltArtists;
if (SAMPLE_MUSIC_PREVIEW_MODE != SampleMusicPreviewMode_LastSong) {
m_sSampleMusicToPlay = "";
}
m_pSampleMusicTimingData = NULL;
g_sCDTitlePath = "";
g_sBannerPath = "";
g_bWantFallbackCdTitle = false;
bool bWantBanner = true;
static SortOrder s_lastSortOrder = SortOrder_Invalid;
if (GAMESTATE->m_SortOrder != s_lastSortOrder) {
// Reload to let Lua metrics have a chance to change the help text.
s_lastSortOrder = GAMESTATE->m_SortOrder;
}
WheelItemDataType wtype = m_MusicWheel.GetSelectedType();
SampleMusicPreviewMode pmode;
switch (wtype) {
case WheelItemDataType_Section:
case WheelItemDataType_Sort:
case WheelItemDataType_Roulette:
case WheelItemDataType_Random:
case WheelItemDataType_Custom:
FOREACH_PlayerNumber(p) m_iSelection[p] = -1;
g_sCDTitlePath = ""; // none
if (SAMPLE_MUSIC_PREVIEW_MODE == SampleMusicPreviewMode_LastSong) {
// HACK: Make random music work in LastSong mode. -aj
if (m_sSampleMusicToPlay == m_sRandomMusicPath) {
m_fSampleStartSeconds = 0;
m_fSampleLengthSeconds = -1;
}
} else {
m_fSampleStartSeconds = 0;
m_fSampleLengthSeconds = -1;
}
switch (wtype) {
case WheelItemDataType_Section:
// reduce scope
{
SortOrder curSort = GAMESTATE->m_SortOrder;
if (curSort == SORT_GROUP) {
g_sBannerPath = SONGMAN->GetSongGroupBannerPath(
m_MusicWheel.GetSelectedSection());
} else {
bWantBanner = false; // we load it ourself
m_Banner.LoadFromSortOrder(curSort);
}
if (SAMPLE_MUSIC_PREVIEW_MODE !=
SampleMusicPreviewMode_LastSong)
m_sSampleMusicToPlay = m_sSectionMusicPath;
}
break;
case WheelItemDataType_Sort:
bWantBanner = false; // we load it ourself
m_Banner.LoadMode();
if (SAMPLE_MUSIC_PREVIEW_MODE !=
SampleMusicPreviewMode_LastSong)
m_sSampleMusicToPlay = m_sSortMusicPath;
break;
case WheelItemDataType_Roulette:
bWantBanner = false; // we load it ourself
m_Banner.LoadRoulette();
if (SAMPLE_MUSIC_PREVIEW_MODE !=
SampleMusicPreviewMode_LastSong)
m_sSampleMusicToPlay = m_sRouletteMusicPath;
break;
case WheelItemDataType_Random:
bWantBanner = false; // we load it ourself
m_Banner.LoadRandom();
// if( SAMPLE_MUSIC_PREVIEW_MODE !=
// SampleMusicPreviewMode_LastSong )
m_sSampleMusicToPlay = m_sRandomMusicPath;
break;
case WheelItemDataType_Custom: {
bWantBanner = false; // we load it ourself
RString sBannerName =
GetMusicWheel()
->GetCurWheelItemData(
GetMusicWheel()->GetCurrentIndex())
->m_pAction->m_sName.c_str();
m_Banner.LoadCustom(sBannerName);
if (SAMPLE_MUSIC_PREVIEW_MODE !=
SampleMusicPreviewMode_LastSong)
m_sSampleMusicToPlay = m_sSectionMusicPath;
} break;
default:
FAIL_M(ssprintf("Invalid WheelItemDataType: %i", wtype));
}
// override this if the sample music mode wants to.
/*
if(SAMPLE_MUSIC_PREVIEW_MODE == SampleMusicPreviewMode_LastSong)
{
m_sSampleMusicToPlay = pSong->GetMusicPath();
m_pSampleMusicTimingData = &pSong->m_SongTiming;
m_fSampleStartSeconds = pSong->m_fMusicSampleStartSeconds;
m_fSampleLengthSeconds = pSong->m_fMusicSampleLengthSeconds;
}
*/
break;
case WheelItemDataType_Song:
case WheelItemDataType_Portal:
// check SampleMusicPreviewMode here.
pmode = SAMPLE_MUSIC_PREVIEW_MODE;
switch (pmode) {
case SampleMusicPreviewMode_ScreenMusic:
// play the screen music
m_sSampleMusicToPlay = m_sLoopMusicPath;
m_fSampleStartSeconds = 0;
m_fSampleLengthSeconds = -1;
break;
case SampleMusicPreviewMode_StartToPreview:
// we want to load the sample music, but we don't want to
// actually play it. fall through. -aj
case SampleMusicPreviewMode_Normal:
case SampleMusicPreviewMode_LastSong: // fall through
// play the sample music
m_sSampleMusicToPlay = pSong->GetPreviewMusicPath();
if (!m_sSampleMusicToPlay.empty() &&
ActorUtil::GetFileType(m_sSampleMusicToPlay) !=
FT_Sound) {
LuaHelpers::ReportScriptErrorFmt(
"Music file %s for song is not a sound file, "
"ignoring.",
m_sSampleMusicToPlay.c_str());
m_sSampleMusicToPlay = "";
}
m_pSampleMusicTimingData = &pSong->m_SongTiming;
m_fSampleStartSeconds = pSong->GetPreviewStartSeconds();
m_fSampleLengthSeconds = pSong->m_fMusicSampleLengthSeconds;
break;
default:
FAIL_M(ssprintf("Invalid preview mode: %i", pmode));
}
SongUtil::GetPlayableSteps(pSong, m_vpSteps);
if (m_vpSteps.empty()) {
// LuaHelpers::ReportScriptError("GetPlayableSteps returned
// nothing.");
}
if (PREFSMAN->m_bShowBanners)
g_sBannerPath = pSong->GetBannerPath();
g_sCDTitlePath = pSong->GetCDTitlePath();
g_bWantFallbackCdTitle = true;
SwitchToPreferredDifficulty();
break;
default:
FAIL_M(ssprintf("Invalid WheelItemDataType: %i", wtype));
}
m_sprCDTitleFront.UnloadTexture();
m_sprCDTitleBack.UnloadTexture();
// Cancel any previous, incomplete requests for song assets,
// since we need new ones.
m_BackgroundLoader.Abort();
g_bCDTitleWaiting = false;
if (!g_sCDTitlePath.empty() || g_bWantFallbackCdTitle) {
LOG->Trace("cache \"%s\"", g_sCDTitlePath.c_str());
m_BackgroundLoader.CacheFile(g_sCDTitlePath); // empty OK
g_bCDTitleWaiting = true;
}
g_bBannerWaiting = false;
if (bWantBanner) {
LOG->Trace("LoadFromCachedBanner(%s)", g_sBannerPath.c_str());
if (m_Banner.LoadFromCachedBanner(g_sBannerPath)) {
/* If the high-res banner is already loaded, just delay before
* loading it, so the low-res one has time to fade in. */
if (!TEXTUREMAN->IsTextureRegistered(
Sprite::SongBannerTexture(g_sBannerPath)))
m_BackgroundLoader.CacheFile(g_sBannerPath);
g_bBannerWaiting = true;
}
}
// Don't stop music if it's already playing the right file.
g_bSampleMusicWaiting = false;
if (!m_MusicWheel.IsRouletting() &&
SOUND->GetMusicPath() != m_sSampleMusicToPlay) {
SOUND->StopMusic();
// some SampleMusicPreviewModes don't want the sample music immediately.
if (SAMPLE_MUSIC_PREVIEW_MODE !=
SampleMusicPreviewMode_StartToPreview) {
if (!m_sSampleMusicToPlay.empty())
g_bSampleMusicWaiting = true;
}
}
g_StartedLoadingAt.Touch();
vector<PlayerNumber> vpns;
FOREACH_HumanPlayer(p) vpns.push_back(p);
AfterStepsOrTrailChange(vpns);
}
void
ScreenSelectMusic::OpenOptionsList(PlayerNumber pn)
{
if (pn != PLAYER_INVALID) {
m_MusicWheel.Move(0);
m_OptionsList[pn].Open();
}
}
void
ScreenSelectMusic::OnConfirmSongDeletion()
{
Song* deletedSong = m_pSongAwaitingDeletionConfirmation;
if (deletedSong == nullptr) {
LOG->Warn("Attempted to delete a null song "
"(ScreenSelectMusic::OnConfirmSongDeletion)");
return;
}
// ensure Stepmania is configured to allow song deletion
if (!PREFSMAN->m_bAllowSongDeletion.Get()) {
LOG->Warn("Attemped to delete a song but AllowSongDeletion was set to "
"false (ScreenSelectMusic::OnConfirmSongDeletion)");
return;
}
RString deleteDir = deletedSong->GetSongDir();
// flush the deleted song from any caches
SONGMAN->UnlistSong(deletedSong);
// refresh the song list
m_MusicWheel.ReloadSongList(false, "");
LOG->Trace("Deleting song: '%s'\n", deleteDir.c_str());
// delete the song directory from disk
FILEMAN->DeleteRecursive(deleteDir);
m_pSongAwaitingDeletionConfirmation = NULL;
}
bool
ScreenSelectMusic::can_open_options_list(PlayerNumber pn)
{
if (!USE_OPTIONS_LIST) {
return false;
}
if (pn >= NUM_PLAYERS) {
return false;
}
if (m_OptionsList[pn].IsOpened()) {
return false;
}
return true;
}
int
ScreenSelectMusic::GetSelectionState()
{
return static_cast<int>(m_SelectionState);
}
// lua start
#include "LuaBinding.h"
/** @brief Allow Lua to have access to the ScreenSelectMusic. */
class LunaScreenSelectMusic : public Luna<ScreenSelectMusic>
{
public:
static int GetGoToOptions(T* p, lua_State* L)
{
lua_pushboolean(L, p->GetGoToOptions());
return 1;
}
static int GetMusicWheel(T* p, lua_State* L)
{
p->GetMusicWheel()->PushSelf(L);
return 1;
}
static int OpenOptionsList(T* p, lua_State* L)
{
PlayerNumber pn = Enum::Check<PlayerNumber>(L, 1);
if (p->can_open_options_list(pn)) {
p->OpenOptionsList(pn);
}
COMMON_RETURN_SELF;
}
static int CanOpenOptionsList(T* p, lua_State* L)
{
PlayerNumber pn = Enum::Check<PlayerNumber>(L, 1);
lua_pushboolean(L, p->can_open_options_list(pn));
return 1;
}
static int SelectCurrent(T* p, lua_State* L)
{
p->SelectCurrent(Enum::Check<PlayerNumber>(L, 1));
return 1;
}
static int GetSelectionState(T* p, lua_State* L)
{
lua_pushnumber(L, p->GetSelectionState());
return 1;
}
static int StartPlaylistAsCourse(T* p, lua_State* L)
{
string name = SArg(1);
Playlist& pl = SONGMAN->GetPlaylists()[name];
// don't allow empty playlists to be started as a course
if (pl.chartlist.empty())
return 1;
// dont allow playlists with an unloaded chart to be played as a course
FOREACH(Chart, pl.chartlist, ch)
if (!ch->loaded)
return 1;
SONGMAN->playlistcourse = name;
GAMESTATE->isplaylistcourse = true;
p->GetMusicWheel()->SelectSong(pl.chartlist[0].songptr);
GAMESTATE->m_SongOptions.GetPreferred().m_fMusicRate =
pl.chartlist[0].rate;
MESSAGEMAN->Broadcast("RateChanged");
p->SelectCurrent(PLAYER_1);
return 1;
}
static int PlayReplay(T* p, lua_State* L)
{
// get the highscore from lua and make the AI load it
HighScore* hs = Luna<HighScore>::check(L, 1);
PlayerAI::SetScoreData(hs);
// prepare old mods to return to
const RString oldMods = GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetCurrent()
.GetString();
// set the heck out of the current rate to make sure everything runs
// correctly
float scoreRate = hs->GetMusicRate();
float oldRate = GAMESTATE->m_SongOptions.GetPreferred().m_fMusicRate;
GAMESTATE->m_SongOptions.GetSong().m_fMusicRate = scoreRate;
GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate = scoreRate;
GAMESTATE->m_SongOptions.GetPreferred().m_fMusicRate = scoreRate;
MESSAGEMAN->Broadcast("RateChanged");
// set mods based on the score, hopefully
// it is known that xmod->cmod and back does not work most of the time.
/*
CHECKPOINT_M("Setting mods for Replay Viewing.");
RString mods = hs->GetModifiers();
GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerOptions.GetSong().FromString(mods);
GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerOptions.GetCurrent().FromString(mods);
GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerOptions.GetPreferred().FromString(mods);
CHECKPOINT_M("Replay mods set.");
*/
// Set mirror mode on if mirror was on in the replay
// Also get ready to reset the turn mods to what they were before
RString mods = hs->GetModifiers();
vector<RString> oldTurns;
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetSong()
.GetTurnMods(oldTurns);
if (mods.find("Mirror") != mods.npos) {
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetSong()
.m_bTurns[PlayerOptions::TURN_MIRROR] = true;
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetCurrent()
.m_bTurns[PlayerOptions::TURN_MIRROR] = true;
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetPreferred()
.m_bTurns[PlayerOptions::TURN_MIRROR] = true;
}
else
{
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetSong()
.m_bTurns[PlayerOptions::TURN_MIRROR] = false;
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetCurrent()
.m_bTurns[PlayerOptions::TURN_MIRROR] = false;
GAMESTATE->m_pPlayerState[PLAYER_1]
->m_PlayerOptions.GetPreferred()
.m_bTurns[PlayerOptions::TURN_MIRROR] = false;
}
GAMEMAN->m_bResetTurns = true;
GAMEMAN->m_vTurnsToReset = oldTurns;
// lock the game into replay mode and GO
LOG->Trace("Viewing replay for score key %s",
hs->GetScoreKey().c_str());
GamePreferences::m_AutoPlay.Set(PC_REPLAY);
GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerController = PC_REPLAY;
p->SelectCurrent(PLAYER_1);
// set mods back to what they were before
GAMEMAN->m_bResetModifiers = true;
GAMEMAN->m_fPreviousRate = oldRate;
GAMEMAN->m_sModsToReset = oldMods;
return 1;
}
static int ShowEvalScreenForScore(T* p, lua_State* L)
{
// get the highscore from lua and fake it to the most recent score
HighScore* hs = Luna<HighScore>::check(L, 1);
SCOREMAN->PutScoreAtTheTop(hs->GetScoreKey());
// set to replay mode to disable score saving
GamePreferences::m_AutoPlay.Set(PC_REPLAY);
// construct the current stage stats and stuff to the best of our
// ability
StageStats ss;
ss.Init();
auto score = SCOREMAN->GetMostRecentScore();
score->LoadReplayData();
auto& pss = ss.m_player[0];
pss.m_HighScore = *score;
pss.CurWifeScore = score->GetWifeScore();
pss.m_fWifeScore = score->GetWifeScore();
pss.m_vNoteRowVector = score->GetNoteRowVector();
pss.m_vOffsetVector = score->GetOffsetVector();
pss.m_vTapNoteTypeVector = score->GetTapNoteTypeVector();
pss.m_vTrackVector = score->GetTrackVector();
score->UnloadReplayData();
pss.m_iSongsPassed = 1;
pss.m_iSongsPlayed = 1;
pss.everusedautoplay = true;
for (int i = TNS_Miss; i < NUM_TapNoteScore; i++) {
pss.m_iTapNoteScores[i] = score->GetTapNoteScore((TapNoteScore)i);
}
for (int i = 0; i < NUM_HoldNoteScore; i++) {
pss.m_iHoldNoteScores[i] =
score->GetHoldNoteScore((HoldNoteScore)i);
}
ss.m_vpPlayedSongs.emplace_back(GAMESTATE->m_pCurSong);
STATSMAN->m_CurStageStats = ss;
STATSMAN->m_vPlayedStageStats.emplace_back(ss);
// set the rate so the MSD and rate display doesnt look weird
float scoreRate = hs->GetMusicRate();
float oldRate = GAMESTATE->m_SongOptions.GetPreferred().m_fMusicRate;
GAMESTATE->m_SongOptions.GetSong().m_fMusicRate = scoreRate;
GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate = scoreRate;
GAMESTATE->m_SongOptions.GetPreferred().m_fMusicRate = scoreRate;
MESSAGEMAN->Broadcast("RateChanged");
// go
LOG->Trace("Viewing evaluation screen for score key %s",
score->GetScoreKey().c_str());
SCREENMAN->SetNewScreen("ScreenEvaluationNormal");
// set rate back to what it was before
GAMEMAN->m_bResetModifiers = true;
GAMEMAN->m_fPreviousRate = oldRate;
return 1;
}
LunaScreenSelectMusic()
{
ADD_METHOD(GetGoToOptions);
ADD_METHOD(GetMusicWheel);
ADD_METHOD(OpenOptionsList);
ADD_METHOD(CanOpenOptionsList);
ADD_METHOD(SelectCurrent);
ADD_METHOD(GetSelectionState);
ADD_METHOD(StartPlaylistAsCourse);
ADD_METHOD(PlayReplay);
ADD_METHOD(ShowEvalScreenForScore);
}
};
LUA_REGISTER_DERIVED_CLASS(ScreenSelectMusic, ScreenWithMenuElements)
// lua end
/*
* (c) 2001-2004 Chris Danford
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
|
#include "gl/framebuffer.h"
#include "gl/glError.h"
#include "gl/primitives.h"
#include "gl/renderState.h"
#include "gl/hardware.h"
#include "gl/texture.h"
#include "log.h"
#include "glm/vec2.hpp"
#include <cmath>
namespace Tangram {
class RenderTexture : public Texture {
static constexpr TextureOptions textureOptions() {
TextureOptions options;
options.minFilter = TextureMinFilter::NEAREST;
options.magFilter = TextureMagFilter::NEAREST;
return options;
}
public:
RenderTexture(int width, int height)
: Texture(textureOptions()) {
resize(width, height);
}
GLuint glHandle() const { return m_glHandle; }
};
FrameBuffer::FrameBuffer(int _width, int _height, bool _colorRenderBuffer) :
m_glFrameBufferHandle(0),
m_glDepthRenderBufferHandle(0),
m_glColorRenderBufferHandle(0),
m_valid(false),
m_colorRenderBuffer(_colorRenderBuffer),
m_width(_width), m_height(_height) {
}
bool FrameBuffer::applyAsRenderTarget(RenderState& _rs, ColorF _clearColor) {
if (!m_glFrameBufferHandle) {
init(_rs);
}
if (!m_valid) {
return false;
}
FrameBuffer::apply(_rs, m_glFrameBufferHandle, {m_width, m_height}, _clearColor);
return true;
}
void FrameBuffer::apply(RenderState& _rs, GLuint _handle, glm::vec2 _viewport, ColorF _clearColor) {
_rs.framebuffer(_handle);
_rs.viewport(0, 0, _viewport.x, _viewport.y);
if (_clearColor == ColorF() && _rs.defaultOpaqueClearColor()) {
_rs.clearDefaultOpaqueColor();
} else {
_rs.clearColor(_clearColor.r, _clearColor.g, _clearColor.b, _clearColor.a);
}
// Enable depth testing
_rs.depthMask(GL_TRUE);
// Setup raster state
_rs.culling(GL_TRUE);
_rs.cullFace(GL_BACK);
GL::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void FrameBuffer::bind(RenderState& _rs) const {
if (m_valid) {
_rs.framebuffer(m_glFrameBufferHandle);
}
}
GLuint FrameBuffer::readAt(float _normalizedX, float _normalizedY) const {
glm::vec2 position(_normalizedX * m_width, _normalizedY * m_height);
GLuint pixel;
GL::readPixels(floorf(position.x), floorf(position.y),
1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
return pixel;
}
FrameBuffer::PixelRect FrameBuffer::readRect(float _normalizedX, float _normalizedY, float _normalizedW, float _normalizedH) const {
PixelRect rect;
rect.left = fminf(fmaxf(floorf(_normalizedX * m_width), 0.f), m_width);
rect.bottom = fminf(fmaxf(floorf(_normalizedY * m_height), 0.f), m_height);
rect.width = fminf(fmaxf(ceilf(_normalizedW * m_width), 0.f), m_width - rect.left);
rect.height = fminf(fmaxf(ceilf(_normalizedH * m_height), 0.f), m_height - rect.bottom);
rect.pixels.resize(rect.width * rect.height);
GL::readPixels(rect.left, rect.bottom, rect.width, rect.height, GL_RGBA, GL_UNSIGNED_BYTE, rect.pixels.data());
return rect;
}
void FrameBuffer::init(RenderState& _rs) {
if (!Hardware::supportsGLRGBA8OES && m_colorRenderBuffer) {
LOGW("Driver doesn't support GL_OES_rgb8_rgba8");
LOGW("Falling back to color texture attachment");
m_colorRenderBuffer = false;
}
GL::genFramebuffers(1, &m_glFrameBufferHandle);
_rs.framebuffer(m_glFrameBufferHandle);
// Setup color render target
if (m_colorRenderBuffer) {
GL::genRenderbuffers(1, &m_glColorRenderBufferHandle);
GL::bindRenderbuffer(GL_RENDERBUFFER, m_glColorRenderBufferHandle);
GL::renderbufferStorage(GL_RENDERBUFFER, GL_RGBA8_OES,
m_width, m_height);
GL::framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_RENDERBUFFER, m_glColorRenderBufferHandle);
} else {
m_texture = std::make_unique<RenderTexture>(m_width, m_height);
m_texture->bind(_rs, 0);
GL::framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, m_texture->glHandle(), 0);
}
{
// Create depth render buffer
GL::genRenderbuffers(1, &m_glDepthRenderBufferHandle);
GL::bindRenderbuffer(GL_RENDERBUFFER, m_glDepthRenderBufferHandle);
GL::renderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16,
m_width, m_height);
GL::framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, m_glDepthRenderBufferHandle);
}
GLenum status = GL::checkFramebufferStatus(GL_FRAMEBUFFER);
GL_CHECK("");
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOGE("Framebuffer status is incomplete:");
switch (status) {
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
LOGE("\tGL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
LOGE("\tGL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
LOGE("\tGL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS");
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
LOGE("\tGL_FRAMEBUFFER_UNSUPPORTED");
break;
default:
LOGE("\tUnknown framebuffer issue");
break;
}
} else {
m_valid = true;
}
m_rs = &_rs;
}
FrameBuffer::~FrameBuffer() {
if (m_rs) {
m_rs->queueFramebufferDeletion(m_glFrameBufferHandle);
}
}
void FrameBuffer::drawDebug(RenderState& _rs, glm::vec2 _dim) {
if (m_texture) {
Primitives::drawTexture(_rs, *m_texture, glm::vec2{}, _dim);
}
}
}
|
/* Licensed to Oleg Tsemaylo under the MIT license.
* Refer to the LICENSE.txt file in the project root for more information.
*/
/**
* @file SumConstantsRuleTest.cpp
*
* Tests for SumConstantsRule class .
*
* @since 11.09.2017
* @author agor
*/
#include <gtest/gtest.h>
#include "SumConstantsRule.h"
#include <Constant.h>
#include <Sum.h>
#include <Variable.h>
#include <ExpressionFactory.h>
class FX_SumConstantsRuleTest : public testing::Test {
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(FX_SumConstantsRuleTest, visit_SumOfTwoConstants_Constant) {
SumConstantsRule rule(createSum(createConstant(2.0), createConstant(3.0)));
ASSERT_TRUE(rule.apply());
PExpression optExp=rule.getOptimizedExpression();
ASSERT_TRUE(isTypeOf<Constant>(optExp));
PConstant optExpTyped = SPointerCast<Constant>(optExp);
ASSERT_DOUBLE_EQ(5.0, optExpTyped->value);
}
TEST_F(FX_SumConstantsRuleTest, visit_OneArgumentIsNotConstants_False) {
SumConstantsRule rule(createSum(createVariable("x"), createConstant(3.0)));
ASSERT_FALSE(rule.apply());
PExpression optExp=rule.getOptimizedExpression();
// was it a sum?
ASSERT_TRUE(isTypeOf<Sum>(optExp));
// assuming that the sum is a right one, dont perform any tests
}
|
//thisislinecodeto#include<iostream>#include<vector>#include<memory>#include<string>constintsize_kkk=512;usingsize=unsignedlong;classSale_data{public:Sale_data()=default;std::stringISB;sizenumb;doubleprice;};intmain(intargc,char*argv[]){std::stringtext;std::stringtmp;while(std::cin>>tmp){text+=tmp;}std::cout<<text<<std::endl;for(auto&c:text){if(std::isalpha(c)){c='X';}}std::cout<<text<<std::endl;return0;}
//XXXXXXXXXXXXXXXX#XXXXXXX<XXXXXXXX>#XXXXXXX<XXXXXX>#XXXXXXX<XXXXXX>#XXXXXXX<XXXXXX>XXXXXXXXXXXX_XXX=512;XXXXXXXXX=XXXXXXXXXXXX;XXXXXXXXX_XXXX{XXXXXX:XXXX_XXXX()=XXXXXXX;XXX::XXXXXXXXX;XXXXXXXX;XXXXXXXXXXX;};XXXXXXX(XXXXXXX,XXXX*XXXX[]){XXX::XXXXXXXXXX;XXX::XXXXXXXXX;XXXXX(XXX::XXX>>XXX){XXXX+=XXX;}XXX::XXXX<<XXXX<<XXX::XXXX;XXX(XXXX&X:XXXX){XX(XXX::XXXXXXX(X)){X='X';}}XXX::XXXX<<XXXX<<XXX::XXXX;XXXXXX0;}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 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 "ConnectionPool.h"
#include "Basics/ReadLocker.h"
#include "Basics/WriteLocker.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "Logger/LogMacros.h"
#include "Network/NetworkFeature.h"
#include "Random/RandomGenerator.h"
#include "Metrics/CounterBuilder.h"
#include "Metrics/GaugeBuilder.h"
#include "Metrics/HistogramBuilder.h"
#include "Metrics/LogScale.h"
#include "Metrics/MetricsFeature.h"
#include <fuerte/connection.h>
DECLARE_GAUGE(arangodb_connection_pool_connections_current, uint64_t,
"Current number of connections in pool");
DECLARE_COUNTER(arangodb_connection_pool_leases_successful_total,
"Total number of successful connection leases");
DECLARE_COUNTER(arangodb_connection_pool_leases_failed_total,
"Total number of failed connection leases");
DECLARE_COUNTER(arangodb_connection_pool_connections_created_total,
"Total number of connections created");
struct LeaseTimeScale {
static arangodb::metrics::LogScale<float> scale() {
return {2.f, 0.f, 1000.f, 10};
}
};
DECLARE_HISTOGRAM(arangodb_connection_pool_lease_time_hist, LeaseTimeScale,
"Time to lease a connection from pool [ms]");
namespace arangodb {
namespace network {
using namespace arangodb::fuerte::v1;
ConnectionPool::ConnectionPool(ConnectionPool::Config const& config)
: _config(config),
_loop(config.numIOThreads, config.name),
_totalConnectionsInPool(_config.metricsFeature.add(
arangodb_connection_pool_connections_current{}.withLabel(
"pool", _config.name))),
_successSelect(_config.metricsFeature.add(
arangodb_connection_pool_leases_successful_total{}.withLabel(
"pool", config.name))),
_noSuccessSelect(_config.metricsFeature.add(
arangodb_connection_pool_leases_failed_total{}.withLabel(
"pool", config.name))),
_connectionsCreated(_config.metricsFeature.add(
arangodb_connection_pool_connections_created_total{}.withLabel(
"pool", config.name))),
_leaseHistMSec(_config.metricsFeature.add(
arangodb_connection_pool_lease_time_hist{}.withLabel("pool",
config.name))) {
TRI_ASSERT(config.numIOThreads > 0);
}
ConnectionPool::~ConnectionPool() { shutdownConnections(); }
/// @brief request a connection for a specific endpoint
/// note: it is the callers responsibility to ensure the endpoint
/// is always the same, we do not do any post-processing
network::ConnectionPtr ConnectionPool::leaseConnection(
std::string const& endpoint, bool& isFromPool) {
READ_LOCKER(guard, _lock);
auto it = _connections.find(endpoint);
if (it == _connections.end()) {
guard.unlock();
auto tmp = std::make_unique<Bucket>(); // get memory outside lock
WRITE_LOCKER(wguard, _lock);
auto [it2, emplaced] = _connections.try_emplace(endpoint, std::move(tmp));
return selectConnection(endpoint, *it2->second, isFromPool);
}
return selectConnection(endpoint, *it->second, isFromPool);
}
/// @brief drain all connections
void ConnectionPool::drainConnections() {
WRITE_LOCKER(guard, _lock);
for (auto& pair : _connections) {
Bucket& buck = *(pair.second);
std::lock_guard<std::mutex> lock(buck.mutex);
buck.list.clear();
}
_connections.clear();
}
/// @brief shutdown all connections
void ConnectionPool::shutdownConnections() {
WRITE_LOCKER(guard, _lock);
for (auto& pair : _connections) {
Bucket& buck = *(pair.second);
std::lock_guard<std::mutex> lock(buck.mutex);
for (std::shared_ptr<Context>& c : buck.list) {
c->fuerte->cancel();
}
}
}
/// remove unused and broken connections
void ConnectionPool::pruneConnections() {
const std::chrono::milliseconds ttl(_config.idleConnectionMilli);
READ_LOCKER(guard, _lock);
for (auto& pair : _connections) {
Bucket& buck = *(pair.second);
std::lock_guard<std::mutex> lock(buck.mutex);
// get under lock
auto now = std::chrono::steady_clock::now();
// this loop removes broken connections, and closes the ones we don't
// need anymore
size_t aliveCount = 0;
// make a single pass over the connections in this bucket
auto it = buck.list.begin();
while (it != buck.list.end()) {
bool remove = false;
if ((*it)->fuerte->state() == fuerte::Connection::State::Closed) {
// lets not keep around disconnected fuerte connection objects
remove = true;
} else if ((*it)->leases.load() == 0 &&
(*it)->fuerte->requestsLeft() == 0) {
if ((now - (*it)->lastLeased) > ttl ||
aliveCount >= _config.maxOpenConnections) {
// connection hasn't been used for a while, or there are too many
// connections
remove = true;
} // else keep the connection
}
if (remove) {
it = buck.list.erase(it);
_totalConnectionsInPool -= 1;
} else {
++aliveCount;
++it;
if (aliveCount == _config.maxOpenConnections && it != buck.list.end()) {
LOG_TOPIC("2d59a", DEBUG, Logger::COMMUNICATION)
<< "pruning extra connections to '" << pair.first << "' ("
<< buck.list.size() << ")";
}
}
}
}
}
/// @brief cancel connections to this endpoint
size_t ConnectionPool::cancelConnections(std::string const& endpoint) {
WRITE_LOCKER(guard, _lock);
auto const& it = _connections.find(endpoint);
if (it != _connections.end()) {
size_t n;
{
Bucket& buck = *(it->second);
std::lock_guard<std::mutex> lock(buck.mutex);
n = buck.list.size();
for (std::shared_ptr<Context>& c : buck.list) {
c->fuerte->cancel();
}
}
_connections.erase(it);
return n;
}
return 0;
}
/// @brief return the number of open connections
size_t ConnectionPool::numOpenConnections() const {
size_t conns = 0;
READ_LOCKER(guard, _lock);
for (auto& pair : _connections) {
Bucket& buck = *(pair.second);
std::lock_guard<std::mutex> lock(buck.mutex);
conns += buck.list.size();
}
return conns;
}
ConnectionPool::Context::Context(std::shared_ptr<fuerte::Connection> c,
std::chrono::steady_clock::time_point t,
std::size_t l)
: fuerte(std::move(c)), lastLeased(t), leases(l) {}
std::shared_ptr<fuerte::Connection> ConnectionPool::createConnection(
fuerte::ConnectionBuilder& builder) {
builder.useIdleTimeout(false);
builder.verifyHost(_config.verifyHosts);
builder.protocolType(_config.protocol); // always overwrite protocol
TRI_ASSERT(builder.socketType() != SocketType::Undefined);
AuthenticationFeature* af = AuthenticationFeature::instance();
if (af != nullptr && af->isActive()) {
std::string const& token = af->tokenCache().jwtToken();
if (!token.empty()) {
builder.jwtToken(token);
builder.authenticationType(fuerte::AuthenticationType::Jwt);
}
}
// builder.onFailure([this](fuerte::Error error,
// const std::string& errorMessage) {
// });
return builder.connect(_loop);
}
ConnectionPtr ConnectionPool::selectConnection(std::string const& endpoint,
ConnectionPool::Bucket& bucket,
bool& isFromPool) {
using namespace std::chrono;
milliseconds const ttl(_config.idleConnectionMilli);
auto start = steady_clock::now();
isFromPool = true; // Will revert for new collections
// exclusively lock the bucket
std::unique_lock<std::mutex> guard(bucket.mutex);
for (std::shared_ptr<Context>& c : bucket.list) {
if (c->fuerte->state() == fuerte::Connection::State::Closed ||
(start - c->lastLeased) > ttl) {
continue;
}
TRI_ASSERT(_config.protocol != fuerte::ProtocolType::Undefined);
std::size_t limit = 0;
switch (_config.protocol) {
case fuerte::ProtocolType::Vst:
case fuerte::ProtocolType::Http2:
limit = 4;
break;
default:
break; // keep default of 0
}
// first check against number of active users
std::size_t num = c->leases.load(std::memory_order_relaxed);
while (num <= limit) {
bool const leased = c->leases.compare_exchange_strong(
num, num + 1, std::memory_order_relaxed);
if (leased) {
// next check against the number of requests in flight
if (c->fuerte->requestsLeft() <= limit &&
c->fuerte->state() != fuerte::Connection::State::Closed) {
c->lastLeased = std::chrono::steady_clock::now();
++_successSelect;
_leaseHistMSec.count(
duration<float, std::micro>(c->lastLeased - start).count());
return {c};
} else { // too many requests,
c->leases.fetch_sub(1, std::memory_order_relaxed);
++_noSuccessSelect;
break;
}
}
}
}
++_connectionsCreated;
// no free connection found, so we add one
LOG_TOPIC("2d6ab", DEBUG, Logger::COMMUNICATION)
<< "creating connection to " << endpoint << " bucket size "
<< bucket.list.size();
fuerte::ConnectionBuilder builder;
builder.endpoint(endpoint); // picks the socket type
auto now = steady_clock::now();
auto c =
std::make_shared<Context>(createConnection(builder), now, 1 /* leases*/);
bucket.list.push_back(c);
guard.unlock();
// continue without the bucket lock
isFromPool = false;
_totalConnectionsInPool += 1;
_leaseHistMSec.count(duration<float, std::micro>(now - start).count());
return {std::move(c)};
}
ConnectionPool::Config const& ConnectionPool::config() const { return _config; }
ConnectionPtr::ConnectionPtr(std::shared_ptr<ConnectionPool::Context> ctx)
: _context{std::move(ctx)} {}
ConnectionPtr::ConnectionPtr(ConnectionPtr&& other) noexcept
: _context(std::move(other._context)) {}
ConnectionPtr::~ConnectionPtr() {
if (_context) {
_context->leases.fetch_sub(1, std::memory_order_relaxed);
}
}
fuerte::Connection& ConnectionPtr::operator*() const {
return *(_context->fuerte);
}
fuerte::Connection* ConnectionPtr::operator->() const {
return _context->fuerte.get();
}
fuerte::Connection* ConnectionPtr::get() const {
return _context->fuerte.get();
}
} // namespace network
} // namespace arangodb
|
#include "hello.h"
void hello_world(){}
|
/*===================================================================*/
/* */
/* spidma.cpp : SPI DMA function */
/* */
/* 2016/1/20 Racoon */
/* */
/*===================================================================*/
#include "mbed.h"
#include "stm32f4xx_hal.h"
SPI_HandleTypeDef SpiHandle;
HAL_StatusTypeDef st;
/*-------------------------------------------------------------------*/
/* callback */
/*-------------------------------------------------------------------*/
extern "C" {
void HAL_SPI_MspInit(__SPI_HandleTypeDef *hspi)
{
static DMA_HandleTypeDef hdma_tx;
GPIO_InitTypeDef GPIO_InitStruct;
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_SPI1_CLK_ENABLE();
__HAL_RCC_DMA2_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_6;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_7;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// TODo finihs with that ot support DMA
// hdma_tx.Instance = DMA2_Stream3;
// hdma_tx.Init.Channel = DMA_CHANNEL_3;
// hdma_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
// hdma_tx.Init.PeriphInc = DMA_PINC_DISABLE;
// hdma_tx.Init.MemInc = DMA_MINC_ENABLE;
// hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
// hdma_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
// hdma_tx.Init.Mode = DMA_NORMAL;
// hdma_tx.Init.Priority = DMA_PRIORITY_HIGH;
// hdma_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
// hdma_tx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
// hdma_tx.Init.MemBurst = DMA_MBURST_SINGLE;
// hdma_tx.Init.PeriphBurst = DMA_MBURST_SINGLE;
// st = HAL_DMA_Init(&hdma_tx);
// __HAL_LINKDMA(&SpiHandle, hdmatx, hdma_tx); // SpiHandle->hdmatx = hdma_tx
// HAL_NVIC_SetPriority(DMA2_Stream3_IRQn, 0, 1);
// HAL_NVIC_EnableIRQ(DMA2_Stream3_IRQn);
// debug("My HAL_SPI_MspInit st=%d\n", st);
}
void DMA2_Stream3_IRQHandler(void)
{
HAL_DMA_IRQHandler(SpiHandle.hdmatx);
}
} // extern "C"
/*-------------------------------------------------------------------*/
/* Write a byte data */
/*-------------------------------------------------------------------*/
void spi_write(uint8_t data)
{
HAL_SPI_Transmit(&SpiHandle, &data, 1, 100);
}
/*-------------------------------------------------------------------*/
/* Write a word data */
/*-------------------------------------------------------------------*/
void spi_writew(uint16_t data)
{
HAL_SPI_Transmit(&SpiHandle, (uint8_t *)&data, 2, 100);
}
/*-------------------------------------------------------------------*/
/* Write a byte data */
/*-------------------------------------------------------------------*/
void spi_write(uint8_t* pData, uint16_t size)
{
HAL_SPI_Transmit(&SpiHandle, pData, size, 100);
}
/*-------------------------------------------------------------------*/
/* Initialize SPI DMA */
/*-------------------------------------------------------------------*/
void spi_init()
{
SpiHandle.Instance = SPI1;
SpiHandle.Init.Mode = SPI_MODE_MASTER;
SpiHandle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
SpiHandle.Init.Direction = SPI_DIRECTION_2LINES;
SpiHandle.Init.CLKPhase = SPI_PHASE_1EDGE;
SpiHandle.Init.CLKPolarity = SPI_POLARITY_HIGH;
SpiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
SpiHandle.Init.CRCPolynomial = 7;
//!ToDo correct here to avoid manipulate with bytes when send 16 bit RGB value for the Pixel
SpiHandle.Init.DataSize = SPI_DATASIZE_8BIT;
// SpiHandle.Init.DataSize = SPI_DATASIZE_16BIT;
SpiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB;
SpiHandle.Init.NSS = SPI_NSS_SOFT;
SpiHandle.Init.TIMode = SPI_TIMODE_DISABLE;
if (HAL_SPI_Init(&SpiHandle) != HAL_OK)
{
while(1){
debug("Can't init HAL SPI\n");
ThisThread::sleep_for(3000ms);
}
}
else{
debug("HAL SPI initilised!\n");
}
}
|
/*
* @lc app=leetcode id=2029 lang=cpp
*
* [2029] Stone Game IX
*/
// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool stoneGameIX(vector<int>& stones) {
int f[3] = {0, 0, 0};
for(int& x : stones){
int i = x % 3;
f[i]++;
}
if(f[0] % 2 == 0){
return f[1] >= 1 && f[2] >= 1;
}
return abs(f[1] - f[2]) > 2;
}
};
// @lc code=end
|
#include <iostream>
#include "http/http_server.hpp"
using namespace shine;
using namespace shine::net;
using namespace http;
int main(){
proactor_engine engine;
shine::string addr = "0.0.0.0:8300";
bool rc = engine.add_acceptor("http_base_server", addr, [&engine](bool status, connection *conn)->bool{
if (status)
{
http::server_peer *conn_handle = new http::server_peer;
conn_handle->set_recv_timeout(15000);
conn_handle->register_url_handle("/", [](const http::request &request, http::response &response)->bool{
response.set_version(request.get_version());
response.set_status_code(200);
response.set_body("hello shineframe!");
return true;
});
conn_handle->register_url_handle("/api/hello", [](const http::request &request, http::response &response)->bool{
response.set_version(request.get_version());
response.set_status_code(200);
shine::string body = "hello api!\r\n\r\nparameters:\r\n";
for (auto pa : request.get_url_parameters())
{
body += pa.first + "=" + pa.second + "\r\n";
}
response.set_body(body);
return true;
});
conn_handle->run(conn);
}
return true;
});
if (rc)
{
std::cout << "bind " << addr << "success." << endl;
engine.run();
}
else
{
std::cout << "bind " << addr << "failed." << endl;
}
return 0;
}
|
// Original Code: Copyright (c) 2011-2014 The Bitcoin Core Developers
// Modified Code: Copyright (c) 2015 Gamecredits Foundation
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentserver.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "base58.h"
#include "ui_interface.h"
#include "wallet.h"
#include <cstdlib>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslError>
#include <QSslSocket>
#include <QStringList>
#include <QTextDocument>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
using namespace boost;
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("gamecredits:");
const char* BITCOIN_REQUEST_MIMETYPE = "application/gamecredits-paymentrequest";
const char* BITCOIN_PAYMENTACK_MIMETYPE = "application/gamecredits-paymentack";
const char* BITCOIN_PAYMENTACK_CONTENTTYPE = "application/gamecredits-payment";
X509_STORE* PaymentServer::certStore = NULL;
void PaymentServer::freeCertStore()
{
if (PaymentServer::certStore != NULL)
{
X509_STORE_free(PaymentServer::certStore);
PaymentServer::certStore = NULL;
}
}
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("GameCreditsQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(QString::fromStdString(GetDataDir(true).string()));
name.append(QString::number(qHash(ddir)));
return name;
}
//
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QList<QString> savedPaymentRequests;
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
qDebug() << "ReportInvalidCertificate : Payment server found an invalid certificate: " << cert.subjectInfo(QSslCertificate::CommonName);
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
if (PaymentServer::certStore == NULL)
atexit(PaymentServer::freeCertStore);
else
freeCertStore();
// Unit tests mostly use this, to pass in fake root CAs:
if (_store)
{
PaymentServer::certStore = _store;
return;
}
// Normal execution, use either -rootcertificates or system certs:
PaymentServer::certStore = X509_STORE_new();
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));
if (certFile.isEmpty())
return; // Empty store
QList<QSslCertificate> certList;
if (certFile != "-system-")
{
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::setDefaultCaCertificates(certList);
}
else
certList = QSslSocket::systemCaCertificates ();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
foreach (const QSslCertificate& cert, certList)
{
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
#if QT_VERSION >= 0x050000
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char *data = (const unsigned char *)certData.data();
X509* x509 = d2i_X509(0, &data, certData.size());
if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509))
{
// Note: X509_STORE_free will free the X509* objects when
// the PaymentServer is destroyed
++nRootCerts;
}
else
{
ReportInvalidCertificate(cert);
continue;
}
}
qDebug() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // gamecredits: URI
{
savedPaymentRequests.append(arg);
SendCoinsRecipient r;
if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty())
{
CBitcoinAddress address(r.address.toStdString());
SelectParams(CChainParams::MAIN);
if (!address.IsValid())
{
SelectParams(CChainParams::TESTNET);
}
}
}
else if (QFile::exists(arg)) // Filename
{
savedPaymentRequests.append(arg);
PaymentRequestPlus request;
if (readPaymentRequest(arg, request))
{
if (request.getDetails().network() == "main")
SelectParams(CChainParams::MAIN);
else
SelectParams(CChainParams::TESTNET);
}
}
else
{
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qDebug() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg;
}
}
return true;
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
foreach (const QString& r, savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
{
delete socket;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) :
QObject(parent),
saveURIs(true),
uriServer(0),
netManager(0),
optionsModel(0)
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click gamecredits: links
// other OSes: helpful when dealing with payment request files (in the future)
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer)
{
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "emit message()" here
QMessageBox::critical(0, tr("Payment request error"),
tr("Cannot start gamecredits: click-to-pay handler"));
}
else {
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));
}
}
}
PaymentServer::~PaymentServer()
{
google::protobuf::ShutdownProtobufLibrary();
}
//
// OSX-specific way of handling gamecredits: URIs and
// PaymentRequest mime types
//
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
// clicking on gamecredits: URIs creates FileOpen events on the Mac
if (event->type() == QEvent::FileOpen)
{
QFileOpenEvent *fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
if (netManager != NULL)
delete netManager;
// netManager is used to fetch paymentrequests given in gamecredits: URIs
netManager = new QNetworkAccessManager(this);
QNetworkProxy proxy;
// Query active proxy (fails if no SOCKS5 proxy)
if (optionsModel->getProxySettings(proxy)) {
if (proxy.type() == QNetworkProxy::Socks5Proxy) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager : Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
}
else
qDebug() << "PaymentServer::initNetManager : No active proxy server found.";
}
else
emit message(tr("Net manager warning"),
tr("Your active proxy doesn't support SOCKS5, which is required for payment requests via proxy."),
CClientUIInterface::MSG_WARNING);
connect(netManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(netRequestFinished(QNetworkReply*)));
connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)),
this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError> &)));
}
void PaymentServer::uiReady()
{
initNetManager();
saveURIs = false;
foreach (const QString& s, savedPaymentRequests)
{
handleURIOrFile(s);
}
savedPaymentRequests.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs)
{
savedPaymentRequests.append(s);
return;
}
if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // gamecredits: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
#else
QUrlQuery uri((QUrl(s)));
#endif
if (uri.hasQueryItem("r")) // payment request URI
{
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid())
{
qDebug() << "PaymentServer::handleURIOrFile : fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
}
else
{
qDebug() << "PaymentServer::handleURIOrFile : Invalid URL: " << fetchUrl;
emit message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
}
else // normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseBitcoinURI(s, &recipient))
emit receivedPaymentRequest(recipient);
else
emit message(tr("URI handling"),
tr("URI can not be parsed! This can be caused by an invalid GameCredits address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (readPaymentRequest(s, request) && processPaymentRequest(request, recipient))
emit receivedPaymentRequest(recipient);
else
emit message(tr("Payment request file handling"),
tr("Payment request file can not be read or processed! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
return;
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
bool PaymentServer::readPaymentRequest(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly))
{
qDebug() << "PaymentServer::readPaymentRequest : Failed to open " << filename;
return false;
}
if (f.size() > MAX_PAYMENT_REQUEST_SIZE)
{
qDebug() << "PaymentServer::readPaymentRequest : " << filename << " too large";
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(PaymentServer::certStore, recipient.authenticatedMerchant);
QList<std::pair<CScript, qint64> > sendingTos = request.getPayTo();
QStringList addresses;
foreach(const PAIRTYPE(CScript, qint64)& sendingTo, sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString()));
}
else if (!recipient.authenticatedMerchant.isEmpty()){
// Insecure payments to custom gamecredits addresses are not supported
// (there is no good way to tell the user where they are paying in a way
// they'd have a chance of understanding).
emit message(tr("Payment request error"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (txOut.IsDust(CTransaction::nMinRelayTxFee)) {
QString msg = tr("Requested payment amount of %1 is too small (considered dust).")
.arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second));
qDebug() << "PaymentServer::processPaymentRequest : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.authenticatedMerchant.isEmpty()) {
qDebug() << "PaymentServer::processPaymentRequest : Secure payment request from " << recipient.authenticatedMerchant;
}
else {
qDebug() << "PaymentServer::processPaymentRequest : Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, "PaymentRequest");
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BITCOIN_REQUEST_MIMETYPE);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, "PaymentACK");
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BITCOIN_PAYMENTACK_CONTENTTYPE);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BITCOIN_PAYMENTACK_MIMETYPE);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant);
std::string strAccount = account.toStdString();
set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);
if (!refundAddresses.empty()) {
CScript s; s.SetDestination(*refundAddresses.begin());
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
CPubKey newKey;
if (wallet->GetKeyFromPool(newKey)) {
LOCK(wallet->cs_wallet); // SetAddressBook
CKeyID keyID = newKey.GetID();
wallet->SetAddressBook(keyID, strAccount, "refund");
CScript s; s.SetDestination(keyID);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
// This should never happen, because sending coins should have just unlocked the wallet
// and refilled the keypool
qDebug() << "PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set";
}
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
}
else {
// This should never happen, either:
qDebug() << "PaymentServer::fetchPaymentACK : Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError)
{
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qDebug() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == "PaymentRequest")
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (request.parse(data) && processPaymentRequest(request, recipient))
{
emit receivedPaymentRequest(recipient);
}
else
{
qDebug() << "PaymentServer::netRequestFinished : Error processing payment request";
emit message(tr("Payment request error"),
tr("Payment request can not be parsed or processed!"),
CClientUIInterface::MSG_ERROR);
}
return;
}
else if (requestType == "PaymentACK")
{
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size()))
{
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qDebug() << "PaymentServer::netRequestFinished : " << msg;
emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
}
else
{
emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError> &errs)
{
Q_UNUSED(reply);
QString errString;
foreach (const QSslError& err, errs) {
qDebug() << "PaymentServer::reportSslErrors : " << err;
errString += err.errorString() + "\n";
}
emit message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't futher process or store the paymentACK message
emit message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
|
/*
* Copyright (c) 2018 https://www.thecoderscorner.com (Nutricherry LTD).
* This product is licensed under an Apache license, see the LICENSE file in the top-level directory.
*/
#include <PlatformDetermination.h>
#include <IoLogging.h>
#include "RuntimeMenuItem.h"
static uint16_t nextAvailableRandomId = RANDOM_ID_START;
const char ALLOWABLE_EDIT_CHARACTERS[] PROGMEM = " .,0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\"$%^&*()_-+=@';:#{/?\\|<>#{}~";
uint16_t nextRandomId() {
return nextAvailableRandomId++;
}
RuntimeMenuItem::RuntimeMenuItem(MenuType menuType, uint16_t id, RuntimeRenderingFn renderFn,
uint8_t itemPosition, uint8_t numberOfRows, MenuItem* next) : MenuItem(menuType, NULL, next, false) {
this->id = id;
this->noOfParts = numberOfRows;
this->renderFn = renderFn;
this->itemPosition = itemPosition;
}
ListRuntimeMenuItem::ListRuntimeMenuItem(uint16_t id, int numberOfRows, RuntimeRenderingFn renderFn, MenuItem* next)
: RuntimeMenuItem(MENUTYPE_RUNTIME_LIST, id, renderFn, 0xff, numberOfRows, next) {
activeItem = 0;
}
RuntimeMenuItem *ListRuntimeMenuItem::getChildItem(int pos) {
menuType = MENUTYPE_RUNTIME_LIST;
itemPosition = pos;
setActive((activeItem - 1) == pos);
return this;
}
RuntimeMenuItem *ListRuntimeMenuItem::asParent() {
menuType = MENUTYPE_RUNTIME_LIST;
itemPosition = LIST_PARENT_ITEM_POS;
return this;
}
RuntimeMenuItem *ListRuntimeMenuItem::asBackMenu() {
setActive(activeItem == 0);
menuType = MENUTYPE_BACK_VALUE;
itemPosition = LIST_PARENT_ITEM_POS;
return this;
}
void TextMenuItem::setTextValue(const char* text, bool silent) {
// skip if they are the same
if (strncmp(data, text, textLength()) == 0) return;
strncpy(data, text, textLength());
cleanUpArray();
setChanged(true);
setSendRemoteNeededAll();
if (!silent) triggerCallback();
}
void TextMenuItem::cleanUpArray() {
uint8_t len = 0;
uint8_t actualLen = textLength();
data[actualLen - 1] = 0;
while (len < actualLen && data[len] != 0) len++;
for (int i = len; i < actualLen; i++) {
data[i] = 0;
}
}
bool TextMenuItem::setCharValue(uint8_t location, char val) {
if (location >= (noOfParts - 1)) return false;
data[location] = val;
// always ensure zero terminated at last position.
cleanUpArray();
setChanged(true);
setSendRemoteNeededAll();
return true;
}
void wrapForEdit(int val, int idx, uint8_t row, char* buffer, int bufferSize, bool forTime = false) {
--row;
if (idx == row) appendChar(buffer, '[', bufferSize);
fastltoa(buffer, val, forTime ? 2 : 4, forTime ? '0' : NOT_PADDED, bufferSize);
if (idx == row) appendChar(buffer, ']', bufferSize);
}
int ipAddressRenderFn(RuntimeMenuItem* item, uint8_t row, RenderFnMode mode, char* buffer, int bufferSize) {
if (item->getMenuType() != MENUTYPE_IPADDRESS) return 0;
IpAddressMenuItem* ipItem = reinterpret_cast<IpAddressMenuItem*>(item);
switch (mode) {
case RENDERFN_VALUE: {
buffer[0] = 0;
uint8_t* data = ipItem->getIpAddress();
wrapForEdit(data[0], 0, row, buffer, bufferSize);
appendChar(buffer, '.', bufferSize);
wrapForEdit(data[1], 1, row, buffer, bufferSize);
appendChar(buffer, '.', bufferSize);
wrapForEdit(data[2], 2, row, buffer, bufferSize);
appendChar(buffer, '.', bufferSize);
wrapForEdit(data[3], 3, row, buffer, bufferSize);
return true;
}
case RENDERFN_SET_VALUE: {
ipItem->setIpPart(row - 1, (uint8_t)buffer[0]);
return true;
}
case RENDERFN_GETPART: {
uint8_t* data = ipItem->getIpAddress();
return (int)data[row - 1];
}
case RENDERFN_NAME: {
if (buffer) buffer[0] = 0;
return true;
}
case RENDERFN_GETRANGE: return 255;
default: return false;
}
}
int twelveHourTime(int hr) {
if(hr == 0 || hr == 12) return 12;
else if(hr < 12) return hr;
else return hr - 12;
}
int timeItemRenderFn(RuntimeMenuItem* item, uint8_t row, RenderFnMode mode, char* buffer, int bufferSize) {
if (item->getMenuType() != MENUTYPE_TIME) return 0;
auto* timeItem = reinterpret_cast<TimeFormattedMenuItem*>(item);
int idx = row - 1;
TimeStorage data = timeItem->getTime();
switch(mode) {
case RENDERFN_NAME: {
if (buffer) buffer[0] = 0;
return true;
}
case RENDERFN_VALUE: {
bool twelveHr = timeItem->getFormat() == EDITMODE_TIME_12H || timeItem->getFormat() == EDITMODE_TIME_12H_HHMM;
bool includeSeconds = timeItem->getFormat() != EDITMODE_TIME_24H_HHMM && timeItem->getFormat() != EDITMODE_TIME_12H_HHMM;
bool includeHundreds = timeItem->getFormat() == EDITMODE_TIME_HUNDREDS_24H || timeItem->getFormat() == EDITMODE_TIME_DURATION_HUNDREDS;
bool optionalHours = timeItem->getFormat() == EDITMODE_TIME_DURATION_HUNDREDS || timeItem->getFormat() == EDITMODE_TIME_DURATION_SECONDS;
buffer[0] = 0;
if(!optionalHours || data.hours != 0) {
int hr = twelveHr ? twelveHourTime(data.hours) : data.hours;
wrapForEdit(hr, 0, row, buffer, bufferSize, true);
appendChar(buffer, ':', bufferSize);
}
wrapForEdit(data.minutes, 1, row, buffer, bufferSize, true);
if(includeSeconds) {
appendChar(buffer, ':', bufferSize);
wrapForEdit(data.seconds, 2, row, buffer, bufferSize, true);
}
if(includeHundreds) {
appendChar(buffer, '.', bufferSize);
wrapForEdit(data.hundreds, 3, row, buffer, bufferSize, true);
}
else if(twelveHr) {
appendChar(buffer, (data.hours > 11) ? 'P' : 'A', bufferSize);
appendChar(buffer, 'M', bufferSize);
}
return true;
}
case RENDERFN_GETRANGE: {
if(idx == 0) return 23;
else if(idx == 1 || idx == 2) return 59;
else if(idx == 3) return 99;
else return true;
}
case RENDERFN_GETPART: {
if(idx == 0) return data.hours;
else if(idx==1) return data.minutes;
else if(idx==2) return data.seconds;
else return data.hundreds;
}
case RENDERFN_SET_VALUE: {
int idx = row - 1;
if(idx == 0) timeItem->getUnderlyingData()->hours = buffer[0];
else if(idx == 1) timeItem->getUnderlyingData()->minutes = buffer[0];
else if(idx == 2) timeItem->getUnderlyingData()->seconds = buffer[0];
else if(idx == 3) timeItem->getUnderlyingData()->hundreds = buffer[0];
return true;
}
default: return false;
}
}
char DateFormattedMenuItem::separator = '/';
DateFormattedMenuItem::DateFormatOption DateFormattedMenuItem::dateFormatMode = DateFormattedMenuItem::DD_MM_YYYY;
int daysForMonth(DateStorage& theDate) {
auto month = theDate.month;
auto year = theDate.year;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
else if (month == 2) {
bool isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
return isLeap ? 29 : 28;
}
else return 31;
}
int toNaturalDateIndex(int act) {
auto fmt = DateFormattedMenuItem::getDateFormatStyle();
if(fmt == DateFormattedMenuItem::DD_MM_YYYY) {
return act;
}
else if(fmt == DateFormattedMenuItem::MM_DD_YYYY) {
return act == 2 ? 2 : act == 1 ? 0 : 1;
}
else /* YYYY_MM_DD */ {
return act == 1 ? 1 : act == 2 ? 0 : 2;
}
}
int toNaturalDateField(DateStorage dateStorage, int act) {
auto fld = toNaturalDateIndex(act);
return fld == 0 ? dateStorage.day : fld == 1 ? dateStorage.month : dateStorage.year;
}
int dateItemRenderFn(RuntimeMenuItem* item, uint8_t row, RenderFnMode mode, char* buffer, int bufferSize) {
if (item->getMenuType() != MENUTYPE_DATE) return 0;
auto timeItem = reinterpret_cast<DateFormattedMenuItem*>(item);
auto idx = row - 1;
auto data = timeItem->getDate();
auto sep = DateFormattedMenuItem::getDateSeparator();
switch(mode) {
case RENDERFN_NAME: {
if (buffer) buffer[0] = 0;
return true;
}
case RENDERFN_VALUE: {
buffer[0] = 0;
wrapForEdit(toNaturalDateField(timeItem->getDate(), 0), 0, row, buffer, bufferSize, toNaturalDateIndex(0) != 2);
appendChar(buffer, sep, bufferSize);
wrapForEdit(toNaturalDateField(timeItem->getDate(), 1), 1, row, buffer, bufferSize, toNaturalDateIndex(1) != 2);
appendChar(buffer, sep, bufferSize);
wrapForEdit(toNaturalDateField(timeItem->getDate(), 2), 2, row, buffer, bufferSize, toNaturalDateIndex(2) != 2);
return true;
}
case RENDERFN_GETRANGE: {
if(idx == toNaturalDateIndex(0)) return daysForMonth(data);
else if(idx == toNaturalDateIndex(1)) return 12;
else if(idx == toNaturalDateIndex(2)) return 9999;
else return true;
}
case RENDERFN_GETPART: {
if(idx == toNaturalDateIndex(0)) return data.day;
else if(idx==toNaturalDateIndex(1)) return data.month;
else return data.year;
}
case RENDERFN_SET_VALUE: {
int idx = row - 1;
if(idx == toNaturalDateIndex(0)) timeItem->getUnderlyingData()->day = buffer[0];
else if(idx == toNaturalDateIndex(1)) timeItem->getUnderlyingData()->month = buffer[0];
else if(idx == toNaturalDateIndex(2)) timeItem->getUnderlyingData()->year = *((int*)buffer);
return true;
}
default: return false;
}
}
int backSubItemRenderFn(RuntimeMenuItem* item, uint8_t /*row*/, RenderFnMode mode, char* buffer, int bufferSize) {
switch (mode) {
case RENDERFN_NAME:
if(item->getMenuType() == MENUTYPE_SUB_VALUE && ((SubMenuItem*)item)->getNamePGMUnsafe()) {
const char* name = ((SubMenuItem*)item)->getNamePGMUnsafe();
safeProgCpy(buffer, name, bufferSize);
}
else {
buffer[0] = 0;
}
return true;
case RENDERFN_EEPROM_POS:
return -1;
case RENDERFN_VALUE:
buffer[0] = 0;
return true;
default: return false;
}
}
inline char charFromEditableSet(int i) {
const char* ptr = &ALLOWABLE_EDIT_CHARACTERS[i];
return pgm_read_byte_near(ptr);
}
int findPositionInEditorSet(char ch) {
if (ch == 0) return 0;
for (int i = 0; i < ALLOWABLE_CHARS_ENCODER_SIZE; i++) {
char pgmCmp = charFromEditableSet(i);
if (pgmCmp == ch) {
return i + 1;
}
}
return 0; // return zero terminator when not found
}
int textItemRenderFn(RuntimeMenuItem* item, uint8_t row, RenderFnMode mode, char* buffer, int bufferSize) {
if (item->getMenuType() != MENUTYPE_TEXT_VALUE) return 0;
auto txtItem = reinterpret_cast<TextMenuItem*>(item);
switch (mode) {
case RENDERFN_VALUE: {
buffer[0] = 0;
row--;
for (int i = 0; i < txtItem->textLength(); ++i) {
char txtVal = txtItem->getTextValue()[i];
if (i == row) {
appendChar(buffer, '[', bufferSize);
appendChar(buffer, txtVal, bufferSize);
appendChar(buffer, ']', bufferSize);
}
else if(txtVal != 0) {
appendChar(buffer, (txtItem->isPasswordField()) ? '*' : txtVal, bufferSize);
}
else {
appendChar(buffer, 0, bufferSize);
}
if (!txtVal) break;
}
return true;
}
case RENDERFN_GETRANGE: {
// we only enter more rows if there isn't a null terminator
// but position 0 is always allowed for editing.
int idx = row - 1;
return (idx > 1 && txtItem->getTextValue()[idx - 1] == 0) ? 0 : ALLOWABLE_CHARS_ENCODER_SIZE;
}
case RENDERFN_SET_VALUE: {
int idx = row - 1;
int offset = buffer[0];
if (offset == 0) {
txtItem->setCharValue(idx, 0);
return true;
}
return txtItem->setCharValue(idx, charFromEditableSet(offset - 1));
}
case RENDERFN_NAME: {
if (buffer) buffer[0] = 0;
return true;
}
case RENDERFN_GETPART: {
return findPositionInEditorSet(txtItem->getTextValue()[row - 1]);
}
default: return false;
}
}
TextMenuItem::TextMenuItem(RuntimeRenderingFn customRenderFn, uint16_t id, int size, MenuItem *next)
: EditableMultiPartMenuItem(MENUTYPE_TEXT_VALUE, id, size, customRenderFn, next) {
data = new char[size];
memset(data, 0, size);
passwordField = false;
}
void IpAddressMenuItem::setIpAddress(const char * ipData) {
memset(data, 0, sizeof(data));
char part[4];
uint8_t currPart = 0;
while (*ipData && currPart < 4) {
part[0] = 0;
while (*ipData && *ipData != '.') {
appendChar(part, *ipData, sizeof(part));
ipData++;
}
serdebugF3("IpPart", getId(), part);
setIpPart(currPart, atoi(part));
currPart++;
if(*ipData) ipData++;
}
}
void IpAddressMenuItem::setIpAddress(uint8_t p1, uint8_t p2, uint8_t p3, uint8_t p4) {
data[0] = p1;
data[1] = p2;
data[2] = p3;
data[3] = p4;
setChanged(true);
setSendRemoteNeededAll();
}
void IpAddressMenuItem::setIpPart(uint8_t part, uint8_t newVal) {
if (part > 3) return;
data[part] = newVal;
changeOccurred(false);
}
long parseIntUntilSeparator(const char* ptr, int& offset) {
char sz[10];
unsigned int pos = 0;
// skip any non numerics
while(ptr[offset] && (ptr[offset] < '0' || ptr[offset] > '9')) {
offset++;
}
// collect the numerics
while(pos < (sizeof(sz)-1) && ptr[offset] && ptr[offset] >= '0' && ptr[offset] <= '9') {
sz[pos++] = ptr[offset++];
}
sz[pos] = 0;
return atol(sz);
}
void TimeFormattedMenuItem::setTimeFromString(const char* ptr) {
int offset = 0;
data.hours = parseIntUntilSeparator(ptr, offset);
data.minutes = parseIntUntilSeparator(ptr, offset);
data.seconds = parseIntUntilSeparator(ptr, offset);
data.hundreds = parseIntUntilSeparator(ptr, offset);
}
TimeFormattedMenuItem::TimeFormattedMenuItem(RuntimeRenderingFn renderFn, uint16_t id, MultiEditWireType format, MenuItem *next)
: EditableMultiPartMenuItem(MENUTYPE_TIME, id, format == EDITMODE_TIME_HUNDREDS_24H ? 4 : 3, renderFn, next) {
setTime(TimeStorage(12, 0));
this->format = format;
}
void DateFormattedMenuItem::setDateFromString(const char *dateText) {
int offset = 0;
data.year = parseIntUntilSeparator(dateText, offset);
data.month = parseIntUntilSeparator(dateText, offset);
data.day = parseIntUntilSeparator(dateText, offset);
}
uint8_t EditableMultiPartMenuItem::beginMultiEdit() {
setEditing(true);
itemPosition = 0;
return noOfParts;
}
int EditableMultiPartMenuItem::changeEditBy(int amt) {
itemPosition += amt;
setChanged(true);
setSendRemoteNeededAll();
return renderFn(this, itemPosition, RENDERFN_GETRANGE, NULL, 0);
}
int EditableMultiPartMenuItem::previousPart() {
if (itemPosition <= 1) {
stopMultiEdit();
return 0;
}
return changeEditBy(-1);
}
int EditableMultiPartMenuItem::nextPart() {
if (itemPosition >= noOfParts) {
stopMultiEdit();
return 0;
}
return changeEditBy(1);
}
void EditableMultiPartMenuItem::stopMultiEdit() {
itemPosition = 0xff;
setEditing(false);
setChanged(true);
setSendRemoteNeededAll();
runCallback();
}
bool EditableMultiPartMenuItem::valueChanged(int newVal) {
uint8_t sz[2];
sz[0] = lowByte(newVal);
sz[1] = highByte(newVal);
bool valueUpdated = renderFn(this, itemPosition, RENDERFN_SET_VALUE, reinterpret_cast<char*>(sz), sizeof(sz));
// we only redraw if either the value has changed, or we are in edit mode, when we always need to draw it on change.
if(valueUpdated) changeOccurred(false);
return valueUpdated;
}
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ie_core.hpp"
#include <unordered_set>
#include <fstream>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <mutex>
#include <ngraph/opsets/opset.hpp>
#include "cpp/ie_cnn_net_reader.h"
#include "cpp/ie_plugin_cpp.hpp"
#include "cpp_interfaces/base/ie_plugin_base.hpp"
#include "details/ie_exception_conversion.hpp"
#include "details/ie_so_pointer.hpp"
#include "file_utils.h"
#include "ie_icore.hpp"
#include "ie_plugin.hpp"
#include "ie_plugin_config.hpp"
#include "ie_profiling.hpp"
#include "ie_util_internal.hpp"
#include "multi-device/multi_device_config.hpp"
#include "xml_parse_utils.h"
using namespace InferenceEngine::PluginConfigParams;
namespace InferenceEngine {
IE_SUPPRESS_DEPRECATED_START
namespace {
std::once_flag flag;
InferenceEngine::details::SharedObjectLoader::Ptr cnnReaderLoader;
InferenceEngine::details::SharedObjectLoader::Ptr createCnnReaderLoader() {
std::call_once(flag, [&] () {
FileUtils::FilePath libraryName = FileUtils::toFilePath(std::string("inference_engine_ir_readers") + std::string(IE_BUILD_POSTFIX));
FileUtils::FilePath irReadersLibraryPath = FileUtils::makeSharedLibraryName(getInferenceEngineLibraryPath(), libraryName);
if (!FileUtils::fileExist(irReadersLibraryPath)) {
THROW_IE_EXCEPTION << "Please, make sure that Inference Engine IR readers library "
<< FileUtils::fromFilePath(::FileUtils::makeSharedLibraryName({}, libraryName)) << " is in "
<< getIELibraryPath();
}
cnnReaderLoader = std::shared_ptr<InferenceEngine::details::SharedObjectLoader>(
new InferenceEngine::details::SharedObjectLoader(irReadersLibraryPath.c_str()));
});
return cnnReaderLoader;
}
IInferencePluginAPI* getInferencePluginAPIInterface(IInferencePlugin* iplugin) {
return dynamic_cast<IInferencePluginAPI*>(iplugin);
}
IInferencePluginAPI* getInferencePluginAPIInterface(InferenceEnginePluginPtr iplugin) {
return getInferencePluginAPIInterface(static_cast<IInferencePlugin*>(iplugin.operator->()));
}
IInferencePluginAPI* getInferencePluginAPIInterface(InferencePlugin plugin) {
return getInferencePluginAPIInterface(static_cast<InferenceEnginePluginPtr>(plugin));
}
template <typename T>
struct Parsed {
std::string _deviceName;
std::map<std::string, T> _config;
};
template <typename T = Parameter>
Parsed<T> parseDeviceNameIntoConfig(const std::string& deviceName, const std::map<std::string, T>& config = {}) {
auto config_ = config;
auto deviceName_ = deviceName;
if (deviceName_.find("HETERO:") == 0) {
deviceName_ = "HETERO";
config_["TARGET_FALLBACK"] = deviceName.substr(7);
} else if (deviceName_.find("MULTI:") == 0) {
deviceName_ = "MULTI";
config_[InferenceEngine::MultiDeviceConfigParams::KEY_MULTI_DEVICE_PRIORITIES] = deviceName.substr(6);
} else {
DeviceIDParser parser(deviceName_);
deviceName_ = parser.getDeviceName();
std::string deviceIDLocal = parser.getDeviceID();
if (!deviceIDLocal.empty()) {
config_[KEY_DEVICE_ID] = deviceIDLocal;
}
}
return {deviceName_, config_};
}
Parameter copyParameterValue(const Parameter & value) {
if (value.is<bool>()) {
return { value.as<bool>() };
} else if (value.is<int>()) {
return { value.as<int>() };
} else if (value.is<unsigned int>()) {
return { value.as<unsigned int>() };
} else if (value.is<float>()) {
return { value.as<float>() };
} else if (value.is<std::string>()) {
return { value.as<std::string>() };
} else if (value.is<std::vector<std::string> >()) {
return { value.as<std::vector<std::string> >() };
} else if (value.is<std::vector<int> >()) {
return { value.as<std::vector<int> >() };
} else if (value.is<std::vector<float> >()) {
return { value.as<std::vector<float> >() };
} else if (value.is<std::vector<unsigned int> >()) {
return { value.as<std::vector<unsigned int> >() };
} else if (value.is<std::tuple<unsigned int, unsigned int, unsigned int> >()) {
return { value.as<std::tuple<unsigned int, unsigned int, unsigned int> >() };
} else if (value.is<std::tuple<unsigned int, unsigned int> >()) {
return { value.as<std::tuple<unsigned int, unsigned int> >() };
}
return std::move(value);
}
} // namespace
CNNNetReaderPtr CreateCNNNetReaderPtr() noexcept {
auto loader = createCnnReaderLoader();
return CNNNetReaderPtr(loader);
}
IE_SUPPRESS_DEPRECATED_END
DeviceIDParser::DeviceIDParser(const std::string& deviceNameWithID) {
deviceName = deviceNameWithID;
auto pos = deviceName.find('.');
if (pos != std::string::npos) {
deviceName = deviceNameWithID.substr(0, pos);
deviceID = deviceNameWithID.substr(pos + 1, deviceNameWithID.size());
}
}
std::string DeviceIDParser::getDeviceID() const {
return deviceID;
}
std::string DeviceIDParser::getDeviceName() const {
return deviceName;
}
std::vector<std::string> DeviceIDParser::getHeteroDevices(std::string fallbackDevice) {
std::vector<std::string> deviceNames;
std::string cdevice;
char delimiter = ',';
size_t pos = 0;
while ((pos = fallbackDevice.find(delimiter)) != std::string::npos) {
deviceNames.push_back(fallbackDevice.substr(0, pos));
fallbackDevice.erase(0, pos + 1);
}
if (!fallbackDevice.empty()) deviceNames.push_back(fallbackDevice);
return deviceNames;
}
std::vector<std::string> DeviceIDParser::getMultiDevices(std::string devicesList) {
std::vector<std::string> deviceNames;
auto trim_request_info = [](std::string device_with_requests) {
auto opening_bracket = device_with_requests.find_first_of('(');
return device_with_requests.substr(0, opening_bracket);
};
std::string device;
char delimiter = ',';
size_t pos = 0;
// in addition to the list of devices, every device can have a #requests in the brackets e.g. "CPU(100)"
// we skip the #requests info here
while ((pos = devicesList.find(delimiter)) != std::string::npos) {
auto d = devicesList.substr(0, pos);
deviceNames.push_back(trim_request_info(d));
devicesList.erase(0, pos + 1);
}
if (!devicesList.empty()) deviceNames.push_back(trim_request_info(devicesList));
return deviceNames;
}
class Core::Impl : public ICore {
// Fields are ordered by deletion order
ITaskExecutor::Ptr _taskExecutor = nullptr;
IE_SUPPRESS_DEPRECATED_START
mutable std::map<std::string, InferencePlugin> plugins;
IE_SUPPRESS_DEPRECATED_END
struct PluginDescriptor {
FileUtils::FilePath libraryLocation;
std::map<std::string, std::string> defaultConfig;
std::vector<FileUtils::FilePath> listOfExtentions;
};
/**
* @brief Holds original blob in order to avoid situations
* when original blob is allocated on stack
*/
class WeightsHolderBlob : public TBlob<uint8_t> {
Blob::CPtr originBlob;
public:
explicit WeightsHolderBlob(const Blob::CPtr& weights) :
TBlob<uint8_t>(weights->getTensorDesc(),
weights->cbuffer().as<uint8_t*>()),
originBlob(weights) { }
};
std::unordered_set<std::string> opsetNames;
std::vector<IExtensionPtr> extensions;
std::map<std::string, PluginDescriptor> pluginRegistry;
mutable std::mutex pluginsMutex; // to lock parallel access to pluginRegistry and plugins
public:
Impl();
~Impl() override;
/**
* @brief Register plugins for devices which are located in .xml configuration file. The function supports UNICODE path
* @param xmlConfigFile An .xml configuraion with device / plugin information
*/
void RegisterPluginsInRegistry(const std::string& xmlConfigFile) {
std::lock_guard<std::mutex> lock(pluginsMutex);
auto parse_result = ParseXml(xmlConfigFile.c_str());
if (!parse_result.error_msg.empty()) {
THROW_IE_EXCEPTION << parse_result.error_msg;
}
pugi::xml_document& xmlDoc = *parse_result.xml;
using namespace XMLParseUtils;
pugi::xml_node ieNode = xmlDoc.document_element();
pugi::xml_node devicesNode = ieNode.child("plugins");
for (auto pluginNode = devicesNode.child("plugin"); !pluginNode.empty();
pluginNode = pluginNode.next_sibling("plugin")) {
std::string deviceName = GetStrAttr(pluginNode, "name");
FileUtils::FilePath pluginPath = FileUtils::toFilePath(GetStrAttr(pluginNode, "location").c_str());
if (deviceName.find('.') != std::string::npos) {
THROW_IE_EXCEPTION << "Device name must not contain dot '.' symbol";
}
// append IR library path for default IE plugins
{
FileUtils::FilePath absFilePath = FileUtils::makePath(getInferenceEngineLibraryPath(), pluginPath);
if (FileUtils::fileExist(absFilePath)) pluginPath = absFilePath;
}
// check properties
auto propertiesNode = pluginNode.child("properties");
std::map<std::string, std::string> config;
if (propertiesNode) {
for (auto propertyNode = propertiesNode.child("property"); !propertyNode.empty();
propertyNode = propertyNode.next_sibling("property")) {
std::string key = GetStrAttr(propertyNode, "key");
std::string value = GetStrAttr(propertyNode, "value");
config[key] = value;
}
}
// check extensions
auto extensionsNode = pluginNode.child("extensions");
std::vector<FileUtils::FilePath> listOfExtentions;
if (extensionsNode) {
for (auto extensionNode = extensionsNode.child("extension"); !extensionNode.empty();
extensionNode = extensionNode.next_sibling("extension")) {
FileUtils::FilePath extensionLocation = FileUtils::toFilePath(GetStrAttr(extensionNode, "location").c_str());
listOfExtentions.push_back(extensionLocation);
}
}
// fill value in plugin registry for later lazy initialization
{
PluginDescriptor desc = {pluginPath, config, listOfExtentions};
pluginRegistry[deviceName] = desc;
}
}
}
//
// ICore public API
//
/**
* @brief Returns global task executor
* @return Reference to task executor
*/
ITaskExecutor::Ptr GetTaskExecutor() const override {
return _taskExecutor;
}
CNNNetwork ReadNetwork(const std::string& modelPath, const std::string& binPath) const override {
IE_PROFILING_AUTO_SCOPE(Core::ReadNetwork)
IE_SUPPRESS_DEPRECATED_START
ResponseDesc desc;
CNNNetReaderPtr cnnReader(createCnnReaderLoader());
StatusCode rt = cnnReader->ReadNetwork(modelPath.c_str(), &desc);
if (rt != OK) THROW_IE_EXCEPTION << desc.msg;
if (cnnReader->getVersion(&desc) >= 10) {
std::lock_guard<std::mutex> lock(pluginsMutex);
cnnReader->addExtensions(GetExtensions());
}
std::string bPath = binPath;
if (bPath.empty()) {
bPath = modelPath;
auto pos = bPath.rfind('.');
if (pos != std::string::npos) bPath = bPath.substr(0, pos);
bPath += ".bin";
if (!FileUtils::fileExist(bPath)) bPath.clear();
}
if (!bPath.empty()) {
rt = cnnReader->ReadWeights(bPath.c_str(), &desc);
if (rt != OK) THROW_IE_EXCEPTION << desc.msg;
} else {
TBlob<uint8_t>::Ptr weights_ptr;
rt = cnnReader->SetWeights(weights_ptr, &desc);
if (rt != OK) THROW_IE_EXCEPTION << desc.msg;
}
IE_SUPPRESS_DEPRECATED_END
return CNNNetwork(cnnReader);
}
CNNNetwork ReadNetwork(const std::string& model, const Blob::CPtr& weights) const override {
IE_PROFILING_AUTO_SCOPE(Core::ReadNetwork)
IE_SUPPRESS_DEPRECATED_START
ResponseDesc desc;
CNNNetReaderPtr cnnReader(createCnnReaderLoader());
StatusCode rt = cnnReader->ReadNetwork(model.data(), model.length(), &desc);
if (rt != OK) THROW_IE_EXCEPTION << desc.msg;
if (cnnReader->getVersion(&desc) >= 10) {
std::lock_guard<std::mutex> lock(pluginsMutex);
cnnReader->addExtensions(GetExtensions());
}
TBlob<uint8_t>::Ptr weights_ptr;
if (weights) {
weights_ptr = std::make_shared<WeightsHolderBlob>(weights);
}
rt = cnnReader->SetWeights(weights_ptr, &desc);
if (rt != OK) THROW_IE_EXCEPTION << desc.msg;
IE_SUPPRESS_DEPRECATED_END
return CNNNetwork(cnnReader);
}
ExecutableNetwork LoadNetwork(const CNNNetwork& network, const std::string& deviceName,
const std::map<std::string, std::string>& config) override {
IE_PROFILING_AUTO_SCOPE(Core::LoadNetwork)
auto parsed = parseDeviceNameIntoConfig(deviceName, config);
IE_SUPPRESS_DEPRECATED_START
return GetCPPPluginByName(parsed._deviceName).LoadNetwork(network, parsed._config);
IE_SUPPRESS_DEPRECATED_END
}
IE_SUPPRESS_DEPRECATED_START
ExecutableNetwork ImportNetwork(std::istream& networkModel, const std::string& deviceName,
const std::map<std::string, std::string>& config) override {
auto parsed = parseDeviceNameIntoConfig(deviceName, config);
if (parsed._deviceName.empty()) {
ExportMagic magic = {};
auto currentPos = networkModel.tellg();
networkModel.read(magic.data(), magic.size());
auto exportedWithName = (exportMagic == magic);
if (exportedWithName) {
std::getline(networkModel, parsed._deviceName);
}
networkModel.seekg(currentPos, networkModel.beg);
}
auto cppPlugin = GetCPPPluginByName(parsed._deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << parsed._deviceName << " does not implement the ImportNetwork method";
}
return pluginAPIInterface->ImportNetwork(networkModel, parsed._config);
}
QueryNetworkResult QueryNetwork(const ICNNNetwork& network, const std::string& deviceName,
const std::map<std::string, std::string>& config) const override {
QueryNetworkResult res;
auto parsed = parseDeviceNameIntoConfig(deviceName, config);
IE_SUPPRESS_DEPRECATED_START
GetCPPPluginByName(parsed._deviceName).QueryNetwork(network, parsed._config, res);
IE_SUPPRESS_DEPRECATED_END
return res;
}
Parameter GetMetric(const std::string& deviceName, const std::string& name) const override {
// HETERO case
{
if (deviceName.find("HETERO:") == 0) {
THROW_IE_EXCEPTION
<< "You can get specific metrics with the GetMetric only for the HETERO itself (without devices). "
"To get individual devices's metrics call GetMetric for each device separately";
}
}
// MULTI case
{
if (deviceName.find("MULTI:") == 0) {
THROW_IE_EXCEPTION
<< "You can get specific metrics with the GetMetric only for the MULTI itself (without devices). "
"To get individual devices's metrics call GetMetric for each device separately";
}
}
auto parsed = parseDeviceNameIntoConfig(deviceName);
IE_SUPPRESS_DEPRECATED_START
InferencePlugin cppPlugin = GetCPPPluginByName(parsed._deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
IE_SUPPRESS_DEPRECATED_END
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << parsed._deviceName << " does not implement the GetMetric method";
}
// we need to return a copy of Parameter object which is created on Core side,
// not in InferenceEngine plugin side, which can be unloaded from Core in a parallel thread
// TODO: remove this WA after *-31417 is resolved
return copyParameterValue(pluginAPIInterface->GetMetric(name, parsed._config));
}
/**
* @deprecated
* @brief Returns reference to CPP plugin wrapper by a device name
* @param deviceName A name of device
* @return Reference to a CPP plugin wrapper
*/
InferencePlugin GetCPPPluginByName(const std::string& deviceName) const {
std::lock_guard<std::mutex> lock(pluginsMutex);
IE_SUPPRESS_DEPRECATED_START
auto it = pluginRegistry.find(deviceName);
if (it == pluginRegistry.end()) {
THROW_IE_EXCEPTION << "Device with \"" << deviceName << "\" name is not registered in the InferenceEngine";
}
// Plugin is in registry, but not created, let's create
if (plugins.find(deviceName) == plugins.end()) {
PluginDescriptor desc = it->second;
try {
InferenceEnginePluginPtr plugin(desc.libraryLocation);
IInferencePlugin* pplugin = static_cast<IInferencePlugin*>(plugin.operator->());
IInferencePluginAPI* iplugin_api_ptr = dynamic_cast<IInferencePluginAPI*>(pplugin);
if (iplugin_api_ptr != nullptr) {
iplugin_api_ptr->SetName(deviceName);
// Set Inference Engine class reference to plugins
ICore* mutableCore = const_cast<ICore*>(static_cast<const ICore*>(this));
iplugin_api_ptr->SetCore(mutableCore);
}
// Add registered extensions to new plugin
for (const auto& ext : extensions) {
plugin->AddExtension(ext, nullptr);
}
InferencePlugin cppPlugin(plugin);
// configuring
{
cppPlugin.SetConfig(desc.defaultConfig);
for (auto&& extensionLocation : desc.listOfExtentions) {
// TODO: fix once InferenceEngine::Extension can accept FileUtils::FilePath
// currently, extensions cannot be loaded using wide path
cppPlugin.AddExtension(make_so_pointer<IExtension>(FileUtils::fromFilePath(extensionLocation)));
}
}
plugins[deviceName] = cppPlugin;
} catch (const details::InferenceEngineException& ex) {
THROW_IE_EXCEPTION << "Failed to create plugin " << FileUtils::fromFilePath(desc.libraryLocation) << " for device " << deviceName
<< "\n"
<< "Please, check your environment\n"
<< ex.what() << "\n";
}
}
IE_SUPPRESS_DEPRECATED_END
return plugins[deviceName];
}
IE_SUPPRESS_DEPRECATED_END
/**
* @brief Unload plugin for specified device, but plugin meta-data is still in plugin registry
* @param deviceName A name of device
*/
void UnloadPluginByName(const std::string& deviceName) {
std::lock_guard<std::mutex> lock(pluginsMutex);
auto it = plugins.find(deviceName);
if (it == plugins.end()) {
THROW_IE_EXCEPTION << "Device with \"" << deviceName << "\" name is not registered in the InferenceEngine";
}
plugins.erase(deviceName);
}
/**
* @brief Registers plugin meta-data in registry for specified device
* @param deviceName A name of device
*/
void RegisterPluginByName(const std::string& pluginName, const std::string& deviceName) {
std::lock_guard<std::mutex> lock(pluginsMutex);
auto it = pluginRegistry.find(deviceName);
if (it != pluginRegistry.end()) {
THROW_IE_EXCEPTION << "Device with \"" << deviceName << "\" is already registered in the InferenceEngine";
}
if (deviceName.find('.') != std::string::npos) {
THROW_IE_EXCEPTION << "Device name must not contain dot '.' symbol";
}
// append IR library path for default IE plugins
FileUtils::FilePath pluginPath;
{
pluginPath = FileUtils::makeSharedLibraryName({}, FileUtils::toFilePath(pluginName.c_str()));
FileUtils::FilePath absFilePath = FileUtils::makePath(getInferenceEngineLibraryPath(), pluginPath);
if (FileUtils::fileExist(absFilePath)) pluginPath = absFilePath;
}
PluginDescriptor desc = {pluginPath, {}, {}};
pluginRegistry[deviceName] = desc;
}
/**
* @brief Porvides a list of plugin names in registry; physically such plugins may not be created
* @return A list of plugin names
*/
std::vector<std::string> GetListOfDevicesInRegistry() const {
std::lock_guard<std::mutex> lock(pluginsMutex);
std::vector<std::string> listOfDevices;
for (auto&& pluginDesc : pluginRegistry) {
listOfDevices.push_back(pluginDesc.first);
}
return listOfDevices;
}
/**
* @brief Sets config values for a plugin or set of plugins
* @param deviceName A device name to set config to
* If empty, config is set for all the plugins / plugin's meta-data
*/
void SetConfigForPlugins(const std::map<std::string, std::string>& config, const std::string& deviceName) {
std::lock_guard<std::mutex> lock(pluginsMutex);
// set config for plugins in registry
bool configIsSet = false;
for (auto& desc : pluginRegistry) {
if (deviceName.empty() || deviceName == desc.first) {
for (auto&& conf : config) {
desc.second.defaultConfig[conf.first] = conf.second;
}
configIsSet = true;
}
}
if (!configIsSet && !deviceName.empty()) {
THROW_IE_EXCEPTION << "Device with \"" << deviceName << "\" name is not registered in the InferenceEngine";
}
// set config for already created plugins
for (auto& plugin : plugins) {
if (deviceName.empty() || deviceName == plugin.first) {
IE_SUPPRESS_DEPRECATED_START
plugin.second.SetConfig(config);
IE_SUPPRESS_DEPRECATED_END
}
}
}
/**
* @brief Registers the extension in a Core object
* Such extensions can be used for both CNNNetwork readers and device plugins
*/
void AddExtension(const IExtensionPtr& extension) {
std::lock_guard<std::mutex> lock(pluginsMutex);
std::map<std::string, ngraph::OpSet> opsets = extension->getOpSets();
for (const auto& it : opsets) {
if (opsetNames.find(it.first) != opsetNames.end())
THROW_IE_EXCEPTION << "Cannot add opset with name: " << it.first << ". Opset with the same name already exists.";
opsetNames.insert(it.first);
}
// add extensions for already created plugins
for (auto& plugin : plugins) {
IE_SUPPRESS_DEPRECATED_START
try {
plugin.second.AddExtension(extension);
} catch (...) {}
IE_SUPPRESS_DEPRECATED_END
}
extensions.emplace_back(extension);
}
/**
* @brief Provides a list of extensions
* @return A list of registered extensions
*/
const std::vector<IExtensionPtr>& GetExtensions() const {
return extensions;
}
};
Core::Impl::Impl() {
opsetNames.insert("opset1");
opsetNames.insert("opset2");
opsetNames.insert("opset3");
}
Core::Impl::~Impl() {}
Core::Core(const std::string& xmlConfigFile) {
_impl = std::make_shared<Impl>();
std::string xmlConfigFile_ = xmlConfigFile;
if (xmlConfigFile_.empty()) {
// register plugins from default plugins.xml config
FileUtils::FilePath xmlConfigFileDefault = FileUtils::makePath(getInferenceEngineLibraryPath(), FileUtils::toFilePath("plugins.xml"));
xmlConfigFile_ = FileUtils::fromFilePath(xmlConfigFileDefault);
}
RegisterPlugins(xmlConfigFile_);
}
std::map<std::string, Version> Core::GetVersions(const std::string& deviceName) const {
std::map<std::string, Version> versions;
std::vector<std::string> deviceNames;
{
// for compatibility with samples / demo
if (deviceName.find("HETERO") == 0) {
auto pos = deviceName.find_first_of(":");
if (pos != std::string::npos) {
deviceNames = DeviceIDParser::getHeteroDevices(deviceName.substr(pos + 1));
}
deviceNames.push_back("HETERO");
} else if (deviceName.find("MULTI") == 0) {
auto pos = deviceName.find_first_of(":");
if (pos != std::string::npos) {
deviceNames = DeviceIDParser::getMultiDevices(deviceName.substr(pos + 1));
}
deviceNames.push_back("MULTI");
} else {
deviceNames.push_back(deviceName);
}
}
for (auto&& deviceName_ : deviceNames) {
DeviceIDParser parser(deviceName_);
std::string deviceNameLocal = parser.getDeviceName();
IE_SUPPRESS_DEPRECATED_START
InferenceEngine::InferencePlugin cppPlugin = _impl->GetCPPPluginByName(deviceNameLocal);
const Version * version = cppPlugin.GetVersion();
IE_SUPPRESS_DEPRECATED_END
versions[deviceNameLocal] = *version;
}
return versions;
}
IE_SUPPRESS_DEPRECATED_START
void Core::SetLogCallback(IErrorListener&) const {
}
IE_SUPPRESS_DEPRECATED_END
CNNNetwork Core::ReadNetwork(const std::string& modelPath, const std::string& binPath) const {
return _impl->ReadNetwork(modelPath, binPath);
}
CNNNetwork Core::ReadNetwork(const std::string& model, const Blob::CPtr& weights) const {
return _impl->ReadNetwork(model, weights);
}
ExecutableNetwork Core::LoadNetwork(const CNNNetwork& network, const std::string& deviceName,
const std::map<std::string, std::string>& config) {
return _impl->LoadNetwork(network, deviceName, config);
}
void Core::AddExtension(const IExtensionPtr& extension) {
_impl->AddExtension(extension);
}
ExecutableNetwork Core::LoadNetwork(const CNNNetwork& network, RemoteContext::Ptr context,
const std::map<std::string, std::string>& config) {
IE_PROFILING_AUTO_SCOPE(Core::LoadNetwork)
std::map<std::string, std::string> config_ = config;
if (context == nullptr) {
THROW_IE_EXCEPTION << "Remote context is null";
}
std::string deviceName_ = context->getDeviceName();
DeviceIDParser device(deviceName_);
std::string deviceName = device.getDeviceName();
IE_SUPPRESS_DEPRECATED_START
auto cppPlugin = _impl->GetCPPPluginByName(deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << deviceName << " does not implement the LoadNetwork method";
}
return pluginAPIInterface->LoadNetwork(network, config_, context);
IE_SUPPRESS_DEPRECATED_END
}
RemoteContext::Ptr Core::CreateContext(const std::string& deviceName_, const ParamMap& params) {
if (deviceName_.find("HETERO") == 0) {
THROW_IE_EXCEPTION << "HETERO device does not support remote contexts";
}
if (deviceName_.find("MULTI") == 0) {
THROW_IE_EXCEPTION << "MULTI device does not support remote contexts";
}
DeviceIDParser device(deviceName_);
std::string deviceName = device.getDeviceName();
IE_SUPPRESS_DEPRECATED_START
auto cppPlugin = _impl->GetCPPPluginByName(deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << deviceName << " does not implement the CreateContext method";
}
return pluginAPIInterface->CreateContext(params);
IE_SUPPRESS_DEPRECATED_END
}
RemoteContext::Ptr Core::GetDefaultContext(const std::string& deviceName_) {
if (deviceName_.find("HETERO") == 0) {
THROW_IE_EXCEPTION << "HETERO device does not support remote contexts";
}
if (deviceName_.find("MULTI") == 0) {
THROW_IE_EXCEPTION << "MULTI device does not support remote contexts";
}
DeviceIDParser device(deviceName_);
std::string deviceName = device.getDeviceName();
IE_SUPPRESS_DEPRECATED_START
auto cppPlugin = _impl->GetCPPPluginByName(deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << deviceName << " does not implement the CreateContext method";
}
return pluginAPIInterface->GetDefaultContext();
IE_SUPPRESS_DEPRECATED_END
}
void Core::AddExtension(IExtensionPtr extension, const std::string& deviceName_) {
if (deviceName_.find("HETERO") == 0) {
THROW_IE_EXCEPTION
<< "HETERO device does not support extensions. Please, set extensions directly to fallback devices";
}
if (deviceName_.find("MULTI") == 0) {
THROW_IE_EXCEPTION
<< "MULTI device does not support extensions. Please, set extensions directly to fallback devices";
}
_impl->AddExtension(extension);
}
ExecutableNetwork Core::ImportNetwork(const std::string& modelFileName, const std::string& deviceName,
const std::map<std::string, std::string>& config) {
if (deviceName.find("HETERO") == 0) {
THROW_IE_EXCEPTION << "HETERO device does not support ImportNetwork";
}
if (deviceName.find("MULTI") == 0) {
THROW_IE_EXCEPTION << "MULTI device does not support ImportNetwork";
}
auto parsed = parseDeviceNameIntoConfig(deviceName, config);
IE_SUPPRESS_DEPRECATED_START
return _impl->GetCPPPluginByName(parsed._deviceName).ImportNetwork(modelFileName, parsed._config);
IE_SUPPRESS_DEPRECATED_END
}
ExecutableNetwork Core::ImportNetwork(std::istream& networkModel, const std::string& deviceName,
const std::map<std::string, std::string>& config) {
return _impl->ImportNetwork(networkModel, deviceName, config);
}
ExecutableNetwork Core::ImportNetwork(std::istream& networkModel,
const RemoteContext::Ptr& context,
const std::map<std::string, std::string>& config) {
IE_PROFILING_AUTO_SCOPE(Core::ImportNetwork)
if (context == nullptr) {
THROW_IE_EXCEPTION << "Remote context is null";
}
std::string deviceName_ = context->getDeviceName();
DeviceIDParser device(deviceName_);
std::string deviceName = device.getDeviceName();
auto parsed = parseDeviceNameIntoConfig(deviceName, config);
IE_SUPPRESS_DEPRECATED_START
auto cppPlugin = _impl->GetCPPPluginByName(deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << deviceName << " does not implement the ImportNetwork method";
}
IE_SUPPRESS_DEPRECATED_END
return pluginAPIInterface->ImportNetwork(networkModel, context, parsed._config);
}
QueryNetworkResult Core::QueryNetwork(const ICNNNetwork& network, const std::string& deviceName,
const std::map<std::string, std::string>& config) const {
return _impl->QueryNetwork(network, deviceName, config);
}
void Core::SetConfig(const std::map<std::string, std::string>& config, const std::string& deviceName) {
// HETERO case
{
if (deviceName.find("HETERO:") == 0) {
THROW_IE_EXCEPTION << "SetConfig is supported only for HETERO itself (without devices). "
"You can configure the devices with SetConfig before creating the HETERO on top.";
}
}
// MULTI case
{
if (deviceName.find("MULTI:") == 0) {
THROW_IE_EXCEPTION << "SetConfig is supported only for MULTI itself (without devices). "
"You can configure the devices with SetConfig before creating the MULTI on top.";
}
}
if (deviceName.empty()) {
_impl->SetConfigForPlugins(config, std::string());
} else {
auto parsed = parseDeviceNameIntoConfig(deviceName, config);
_impl->SetConfigForPlugins(parsed._config, parsed._deviceName);
}
}
Parameter Core::GetConfig(const std::string& deviceName, const std::string& name) const {
// HETERO case
{
if (deviceName.find("HETERO:") == 0) {
THROW_IE_EXCEPTION
<< "You can only GetConfig of the HETERO itself (without devices). "
"GetConfig is also possible for the individual devices before creating the HETERO on top.";
}
}
// MULTI case
{
if (deviceName.find("MULTI:") == 0) {
THROW_IE_EXCEPTION
<< "You can only GetConfig of the MULTI itself (without devices). "
"GetConfig is also possible for the individual devices before creating the MULTI on top.";
}
}
auto parsed = parseDeviceNameIntoConfig(deviceName);
IE_SUPPRESS_DEPRECATED_START
auto cppPlugin = _impl->GetCPPPluginByName(parsed._deviceName);
auto pluginAPIInterface = getInferencePluginAPIInterface(cppPlugin);
IE_SUPPRESS_DEPRECATED_END
if (pluginAPIInterface == nullptr) {
THROW_IE_EXCEPTION << parsed._deviceName << " does not implement the GetConfig method";
}
// we need to return a copy of Parameter object which is created on Core side,
// not in InferenceEngine plugin side, which can be unloaded from Core in a parallel thread
// TODO: remove this WA after *-31417 is resolved
return copyParameterValue(pluginAPIInterface->GetConfig(name, parsed._config));
}
Parameter Core::GetMetric(const std::string& deviceName, const std::string& name) const {
return _impl->GetMetric(deviceName, name);
}
std::vector<std::string> Core::GetAvailableDevices() const {
std::vector<std::string> devices;
std::string propertyName = METRIC_KEY(AVAILABLE_DEVICES);
for (auto&& deviceName : _impl->GetListOfDevicesInRegistry()) {
std::vector<std::string> devicesIDs;
IE_SUPPRESS_DEPRECATED_START
try {
Parameter p = GetMetric(deviceName, propertyName);
devicesIDs = p.as<std::vector<std::string>>();
} catch (details::InferenceEngineException&) {
// plugin is not created by e.g. invalid env
} catch (const std::exception& ex) {
THROW_IE_EXCEPTION << "An exception is thrown while trying to create the " << deviceName
<< " device and call GetMetric: " << ex.what();
} catch (...) {
THROW_IE_EXCEPTION << "Unknown exception is thrown while trying to create the " << deviceName
<< " device and call GetMetric";
}
IE_SUPPRESS_DEPRECATED_END
if (devicesIDs.size() > 1) {
for (auto&& deviceID : devicesIDs) {
devices.push_back(deviceName + '.' + deviceID);
}
} else if (!devicesIDs.empty()) {
devices.push_back(deviceName);
}
}
return devices;
}
void Core::RegisterPlugin(const std::string& pluginName, const std::string& deviceName) {
_impl->RegisterPluginByName(pluginName, deviceName);
}
void Core::RegisterPlugins(const std::string& xmlConfigFile) {
_impl->RegisterPluginsInRegistry(xmlConfigFile);
}
void Core::UnregisterPlugin(const std::string& deviceName_) {
DeviceIDParser parser(deviceName_);
std::string deviceName = parser.getDeviceName();
_impl->UnloadPluginByName(deviceName);
}
} // namespace InferenceEngine
|
/*
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
*
* Author : Bruce Liang
* Website : https://github.com/ldcsaa
* Project : https://github.com/ldcsaa/HP-Socket
* Blog : http://www.cnblogs.com/ldcsaa
* Wiki : http://www.oschina.net/p/hp-socket
* QQ Group : 44636872, 75375912
*
* 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 "stdafx.h"
#include "Common/GeneralHelper.h"
#include "Common/SysHelper.h"
#include "SocketHelper.h"
#include <mstcpip.h>
#pragma comment(lib, "ws2_32")
#if !defined(stscanf_s)
#ifdef _UNICODE
#define stscanf_s swscanf_s
#else
#define stscanf_s sscanf_s
#endif
#endif
static const BYTE s_szUdpCloseNotify[] = {0xBE, 0xB6, 0x1F, 0xEB, 0xDA, 0x52, 0x46, 0xBA, 0x92, 0x33, 0x59, 0xDB, 0xBF, 0xE6, 0xC8, 0xE4};
static const int s_iUdpCloseNotifySize = ARRAY_SIZE(s_szUdpCloseNotify);
const hp_addr hp_addr::ANY_ADDR4(AF_INET, TRUE);
const hp_addr hp_addr::ANY_ADDR6(AF_INET6, TRUE);
///////////////////////////////////////////////////////////////////////////////////////////////////////
ADDRESS_FAMILY DetermineAddrFamily(LPCTSTR lpszAddress)
{
if (!lpszAddress || lpszAddress[0] == 0)
return AF_UNSPEC;
if(::StrChr(lpszAddress, IPV6_ADDR_SEPARATOR_CHAR))
return AF_INET6;
TCHAR c;
int arr[4];
if(stscanf_s(lpszAddress, _T("%d.%d.%d.%d%c"), &arr[0], &arr[1], &arr[2], &arr[3], &c, 1) != 4)
return AF_UNSPEC;
for(int i = 0; i < 4; i++)
{
if(arr[i] < 0 || arr[i] > 255)
return AF_UNSPEC;
}
return AF_INET;
}
BOOL GetInAddr(LPCTSTR lpszAddress, HP_ADDR& addr)
{
addr.family = DetermineAddrFamily(lpszAddress);
if (addr.family == AF_UNSPEC)
return FALSE;
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
return (::InetPton(addr.family, lpszAddress, addr.Addr()) == TRUE);
#else
HP_SOCKADDR sockAddr(addr.family);
if(!GetSockAddr(lpszAddress, 0, sockAddr))
return FALSE;
memcpy(addr.Addr(), sockAddr.SinAddr(), addr.AddrSize());
return TRUE;
#endif
}
BOOL GetSockAddr(LPCTSTR lpszAddress, USHORT usPort, HP_SOCKADDR& addr)
{
if(addr.family != AF_INET && addr.family != AF_INET6)
{
::WSASetLastError(WSAEADDRNOTAVAIL);
return FALSE;
}
int iSize = addr.AddrSize();
if(::WSAStringToAddress((LPTSTR)lpszAddress, addr.family, nullptr, addr.Addr(), &iSize) != NO_ERROR)
return FALSE;
if(usPort != 0)
addr.SetPort(usPort);
return TRUE;
}
BOOL IsIPAddress(LPCTSTR lpszAddress, EnIPAddrType* penType)
{
HP_ADDR addr;
BOOL isOK = GetInAddr(lpszAddress, addr);
if(isOK && penType)
*penType = addr.IsIPv4() ? IPT_IPV4 : IPT_IPV6;
return isOK;
}
BOOL GetIPAddress(LPCTSTR lpszHost, LPTSTR lpszIP, int& iIPLen, EnIPAddrType& enType)
{
HP_SOCKADDR addr;
if(!GetSockAddrByHostName(lpszHost, 0, addr))
return FALSE;
enType = addr.IsIPv4() ? IPT_IPV4 : IPT_IPV6;
USHORT usPort;
ADDRESS_FAMILY usFamily;
return sockaddr_IN_2_A(addr, usFamily, lpszIP, iIPLen, usPort);
}
BOOL GetSockAddrByHostName(LPCTSTR lpszHost, USHORT usPort, HP_SOCKADDR& addr)
{
addr.family = DetermineAddrFamily(lpszHost);
if(addr.family != AF_UNSPEC)
return GetSockAddr(lpszHost, usPort, addr);
return GetSockAddrByHostNameDirectly(lpszHost, usPort, addr);
}
BOOL GetSockAddrByHostNameDirectly(LPCTSTR lpszHost, USHORT usPort, HP_SOCKADDR& addr)
{
addr.ZeroAddr();
addrinfo* pInfo = nullptr;
addrinfo hints = {0};
hints.ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG);
hints.ai_family = addr.family;
int rs = ::getaddrinfo(CT2A(lpszHost), nullptr, &hints, &pInfo);
if(rs != NO_ERROR)
{
::WSASetLastError(rs);
return FALSE;
}
BOOL isOK = FALSE;
for(addrinfo* pCur = pInfo; pCur != nullptr; pCur = pCur->ai_next)
{
if(pCur->ai_family == AF_INET || pCur->ai_family == AF_INET6)
{
memcpy(addr.Addr(), pCur->ai_addr, pCur->ai_addrlen);
isOK = TRUE;
break;
}
}
::freeaddrinfo(pInfo);
if(isOK)
addr.SetPort(usPort);
else
::WSASetLastError(WSAHOST_NOT_FOUND);
return isOK;
}
BOOL EnumHostIPAddresses(LPCTSTR lpszHost, EnIPAddrType enType, LPTIPAddr** lpppIPAddr, int& iIPAddrCount)
{
*lpppIPAddr = nullptr;
iIPAddrCount = 0;
ADDRESS_FAMILY usFamily = (enType == IPT_ALL ?
AF_UNSPEC : (enType == IPT_IPV4 ?
AF_INET : (enType == IPT_IPV6 ?
AF_INET6 : 0xFF)));
if(usFamily == 0xFF)
{
::WSASetLastError(WSAEAFNOSUPPORT);
return FALSE;
}
vector<HP_PSOCKADDR> vt;
ADDRESS_FAMILY usFamily2 = DetermineAddrFamily(lpszHost);
if(usFamily2 != AF_UNSPEC)
{
if(usFamily != AF_UNSPEC && usFamily != usFamily2)
{
::WSASetLastError(WSAHOST_NOT_FOUND);
return FALSE;
}
HP_SOCKADDR addr(usFamily2);
if(!GetSockAddr(lpszHost, 0, addr))
return FALSE;
vt.emplace_back(&addr);
return RetrieveSockAddrIPAddresses(vt, lpppIPAddr, iIPAddrCount);
}
addrinfo* pInfo = nullptr;
addrinfo hints = {0};
hints.ai_flags = AI_ALL;
hints.ai_family = usFamily;
int rs = ::getaddrinfo(CT2A(lpszHost), nullptr, &hints, &pInfo);
if(rs != NO_ERROR)
{
::WSASetLastError(rs);
return FALSE;
}
for(addrinfo* pCur = pInfo; pCur != nullptr; pCur = pCur->ai_next)
{
if(pCur->ai_family == AF_INET || pCur->ai_family == AF_INET6)
vt.emplace_back((HP_PSOCKADDR)pCur->ai_addr);
}
BOOL isOK = RetrieveSockAddrIPAddresses(vt, lpppIPAddr, iIPAddrCount);
::freeaddrinfo(pInfo);
if(!isOK) ::WSASetLastError(WSAHOST_NOT_FOUND);
return isOK;
}
BOOL RetrieveSockAddrIPAddresses(const vector<HP_PSOCKADDR>& vt, LPTIPAddr** lpppIPAddr, int& iIPAddrCount)
{
iIPAddrCount = (int)vt.size();
if(iIPAddrCount == 0) return FALSE;
HP_PSOCKADDR pSockAddr;
ADDRESS_FAMILY usFamily;
USHORT usPort;
int iAddrLength;
LPTSTR lpszAddr;
LPTIPAddr lpItem;
(*lpppIPAddr) = new LPTIPAddr[iIPAddrCount + 1];
(*lpppIPAddr)[iIPAddrCount] = nullptr;
for(int i = 0; i < iIPAddrCount; i++)
{
pSockAddr = vt[i];
iAddrLength = HP_SOCKADDR::AddrMinStrLength(pSockAddr->family) + 6;
lpszAddr = new TCHAR[iAddrLength];
ENSURE(sockaddr_IN_2_A(*vt[i], usFamily, lpszAddr, iAddrLength, usPort));
lpItem = new TIPAddr;
lpItem->type = pSockAddr->IsIPv4() ? IPT_IPV4 : IPT_IPV6;
lpItem->address = lpszAddr;
(*lpppIPAddr)[i] = lpItem;
}
return TRUE;
}
BOOL FreeHostIPAddresses(LPTIPAddr* lppIPAddr)
{
if(!lppIPAddr) return FALSE;
LPTIPAddr p;
LPTIPAddr* lppCur = lppIPAddr;
while((p = *lppCur++) != nullptr)
{
delete[] p->address;
delete p;
}
delete[] lppIPAddr;
return TRUE;
}
BOOL sockaddr_IN_2_A(const HP_SOCKADDR& addr, ADDRESS_FAMILY& usFamily, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
BOOL isOK = FALSE;
usFamily = addr.family;
usPort = addr.Port();
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
if(::InetNtop(addr.family, addr.SinAddr(), lpszAddress, iAddressLen))
{
iAddressLen = lstrlen(lpszAddress) + 1;
isOK = TRUE;
}
else
{
if(::WSAGetLastError() == ERROR_INVALID_PARAMETER)
iAddressLen = HP_SOCKADDR::AddrMinStrLength(usFamily);
}
#else
if(::WSAAddressToString((LPSOCKADDR)addr.Addr(), addr.AddrSize(), nullptr, lpszAddress, (LPDWORD)&iAddressLen) == NO_ERROR)
{
LPTSTR lpszEnd = nullptr;
BOOL bIPv6 = addr.IsIPv6();
BOOL bHasPort = (addr.Port() != 0);
if(!bIPv6)
{
if(bHasPort)
lpszEnd = ::StrChr(lpszAddress, PORT_SEPARATOR_CHAR);
}
else
{
if(bHasPort)
{
static const TCHAR s_szBrk[] = {IPV6_ADDR_END_CHAR, IPV6_ZONE_INDEX_CHAR, 0};
ASSERT(lpszAddress[0] == IPV6_ADDR_BEGIN_CHAR);
lpszEnd = ::StrPBrk(lpszAddress, s_szBrk);
}
else
{
lpszEnd = ::StrChr(lpszAddress, IPV6_ZONE_INDEX_CHAR);
}
}
ASSERT(!bHasPort || lpszEnd);
if(lpszEnd)
{
lpszEnd[0] = 0;
iAddressLen = lpszEnd - lpszAddress;
}
if(bIPv6 && bHasPort)
memcpy(lpszAddress, (lpszAddress + 1), iAddressLen * sizeof(TCHAR));
else
++iAddressLen;
isOK = TRUE;
}
#endif
return isOK;
}
BOOL sockaddr_A_2_IN(LPCTSTR lpszAddress, USHORT usPort, HP_SOCKADDR& addr)
{
addr.family = DetermineAddrFamily(lpszAddress);
return GetSockAddr(lpszAddress, usPort, addr);
}
BOOL GetSocketAddress(SOCKET socket, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort, BOOL bLocal)
{
HP_SOCKADDR addr;
int addr_len = addr.AddrSize();
int result = bLocal ? getsockname(socket, addr.Addr(), &addr_len) : getpeername(socket, addr.Addr(), &addr_len);
if(result != NO_ERROR)
return FALSE;
ADDRESS_FAMILY usFamily;
return sockaddr_IN_2_A(addr, usFamily, lpszAddress, iAddressLen, usPort);
}
BOOL GetSocketLocalAddress(SOCKET socket, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
return GetSocketAddress(socket, lpszAddress, iAddressLen, usPort, TRUE);
}
BOOL GetSocketRemoteAddress(SOCKET socket, LPTSTR lpszAddress, int& iAddressLen, USHORT& usPort)
{
return GetSocketAddress(socket, lpszAddress, iAddressLen, usPort, FALSE);
}
ULONGLONG NToH64(ULONGLONG value)
{
return (((ULONGLONG)ntohl((u_long)((value << 32) >> 32))) << 32) | ntohl((u_long)(value >> 32));
}
ULONGLONG HToN64(ULONGLONG value)
{
return (((ULONGLONG)htonl((u_long)((value << 32) >> 32))) << 32) | htonl((u_long)(value >> 32));
}
BOOL IsLittleEndian()
{
static const USHORT _s_endian_test_value = 0x0102;
static const BOOL _s_bLE = (*((BYTE*)&_s_endian_test_value) == 0x02);
return _s_bLE;
}
USHORT HToLE16(USHORT value)
{
return IsLittleEndian() ? value : ENDIAN_SWAP_16(value);
}
USHORT HToBE16(USHORT value)
{
return IsLittleEndian() ? ENDIAN_SWAP_16(value) : value;
}
DWORD HToLE32(DWORD value)
{
return IsLittleEndian() ? value : ENDIAN_SWAP_32(value);
}
DWORD HToBE32(DWORD value)
{
return IsLittleEndian() ? ENDIAN_SWAP_32(value) : value;
}
PVOID GetExtensionFuncPtr(SOCKET sock, GUID guid)
{
DWORD dwBytes;
PVOID pfn = nullptr;
::WSAIoctl (
sock,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&guid,
sizeof(guid),
&pfn,
sizeof(pfn),
&dwBytes,
nullptr,
nullptr
);
return pfn;
}
LPFN_ACCEPTEX Get_AcceptEx_FuncPtr(SOCKET sock)
{
GUID guid = WSAID_ACCEPTEX;
return (LPFN_ACCEPTEX)GetExtensionFuncPtr(sock, guid);
}
LPFN_GETACCEPTEXSOCKADDRS Get_GetAcceptExSockaddrs_FuncPtr(SOCKET sock)
{
GUID guid = WSAID_GETACCEPTEXSOCKADDRS;
return (LPFN_GETACCEPTEXSOCKADDRS)GetExtensionFuncPtr(sock, guid);
}
LPFN_CONNECTEX Get_ConnectEx_FuncPtr(SOCKET sock)
{
GUID guid = WSAID_CONNECTEX;
return (LPFN_CONNECTEX)GetExtensionFuncPtr(sock, guid);
}
LPFN_TRANSMITFILE Get_TransmitFile_FuncPtr(SOCKET sock)
{
GUID guid = WSAID_TRANSMITFILE;
return (LPFN_TRANSMITFILE)GetExtensionFuncPtr(sock, guid);
}
LPFN_DISCONNECTEX Get_DisconnectEx_FuncPtr (SOCKET sock)
{
GUID guid = WSAID_DISCONNECTEX;
return (LPFN_DISCONNECTEX)GetExtensionFuncPtr(sock, guid);
}
HRESULT ReadSmallFile(LPCTSTR lpszFileName, CAtlFile& file, CAtlFileMapping<>& fmap, DWORD dwMaxFileSize)
{
ASSERT(lpszFileName != nullptr);
HRESULT hr = file.Create(lpszFileName, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING);
if(SUCCEEDED(hr))
{
ULONGLONG ullLen;
hr = file.GetSize(ullLen);
if(SUCCEEDED(hr))
{
if(ullLen > 0 && ullLen <= dwMaxFileSize)
hr = fmap.MapFile(file);
else if(ullLen == 0)
hr = HRESULT_FROM_WIN32(ERROR_FILE_INVALID);
else
hr = HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
}
}
return hr;
}
HRESULT MakeSmallFilePackage(LPCTSTR lpszFileName, CAtlFile& file, CAtlFileMapping<>& fmap, WSABUF szBuf[3], const LPWSABUF pHead, const LPWSABUF pTail)
{
DWORD dwMaxFileSize = MAX_SMALL_FILE_SIZE - (pHead ? pHead->len : 0) - (pTail ? pTail->len : 0);
ASSERT(dwMaxFileSize <= MAX_SMALL_FILE_SIZE);
HRESULT hr = ReadSmallFile(lpszFileName, file, fmap, dwMaxFileSize);
if(SUCCEEDED(hr))
{
szBuf[1].len = (ULONG)fmap.GetMappingSize();
szBuf[1].buf = fmap;
if(pHead) memcpy(&szBuf[0], pHead, sizeof(WSABUF));
else memset(&szBuf[0], 0, sizeof(WSABUF));
if(pTail) memcpy(&szBuf[2], pTail, sizeof(WSABUF));
else memset(&szBuf[2], 0, sizeof(WSABUF));
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL PostIocpCommand(HANDLE hIOCP, EnIocpCommand enCmd, ULONG_PTR ulParam)
{
return ::PostQueuedCompletionStatus(hIOCP, enCmd, ulParam, nullptr);
}
BOOL PostIocpExit(HANDLE hIOCP)
{
return PostIocpCommand(hIOCP, IOCP_CMD_EXIT, 0);
}
BOOL PostIocpAccept(HANDLE hIOCP)
{
return PostIocpCommand(hIOCP, IOCP_CMD_ACCEPT, 0);
}
BOOL PostIocpDisconnect(HANDLE hIOCP, CONNID dwConnID)
{
return PostIocpCommand(hIOCP, IOCP_CMD_DISCONNECT, dwConnID);
}
BOOL PostIocpSend(HANDLE hIOCP, CONNID dwConnID)
{
return PostIocpCommand(hIOCP, IOCP_CMD_SEND, dwConnID);
}
BOOL PostIocpUnpause(HANDLE hIOCP, CONNID dwConnID)
{
return PostIocpCommand(hIOCP, IOCP_CMD_UNPAUSE, dwConnID);
}
BOOL PostIocpTimeout(HANDLE hIOCP, CONNID dwConnID)
{
return PostIocpCommand(hIOCP, IOCP_CMD_TIMEOUT, dwConnID);
}
BOOL PostIocpClose(HANDLE hIOCP, CONNID dwConnID, int iErrorCode)
{
return PostIocpCommand(hIOCP, (EnIocpCommand)iErrorCode, dwConnID);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
int SSO_SetSocketOption(SOCKET sock, int level, int name, LPVOID val, int len)
{
return setsockopt(sock, level, name, (CHAR*)val, len);
}
int SSO_GetSocketOption(SOCKET sock, int level, int name, LPVOID val, int* len)
{
return getsockopt(sock, level, name, (CHAR*)val, len);
}
int SSO_IoctlSocket(SOCKET sock, long cmd, u_long* arg)
{
return ioctlsocket(sock, cmd, arg);
}
int SSO_WSAIoctl(SOCKET sock, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned)
{
return ::WSAIoctl(sock, dwIoControlCode, lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, nullptr, nullptr);
}
int SSO_UpdateAcceptContext(SOCKET soClient, SOCKET soBind)
{
return setsockopt(soClient, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (CHAR*)&soBind, sizeof(SOCKET));
}
int SSO_UpdateConnectContext(SOCKET soClient, int iOption)
{
return setsockopt(soClient, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, (CHAR*)&iOption, sizeof(int));
}
int SSO_NoBlock(SOCKET sock, BOOL bNoBlock)
{
return ioctlsocket(sock, FIONBIO, (ULONG*)&bNoBlock);
}
int SSO_NoDelay(SOCKET sock, BOOL bNoDelay)
{
return setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (CHAR*)&bNoDelay, sizeof(BOOL));
}
int SSO_DontLinger(SOCKET sock, BOOL bDont)
{
return setsockopt(sock, SOL_SOCKET, SO_DONTLINGER, (CHAR*)&bDont, sizeof(BOOL));
}
int SSO_Linger(SOCKET sock, USHORT l_onoff, USHORT l_linger)
{
linger ln = {l_onoff, l_linger};
return setsockopt(sock, SOL_SOCKET, SO_LINGER, (CHAR*)&ln, sizeof(linger));
}
int SSO_KeepAlive(SOCKET sock, BOOL bKeepAlive)
{
return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (CHAR*)&bKeepAlive, sizeof(BOOL));
}
int SSO_KeepAliveVals(SOCKET sock, u_long onoff, u_long time, u_long interval)
{
int result = NO_ERROR;
tcp_keepalive in = {onoff, time, interval};
DWORD dwBytes;
if(::WSAIoctl (
sock,
SIO_KEEPALIVE_VALS,
(LPVOID)&in,
sizeof(in),
nullptr,
0,
&dwBytes,
nullptr,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
if(result == WSAEWOULDBLOCK)
result = NO_ERROR;
}
return result;
}
int SSO_RecvBuffSize(SOCKET sock, int size)
{
return setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (CHAR*)&size, sizeof(int));
}
int SSO_SendBuffSize(SOCKET sock, int size)
{
return setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (CHAR*)&size, sizeof(int));
}
int SSO_RecvTimeOut(SOCKET sock, int ms)
{
return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (CHAR*)&ms, sizeof(int));
}
int SSO_SendTimeOut(SOCKET sock, int ms)
{
return setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (CHAR*)&ms, sizeof(int));
}
int SSO_ReuseAddress(SOCKET sock, EnReuseAddressPolicy opt)
{
BOOL bSet = TRUE;
BOOL bUnSet = FALSE;
int rs = NO_ERROR;
if(opt == RAP_NONE)
{
rs = setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (CHAR*)&bSet, sizeof(BOOL));
rs |= setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (CHAR*)&bUnSet, sizeof(BOOL));
}
else if(opt == RAP_ADDR_ONLY)
{
rs = setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (CHAR*)&bUnSet, sizeof(BOOL));
rs |= setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (CHAR*)&bUnSet, sizeof(BOOL));
}
else if(opt == RAP_ADDR_AND_PORT)
{
rs = setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (CHAR*)&bUnSet, sizeof(BOOL));
rs |= setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (CHAR*)&bSet, sizeof(BOOL));
}
else
{
::SetLastError(ERROR_INVALID_PARAMETER);
rs = -1;
}
return rs;
}
int SSO_ExclusiveAddressUse(SOCKET sock, BOOL bExclusive)
{
return setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (CHAR*)&bExclusive, sizeof(BOOL));
}
int SSO_UDP_ConnReset(SOCKET sock, BOOL bNewBehavior)
{
int result = NO_ERROR;
DWORD dwBytes;
if(::WSAIoctl (
sock,
SIO_UDP_CONNRESET,
(LPVOID)&bNewBehavior,
sizeof(bNewBehavior),
nullptr,
0,
&dwBytes,
nullptr,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
if(result == WSAEWOULDBLOCK)
result = NO_ERROR;
}
return result;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
CONNID GenerateConnectionID()
{
static volatile CONNID s_dwConnID = 0;
CONNID dwConnID = ::InterlockedIncrement(&s_dwConnID);
if(dwConnID == 0)
dwConnID = ::InterlockedIncrement(&s_dwConnID);
return dwConnID;
}
int IsUdpCloseNotify(const BYTE* pData, int iLength)
{
return (iLength == s_iUdpCloseNotifySize &&
memcmp(pData, s_szUdpCloseNotify, s_iUdpCloseNotifySize) == 0) ;
}
int SendUdpCloseNotify(SOCKET sock)
{
return send(sock, (LPCSTR)s_szUdpCloseNotify, s_iUdpCloseNotifySize, 0);
}
int SendUdpCloseNotify(SOCKET sock, const HP_SOCKADDR& remoteAddr)
{
return sendto(sock, (LPCSTR)s_szUdpCloseNotify, s_iUdpCloseNotifySize, 0, remoteAddr.Addr(), remoteAddr.AddrSize());
}
int ManualCloseSocket(SOCKET sock, int iShutdownFlag, BOOL bGraceful)
{
if(!bGraceful)
SSO_Linger(sock, 1, 0);
if(iShutdownFlag != 0xFF)
shutdown(sock, iShutdownFlag);
return closesocket(sock);
}
int PostAccept(LPFN_ACCEPTEX pfnAcceptEx, SOCKET soListen, SOCKET soClient, TBufferObj* pBufferObj, ADDRESS_FAMILY usFamily)
{
int result = PostAcceptNotCheck(pfnAcceptEx, soListen, soClient, pBufferObj, usFamily);
if(result == WSA_IO_PENDING)
result = NO_ERROR;
return result;
}
int PostAcceptNotCheck(LPFN_ACCEPTEX pfnAcceptEx, SOCKET soListen, SOCKET soClient, TBufferObj* pBufferObj, ADDRESS_FAMILY usFamily)
{
int result = NO_ERROR;
pBufferObj->client = soClient;
pBufferObj->operation = SO_ACCEPT;
int iAddrLen = HP_SOCKADDR::AddrSize(usFamily) + 16;
if(!pfnAcceptEx (
soListen,
pBufferObj->client,
pBufferObj->buff.buf,
0,
iAddrLen,
iAddrLen,
nullptr,
&pBufferObj->ov
)
)
{
result = ::WSAGetLastError();
}
return result;
}
int PostConnect(LPFN_CONNECTEX pfnConnectEx, SOCKET soClient, const HP_SOCKADDR& sockAddr, TBufferObj* pBufferObj)
{
int result = PostConnectNotCheck(pfnConnectEx, soClient, sockAddr, pBufferObj);
if(result == WSA_IO_PENDING)
result = NO_ERROR;
return result;
}
int PostConnectNotCheck(LPFN_CONNECTEX pfnConnectEx, SOCKET soClient, const HP_SOCKADDR& sockAddr, TBufferObj* pBufferObj)
{
int result = NO_ERROR;
pBufferObj->client = soClient;
pBufferObj->operation = SO_CONNECT;
if(!pfnConnectEx (
soClient,
sockAddr.Addr(),
sockAddr.AddrSize(),
nullptr,
0,
nullptr,
&pBufferObj->ov
)
)
{
result = ::WSAGetLastError();
}
return result;
}
int PostSend(TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
int result = PostSendNotCheck(pSocketObj, pBufferObj);
if(result == WSA_IO_PENDING)
result = NO_ERROR;
return result;
}
int PostSendNotCheck(TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
int result = NO_ERROR;
DWORD dwBytes = 0;
pBufferObj->client = pSocketObj->socket;
pBufferObj->operation = SO_SEND;
pBufferObj->ResetSendCounter();
pSocketObj->Increment();
if(::WSASend(
pBufferObj->client,
&pBufferObj->buff,
1,
&dwBytes,
0,
&pBufferObj->ov,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
if(result != WSA_IO_PENDING)
pSocketObj->Decrement();
}
return result;
}
int PostReceive(TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
int result = PostReceiveNotCheck(pSocketObj, pBufferObj);
if(result == WSA_IO_PENDING)
result = NO_ERROR;
return result;
}
int PostReceiveNotCheck(TSocketObj* pSocketObj, TBufferObj* pBufferObj)
{
int result = NO_ERROR;
DWORD dwFlag = 0;
DWORD dwBytes = 0;
pBufferObj->client = pSocketObj->socket;
pBufferObj->operation = SO_RECEIVE;
pSocketObj->Increment();
if(::WSARecv(
pBufferObj->client,
&pBufferObj->buff,
1,
&dwBytes,
&dwFlag,
&pBufferObj->ov,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
if(result != WSA_IO_PENDING)
pSocketObj->Decrement();
}
return result;
}
int PostSendTo(SOCKET sock, TUdpBufferObj* pBufferObj)
{
int result = PostSendToNotCheck(sock, pBufferObj);
if(result == WSA_IO_PENDING)
result = NO_ERROR;
return result;
}
int PostSendToNotCheck(SOCKET sock, TUdpBufferObj* pBufferObj)
{
int result = NO_ERROR;
DWORD dwBytes = 0;
pBufferObj->operation = SO_SEND;
pBufferObj->addrLen = pBufferObj->remoteAddr.AddrSize();
pBufferObj->ResetSendCounter();
if(::WSASendTo (
sock,
&pBufferObj->buff,
1,
&dwBytes,
0,
pBufferObj->remoteAddr.Addr(),
pBufferObj->addrLen,
&pBufferObj->ov,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
}
return result;
}
int PostReceiveFrom(SOCKET sock, TUdpBufferObj* pBufferObj)
{
int result = PostReceiveFromNotCheck(sock, pBufferObj);
if(result == WSA_IO_PENDING)
result = NO_ERROR;
return result;
}
int PostReceiveFromNotCheck(SOCKET sock, TUdpBufferObj* pBufferObj)
{
int result = NO_ERROR;
pBufferObj->operation = SO_RECEIVE;
pBufferObj->addrLen = pBufferObj->remoteAddr.AddrSize();
do
{
DWORD dwFlag = 0;
DWORD dwBytes = 0;
if(::WSARecvFrom(
sock,
&pBufferObj->buff,
1,
&dwBytes,
&dwFlag,
pBufferObj->remoteAddr.Addr(),
&pBufferObj->addrLen,
&pBufferObj->ov,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
}
if(!IS_UDP_RESET_ERROR(result))
break;
pBufferObj->ResetOV();
} while(TRUE);
return result;
}
int NoBlockReceive(TBufferObj* pBufferObj)
{
int result = NoBlockReceiveNotCheck(pBufferObj);
if(result == WSAEWOULDBLOCK)
result = NO_ERROR;
return result;
}
int NoBlockReceiveNotCheck(TBufferObj* pBufferObj)
{
int result = NO_ERROR;
DWORD dwFlag = 0;
DWORD dwBytes = 0;
if(::WSARecv(
pBufferObj->client,
&pBufferObj->buff,
1,
&dwBytes,
&dwFlag,
nullptr,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
}
else
{
if(dwBytes > 0)
pBufferObj->buff.len = dwBytes;
else
result = WSAEDISCON;
}
return result;
}
int NoBlockReceiveFrom(SOCKET sock, TUdpBufferObj* pBufferObj)
{
int result = NoBlockReceiveFromNotCheck(sock, pBufferObj);
if(result == WSAEWOULDBLOCK)
result = NO_ERROR;
return result;
}
int NoBlockReceiveFromNotCheck(SOCKET sock, TUdpBufferObj* pBufferObj)
{
int result = NO_ERROR;
pBufferObj->addrLen = pBufferObj->remoteAddr.AddrSize();
do
{
DWORD dwFlag = 0;
DWORD dwBytes = 0;
if(::WSARecvFrom(
sock,
&pBufferObj->buff,
1,
&dwBytes,
&dwFlag,
pBufferObj->remoteAddr.Addr(),
&pBufferObj->addrLen,
nullptr,
nullptr
) == SOCKET_ERROR)
{
result = ::WSAGetLastError();
}
else
{
if(dwBytes > 0)
pBufferObj->buff.len = dwBytes;
else
result = WSAEDISCON;
}
} while(IS_UDP_RESET_ERROR(result));
return result;
}
BOOL SetMultiCastSocketOptions(SOCKET sock, const HP_SOCKADDR& bindAddr, const HP_SOCKADDR& castAddr, int iMCTtl, BOOL bMCLoop)
{
if(castAddr.IsIPv4())
{
ENSURE(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_MULTICAST_TTL, &iMCTtl, sizeof(iMCTtl)) != SOCKET_ERROR);
ENSURE(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &bMCLoop, sizeof(bMCLoop)) != SOCKET_ERROR);
ip_mreq mcast;
::ZeroMemory(&mcast, sizeof(mcast));
mcast.imr_multiaddr = castAddr.addr4.sin_addr;
mcast.imr_interface = bindAddr.addr4.sin_addr;
if(::SSO_SetSocketOption(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast)) == SOCKET_ERROR)
return FALSE;
}
else
{
ENSURE(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &iMCTtl, sizeof(iMCTtl)) != SOCKET_ERROR);
ENSURE(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &bMCLoop, sizeof(bMCLoop)) != SOCKET_ERROR);
ipv6_mreq mcast;
::ZeroMemory(&mcast, sizeof(mcast));
mcast.ipv6mr_multiaddr = castAddr.addr6.sin6_addr;
mcast.ipv6mr_interface = bindAddr.addr6.sin6_scope_id;
if(::SSO_SetSocketOption(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mcast, sizeof(mcast)) == SOCKET_ERROR)
return FALSE;
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
LPCTSTR GetSocketErrorDesc(EnSocketError enCode)
{
switch(enCode)
{
case SE_OK: return _T("SUCCESS");
case SE_ILLEGAL_STATE: return _T("Illegal State");
case SE_INVALID_PARAM: return _T("Invalid Parameter");
case SE_SOCKET_CREATE: return _T("Create SOCKET Fail");
case SE_SOCKET_BIND: return _T("Bind SOCKET Fail");
case SE_SOCKET_PREPARE: return _T("Prepare SOCKET Fail");
case SE_SOCKET_LISTEN: return _T("Listen SOCKET Fail");
case SE_CP_CREATE: return _T("Create IOCP Fail");
case SE_WORKER_THREAD_CREATE: return _T("Create Worker Thread Fail");
case SE_DETECT_THREAD_CREATE: return _T("Create Detector Thread Fail");
case SE_SOCKE_ATTACH_TO_CP: return _T("Attach SOCKET to IOCP Fail");
case SE_CONNECT_SERVER: return _T("Connect to Server Fail");
case SE_NETWORK: return _T("Network Error");
case SE_DATA_PROC: return _T("Process Data Error");
case SE_DATA_SEND: return _T("Send Data Fail");
case SE_SSL_ENV_NOT_READY: return _T("SSL environment not ready");
default: ASSERT(FALSE); return _T("UNKNOWN ERROR");
}
}
BOOL CodePageToUnicode(int iCodePage, const char szSrc[], WCHAR szDest[], int& iDestLength)
{
ASSERT(szSrc);
int iSize = ::MultiByteToWideChar(iCodePage, 0, szSrc, -1, nullptr, 0);
if(iSize == 0 || iSize > iDestLength || !szDest || iDestLength == 0)
{
iDestLength = iSize;
return FALSE;
}
if(::MultiByteToWideChar(iCodePage, 0, szSrc, -1, szDest, iSize) != 0)
iDestLength = iSize;
else
iDestLength = 0;
return iDestLength != 0;
}
BOOL UnicodeToCodePage(int iCodePage, const WCHAR szSrc[], char szDest[], int& iDestLength)
{
ASSERT(szSrc);
int iSize = ::WideCharToMultiByte(iCodePage, 0, szSrc, -1, nullptr, 0, nullptr, nullptr);
if(iSize == 0 || iSize > iDestLength || !szDest || iDestLength == 0)
{
iDestLength = iSize;
return FALSE;
}
if(::WideCharToMultiByte(iCodePage, 0, szSrc, -1, szDest, iSize, nullptr, nullptr) != 0)
iDestLength = iSize;
else
iDestLength = 0;
return iDestLength != 0;
}
BOOL GbkToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength)
{
return CodePageToUnicode(CP_ACP, szSrc, szDest, iDestLength);
}
BOOL UnicodeToGbk(const WCHAR szSrc[], char szDest[], int& iDestLength)
{
return UnicodeToCodePage(CP_ACP, szSrc, szDest, iDestLength);
}
BOOL Utf8ToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength)
{
return CodePageToUnicode(CP_UTF8, szSrc, szDest, iDestLength);
}
BOOL UnicodeToUtf8(const WCHAR szSrc[], char szDest[], int& iDestLength)
{
return UnicodeToCodePage(CP_UTF8, szSrc, szDest, iDestLength);
}
BOOL GbkToUtf8(const char szSrc[], char szDest[], int& iDestLength)
{
int iMiddleLength = 0;
GbkToUnicode(szSrc, nullptr, iMiddleLength);
if(iMiddleLength == 0)
{
iDestLength = 0;
return FALSE;
}
unique_ptr<WCHAR[]> p(new WCHAR[iMiddleLength]);
ENSURE(GbkToUnicode(szSrc, p.get(), iMiddleLength));
return UnicodeToUtf8(p.get(), szDest, iDestLength);
}
BOOL Utf8ToGbk(const char szSrc[], char szDest[], int& iDestLength)
{
int iMiddleLength = 0;
Utf8ToUnicode(szSrc, nullptr, iMiddleLength);
if(iMiddleLength == 0)
{
iDestLength = 0;
return FALSE;
}
unique_ptr<WCHAR[]> p(new WCHAR[iMiddleLength]);
ENSURE(Utf8ToUnicode(szSrc, p.get(), iMiddleLength));
return UnicodeToGbk(p.get(), szDest, iDestLength);
}
DWORD GuessBase64EncodeBound(DWORD dwSrcLen)
{
return 4 * ((dwSrcLen + 2) / 3);
}
DWORD GuessBase64DecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
if(dwSrcLen < 2)
return 0;
if(lpszSrc[dwSrcLen - 2] == '=')
dwSrcLen -= 2;
else if(lpszSrc[dwSrcLen - 1] == '=')
--dwSrcLen;
DWORD dwMod = dwSrcLen % 4;
DWORD dwAdd = dwMod == 2 ? 1 : (dwMod == 3 ? 2 : 0);
return 3 * (dwSrcLen / 4) + dwAdd;
}
int Base64Encode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
static const BYTE CODES[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
DWORD dwRealLen = GuessBase64EncodeBound(dwSrcLen);
if(lpszDest == nullptr || dwDestLen < dwRealLen)
{
dwDestLen = dwRealLen;
return -5;
}
BYTE* p = lpszDest;
DWORD leven = 3 * (dwSrcLen / 3);
DWORD i = 0;
for (; i < leven; i += 3)
{
*p++ = CODES[lpszSrc[0] >> 2];
*p++ = CODES[((lpszSrc[0] & 3) << 4) + (lpszSrc[1] >> 4)];
*p++ = CODES[((lpszSrc[1] & 0xf) << 2) + (lpszSrc[2] >> 6)];
*p++ = CODES[lpszSrc[2] & 0x3f];
lpszSrc += 3;
}
if(i < dwSrcLen)
{
BYTE a = lpszSrc[0];
BYTE b = (i + 1 < dwSrcLen) ? lpszSrc[1] : 0;
*p++ = CODES[a >> 2];
*p++ = CODES[((a & 3) << 4) + (b >> 4)];
*p++ = (i + 1 < dwSrcLen) ? CODES[((b & 0xf) << 2)] : '=';
*p++ = '=';
}
ASSERT(dwRealLen == (DWORD)(p - lpszDest));
if(dwDestLen > dwRealLen)
{
*p = 0;
dwDestLen = dwRealLen;
}
return 0;
}
int Base64Decode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
static const BYTE MAP[256] =
{
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255,
255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255
};
DWORD dwRealLen = GuessBase64DecodeBound(lpszSrc, dwSrcLen);
if(lpszDest == nullptr || dwDestLen < dwRealLen)
{
dwDestLen = dwRealLen;
return -5;
}
BYTE c;
int g = 3;
DWORD i, x, y, z;
for(i = x = y = z = 0; i < dwSrcLen || x != 0;)
{
c = i < dwSrcLen ? MAP[lpszSrc[i++]] : 254;
if(c == 255) {dwDestLen = 0; return -3;}
else if(c == 254) {c = 0; g--;}
else if(c == 253) continue;
z = (z << 6) | c;
if(++x == 4)
{
lpszDest[y++] = (BYTE)((z >> 16) & 255);
if (g > 1) lpszDest[y++] = (BYTE)((z >> 8) & 255);
if (g > 2) lpszDest[y++] = (BYTE)(z & 255);
x = z = 0;
}
}
BOOL isOK = (y == dwRealLen);
if(!isOK)
dwDestLen = 0;
else
{
if(dwDestLen > dwRealLen)
{
lpszDest[dwRealLen] = 0;
dwDestLen = dwRealLen;
}
}
return isOK ? 0 : -3;
}
DWORD GuessUrlEncodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
DWORD dwAdd = 0;
for(DWORD i = 0; i < dwSrcLen; i++)
{
BYTE c = lpszSrc[i];
if(!(isalnum(c) || c == ' ' || c == '.' || c == '-' || c == '_' || c == '*'))
dwAdd += 2;
}
return dwSrcLen + dwAdd;
}
DWORD GuessUrlDecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
DWORD dwPercent = 0;
for(DWORD i = 0; i < dwSrcLen; i++)
{
if(lpszSrc[i] == '%')
{
++dwPercent;
i += 2;
}
}
DWORD dwSub = dwPercent * 2;
if(dwSrcLen < dwSub)
return 0;
return dwSrcLen - dwSub;
}
int UrlEncode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
if(lpszDest == nullptr || dwDestLen == 0)
goto ERROR_DEST_LEN;
BYTE c;
DWORD j = 0;
for(DWORD i = 0; i < dwSrcLen; i++)
{
if(j >= dwDestLen)
goto ERROR_DEST_LEN;
c = lpszSrc[i];
if (isalnum(c) || c == '.' || c == '-' || c == '_' || c == '*')
lpszDest[j++] = c;
else if(c == ' ')
lpszDest[j++] = '+';
else
{
if(j + 3 >= dwDestLen)
goto ERROR_DEST_LEN;
lpszDest[j++] = '%';
HEX_VALUE_TO_DOUBLE_CHAR(lpszDest + j, c);
j += 2;
}
}
if(dwDestLen > j)
{
lpszDest[j] = 0;
dwDestLen = j;
}
return 0;
ERROR_DEST_LEN:
dwDestLen = GuessUrlEncodeBound(lpszSrc, dwSrcLen);
return -5;
}
int UrlDecode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
if(lpszDest == nullptr || dwDestLen == 0)
goto ERROR_DEST_LEN;
char c;
DWORD j = 0;
for(DWORD i = 0; i < dwSrcLen; i++)
{
if(j >= dwDestLen)
goto ERROR_DEST_LEN;
c = lpszSrc[i];
if(c == '+')
lpszDest[j++] = ' ';
else if(c != '%')
lpszDest[j++] = c;
else
{
if(i + 2 >= dwSrcLen)
goto ERROR_SRC_DATA;
lpszDest[j++] = HEX_DOUBLE_CHAR_TO_VALUE(lpszSrc + i + 1);
i += 2;
}
}
if(dwDestLen > j)
{
lpszDest[j] = 0;
dwDestLen = j;
}
return 0;
ERROR_SRC_DATA:
dwDestLen = 0;
return -3;
ERROR_DEST_LEN:
dwDestLen = GuessUrlDecodeBound(lpszSrc, dwSrcLen);
return -5;
}
void DestroyCompressor(IHPCompressor* pCompressor)
{
delete pCompressor;
}
void DestroyDecompressor(IHPDecompressor* pDecompressor)
{
delete pDecompressor;
}
#ifdef _ZLIB_SUPPORT
CHPZlibCompressor::CHPZlibCompressor(Fn_CompressDataCallback fnCallback, int iWindowBits, int iLevel, int iMethod, int iMemLevel, int iStrategy)
: m_fnCallback (fnCallback)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
::ZeroObject(m_Stream);
m_bValid = (::deflateInit2(&m_Stream, iLevel, iMethod, iWindowBits, iMemLevel, iStrategy) == Z_OK);
}
CHPZlibCompressor::~CHPZlibCompressor()
{
if(m_bValid) ::deflateEnd(&m_Stream);
}
BOOL CHPZlibCompressor::Reset()
{
return (m_bValid = (::deflateReset(&m_Stream) == Z_OK));
}
BOOL CHPZlibCompressor::Process(const BYTE* pData, int iLength, BOOL bLast, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
BYTE szBuff[COMPRESS_BUFFER_SIZE];
m_Stream.next_in = (z_const Bytef*)pData;
m_Stream.avail_in = iLength;
int rs = Z_OK;
BOOL isOK = TRUE;
while(m_Stream.avail_in > 0)
{
do
{
m_Stream.next_out = szBuff;
m_Stream.avail_out = COMPRESS_BUFFER_SIZE;
rs = ::deflate(&m_Stream, bLast ? Z_FINISH : Z_NO_FLUSH);
if(rs == Z_STREAM_ERROR)
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto ZLIB_COMPRESS_END;
}
int iRead = (int)(COMPRESS_BUFFER_SIZE - m_Stream.avail_out);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff, iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto ZLIB_COMPRESS_END;
}
} while(m_Stream.avail_out == 0);
}
ZLIB_COMPRESS_END:
ASSERT(!isOK || (rs == Z_OK && !bLast) || (rs == Z_STREAM_END && bLast));
if(!isOK || bLast) Reset();
return isOK;
}
CHPZlibDecompressor::CHPZlibDecompressor(Fn_DecompressDataCallback fnCallback, int iWindowBits)
: m_fnCallback (fnCallback)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
::ZeroObject(m_Stream);
m_bValid = (::inflateInit2(&m_Stream, iWindowBits) == Z_OK);
}
CHPZlibDecompressor::~CHPZlibDecompressor()
{
if(m_bValid) ::inflateEnd(&m_Stream);
}
BOOL CHPZlibDecompressor::Reset()
{
return (m_bValid = (::inflateReset(&m_Stream) == Z_OK));
}
BOOL CHPZlibDecompressor::Process(const BYTE* pData, int iLength, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
BYTE szBuff[COMPRESS_BUFFER_SIZE];
m_Stream.next_in = (z_const Bytef*)pData;
m_Stream.avail_in = iLength;
int rs = Z_OK;
BOOL isOK = TRUE;
while(m_Stream.avail_in > 0)
{
do
{
m_Stream.next_out = szBuff;
m_Stream.avail_out = COMPRESS_BUFFER_SIZE;
rs = ::inflate(&m_Stream, Z_NO_FLUSH);
if(rs != Z_OK && rs != Z_STREAM_END)
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto ZLIB_DECOMPRESS_END;
}
int iRead = (int)(COMPRESS_BUFFER_SIZE - m_Stream.avail_out);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff, iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto ZLIB_DECOMPRESS_END;
}
} while(m_Stream.avail_out == 0);
if(rs == Z_STREAM_END)
break;
}
ZLIB_DECOMPRESS_END:
ASSERT(!isOK || rs == Z_OK || rs == Z_STREAM_END);
if(!isOK || rs == Z_STREAM_END) Reset();
return isOK;
}
IHPCompressor* CreateZLibCompressor(Fn_CompressDataCallback fnCallback, int iWindowBits, int iLevel, int iMethod, int iMemLevel, int iStrategy)
{
return new CHPZlibCompressor(fnCallback, iWindowBits, iLevel, iMethod, iMemLevel, iStrategy);
}
IHPCompressor* CreateGZipCompressor(Fn_CompressDataCallback fnCallback, int iLevel, int iMethod, int iMemLevel, int iStrategy)
{
return new CHPZlibCompressor(fnCallback, MAX_WBITS + 16, iLevel, iMethod, iMemLevel, iStrategy);
}
IHPDecompressor* CreateZLibDecompressor(Fn_DecompressDataCallback fnCallback, int iWindowBits)
{
return new CHPZlibDecompressor(fnCallback, iWindowBits);
}
IHPDecompressor* CreateGZipDecompressor(Fn_DecompressDataCallback fnCallback)
{
return new CHPZlibDecompressor(fnCallback, MAX_WBITS + 32);
}
int Compress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return CompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen);
}
int CompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iLevel, int iMethod, int iWindowBits, int iMemLevel, int iStrategy)
{
z_stream stream;
stream.next_in = (z_const Bytef*)lpszSrc;
stream.avail_in = dwSrcLen;
stream.next_out = lpszDest;
stream.avail_out = dwDestLen;
stream.zalloc = nullptr;
stream.zfree = nullptr;
stream.opaque = nullptr;
int err = ::deflateInit2(&stream, iLevel, iMethod, iWindowBits, iMemLevel, iStrategy);
if(err != Z_OK) return err;
err = ::deflate(&stream, Z_FINISH);
if(err != Z_STREAM_END)
{
::deflateEnd(&stream);
return err == Z_OK ? Z_BUF_ERROR : err;
}
if(dwDestLen > stream.total_out)
{
lpszDest[stream.total_out] = 0;
dwDestLen = stream.total_out;
}
return ::deflateEnd(&stream);
}
int Uncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return UncompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen);
}
int UncompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iWindowBits)
{
z_stream stream;
stream.next_in = (z_const Bytef*)lpszSrc;
stream.avail_in = dwSrcLen;
stream.next_out = lpszDest;
stream.avail_out = dwDestLen;
stream.zalloc = nullptr;
stream.zfree = nullptr;
int err = ::inflateInit2(&stream, iWindowBits);
if(err != Z_OK) return err;
err = ::inflate(&stream, Z_FINISH);
if(err != Z_STREAM_END)
{
::inflateEnd(&stream);
return (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) ? Z_DATA_ERROR : err;
}
if(dwDestLen > stream.total_out)
{
lpszDest[stream.total_out] = 0;
dwDestLen = stream.total_out;
}
return inflateEnd(&stream);
}
DWORD GuessCompressBound(DWORD dwSrcLen, BOOL bGZip)
{
DWORD dwBound = ::compressBound(dwSrcLen);
if(bGZip) dwBound += 16;
return dwBound;
}
int GZipCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return CompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16);
}
int GZipUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return UncompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, MAX_WBITS + 32);
}
DWORD GZipGuessUncompressBound(const BYTE* lpszSrc, DWORD dwSrcLen)
{
if(dwSrcLen < 20 || *(USHORT*)lpszSrc != 0x8B1F)
return 0;
return *(DWORD*)(lpszSrc + dwSrcLen - 4);
}
#endif
#ifdef _BROTLI_SUPPORT
CHPBrotliCompressor::CHPBrotliCompressor(Fn_CompressDataCallback fnCallback, int iQuality, int iWindow, int iMode)
: m_fnCallback (fnCallback)
, m_bValid (FALSE)
, m_iQuality (iQuality)
, m_iWindow (iWindow)
, m_iMode (iMode)
{
ASSERT(m_fnCallback != nullptr);
Reset();
}
CHPBrotliCompressor::~CHPBrotliCompressor()
{
if(m_bValid) ::BrotliEncoderDestroyInstance(m_pState);
}
BOOL CHPBrotliCompressor::Reset()
{
if(m_bValid) ::BrotliEncoderDestroyInstance(m_pState);
m_pState = ::BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
if(m_pState != nullptr)
{
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_QUALITY , (UINT)m_iQuality);
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_LGWIN , (UINT)m_iWindow);
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_MODE , (UINT)m_iMode);
if (m_iWindow > BROTLI_MAX_WINDOW_BITS)
::BrotliEncoderSetParameter(m_pState, BROTLI_PARAM_LARGE_WINDOW, BROTLI_TRUE);
}
return (m_bValid = (m_pState != nullptr));
}
BOOL CHPBrotliCompressor::Process(const BYTE* pData, int iLength, BOOL bLast, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
BYTE szBuff[COMPRESS_BUFFER_SIZE];
const BYTE* pNextInData = pData;
size_t iAvlInLen = (SIZE_T)iLength;
BYTE* pNextOutData = nullptr;
size_t iAvlOutLen = 0;
BOOL isOK = TRUE;
while(iAvlInLen > 0)
{
do
{
pNextOutData = szBuff;
iAvlOutLen = COMPRESS_BUFFER_SIZE;
if(!::BrotliEncoderCompressStream(m_pState, bLast ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS, &iAvlInLen, &pNextInData, &iAvlOutLen, &pNextOutData, nullptr))
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto BROTLI_COMPRESS_END;
}
int iRead = (int)(COMPRESS_BUFFER_SIZE - iAvlOutLen);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff, iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto BROTLI_COMPRESS_END;
}
} while (iAvlOutLen == 0);
}
BROTLI_COMPRESS_END:
if(!isOK || bLast) Reset();
return isOK;
}
CHPBrotliDecompressor::CHPBrotliDecompressor(Fn_DecompressDataCallback fnCallback)
: m_fnCallback (fnCallback)
, m_bValid (FALSE)
{
ASSERT(m_fnCallback != nullptr);
Reset();
}
CHPBrotliDecompressor::~CHPBrotliDecompressor()
{
if(m_bValid) ::BrotliDecoderDestroyInstance(m_pState);
}
BOOL CHPBrotliDecompressor::Reset()
{
if(m_bValid) ::BrotliDecoderDestroyInstance(m_pState);
m_pState = ::BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
return (m_bValid = (m_pState != nullptr));
}
BOOL CHPBrotliDecompressor::Process(const BYTE* pData, int iLength, PVOID pContext)
{
ASSERT(IsValid() && iLength > 0);
if(!IsValid())
{
::SetLastError(ERROR_INVALID_STATE);
return FALSE;
}
BYTE szBuff[COMPRESS_BUFFER_SIZE];
const BYTE* pNextInData = pData;
size_t iAvlInLen = (SIZE_T)iLength;
BYTE* pNextOutData = nullptr;
size_t iAvlOutLen = 0;
BOOL isOK = TRUE;
BrotliDecoderResult rs = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
do
{
do
{
pNextOutData = szBuff;
iAvlOutLen = COMPRESS_BUFFER_SIZE;
rs = ::BrotliDecoderDecompressStream(m_pState, &iAvlInLen, &pNextInData, &iAvlOutLen, &pNextOutData, nullptr);
if(rs == BROTLI_DECODER_RESULT_ERROR)
{
::SetLastError(ERROR_INVALID_DATA);
isOK = FALSE;
goto BROTLI_DECOMPRESS_END;
}
int iRead = (int)(COMPRESS_BUFFER_SIZE - iAvlOutLen);
if(iRead == 0)
break;
if(!m_fnCallback(szBuff, iRead, pContext))
{
::SetLastError(ERROR_CANCELLED);
isOK = FALSE;
goto BROTLI_DECOMPRESS_END;
}
} while (iAvlOutLen == 0);
if(rs == BROTLI_DECODER_RESULT_SUCCESS)
break;;
} while(rs == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT);
BROTLI_DECOMPRESS_END:
if(!isOK || rs == BROTLI_DECODER_RESULT_SUCCESS) Reset();
return isOK;
}
IHPCompressor* CreateBrotliCompressor(Fn_CompressDataCallback fnCallback, int iQuality, int iWindow, int iMode)
{
return new CHPBrotliCompressor(fnCallback, iQuality, iWindow, iMode);
}
IHPDecompressor* CreateBrotliDecompressor(Fn_DecompressDataCallback fnCallback)
{
return new CHPBrotliDecompressor(fnCallback);
}
int BrotliCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
return BrotliCompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, BROTLI_DEFAULT_QUALITY, BROTLI_DEFAULT_WINDOW, BROTLI_DEFAULT_MODE);
}
int BrotliCompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iQuality, int iWindow, int iMode)
{
size_t stDestLen = (size_t)dwDestLen;
int rs = ::BrotliEncoderCompress(iQuality, iWindow, (BrotliEncoderMode)iMode, (size_t)dwSrcLen, lpszSrc, &stDestLen, lpszDest);
dwDestLen = (DWORD)stDestLen;
return (rs == 1) ? 0 : ((rs == 3) ? -5 : -3);
}
int BrotliUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
{
size_t stDestLen = (size_t)dwDestLen;
BrotliDecoderResult rs = ::BrotliDecoderDecompress((size_t)dwSrcLen, lpszSrc, &stDestLen, lpszDest);
dwDestLen = (DWORD)stDestLen;
return (rs == BROTLI_DECODER_RESULT_SUCCESS) ? 0 : ((rs == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) ? -5 : -3);
}
DWORD BrotliGuessCompressBound(DWORD dwSrcLen)
{
return (DWORD)::BrotliEncoderMaxCompressedSize((size_t)dwSrcLen);
}
#endif
|
#include "DSARemoveBoneView.h"
#include "iqf_main.h"
#include <QFileDialog>
#include "mitkImageCast.h"
#include "ITKImageTypeDef.h"
#include "ITK_Helpers.h"
//qt
#include <QDebug>
#include "CVA/IQF_DSATool.h"
#include "cva/cva_command_def.h"
#include "qf_log.h"
DSARemoveBoneView::DSARemoveBoneView() :MitkPluginView()
{
}
DSARemoveBoneView::~DSARemoveBoneView()
{
}
WndHandle DSARemoveBoneView::GetPluginHandle()
{
return this;
}
void DSARemoveBoneView::CreateView()
{
m_ui.setupUi(this);
connect(m_ui.OpenBtn, &QPushButton::clicked, this, &DSARemoveBoneView::OpenDir);
connect(m_ui.SaveBtn, &QPushButton::clicked, this, &DSARemoveBoneView::SaveDir);
connect(m_ui.StartBtn, &QPushButton::clicked, this, &DSARemoveBoneView::StartCut);
connect(m_ui.MarkBtn, &QPushButton::clicked, this, &DSARemoveBoneView::Mark);
connect(m_ui.DeleteBtn, &QPushButton::clicked, this, &DSARemoveBoneView::DeleteMark);
connect(m_ui.ExportBtn, &QPushButton::clicked, this, &DSARemoveBoneView::Export);
m_pCut = new CutThread(m_pMain);
m_pCut->GetSubject()->Attach(this);
qRegisterMetaType<QFileInfoList>("QFileInfoList");
}
QFileInfoList GetDirList(QString path)
{
QDir dir(path);
QFileInfoList dir_list = dir.entryInfoList(QStringList()<<"*.DSA",QDir::Dirs);
QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs);
folder_list.removeFirst();
folder_list.removeFirst();
foreach (QFileInfo info,folder_list)
{
QString name = info.absoluteFilePath();
QFileInfoList child_dir_list = GetDirList(name);
dir_list.append(child_dir_list);
}
return dir_list;
}
void DSARemoveBoneView::Mark()
{
if (!QDir().exists(m_CurrentDSAFileName) || m_CurrentDSAFileName.isEmpty())
{
return;
}
if ((m_ui.MarkedDataList->findItems(m_CurrentDSAFileName, Qt::MatchExactly).size()!=0))
{
m_ui.LogTE->setHtml(m_ui.LogTE->toHtml()+QString("<font color=blue weight=bold size=4>%1 is already marked!</font>").arg(m_CurrentDSAFileName));
return;
}
QListWidgetItem* item = new QListWidgetItem(m_CurrentDSAFileName);
item->setFlags(item->flags() | Qt::ItemIsEditable);
item->setSelected(true);
m_ui.MarkedDataList->addItem(item);
}
void DSARemoveBoneView::DeleteMark()
{
m_ui.MarkedDataList->takeItem(m_ui.MarkedDataList->currentRow());
}
void DSARemoveBoneView :: Export()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log"),
"",
tr("log (*.txt)"));
QFile file(fileName);
if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
{
m_ui.LogTE->setHtml(m_ui.LogTE->toHtml() + QString("<font color=red weight=bold size=4>Open file %1 failed !</font>").arg(fileName));
return;
}
QTextStream out(&file);
for (int i=0;i<m_ui.MarkedDataList->count();i++)
{
out << m_ui.MarkedDataList->item(i)->text() << "\n";
}
file.close();
m_ui.LogTE->setHtml(m_ui.LogTE->toHtml() + QString("<font color=green weight=bold size=4>Save log file %1 successfully !</font>").arg(fileName));
}
void DSARemoveBoneView :: OpenDir()
{
QString defaultOpenFilePath = GetMitkReferenceInterface()->GetString("LastOpenDirectory");
QString dirName = QFileDialog::getExistingDirectory(NULL, "Open Dicom Dir",
defaultOpenFilePath,
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dirName.isEmpty())
return;
m_ui.OpenDirLE->setText(dirName);
GetMitkReferenceInterface()->SetString("LastOpenDirectory", dirName.toLocal8Bit().constData());
}
void DSARemoveBoneView::SaveDir()
{
QString defaultOpenFilePath = GetMitkReferenceInterface()->GetString("LastOpenDirectory");
QString dirName = QFileDialog::getExistingDirectory(NULL, "Open Dicom Dir",
defaultOpenFilePath,
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dirName.isEmpty())
return;
m_ui.SaveDirLE->setText(dirName);
}
void DSARemoveBoneView::StartCut()
{
if (m_ui.SaveDirLE->text().isEmpty()||m_ui.OpenDirLE->text().isEmpty())
{
QF_ERROR << "Please set the open directory and save directory!";
return;
}
m_ui.LogTE->clear();
m_ui.MarkedDataList->clear();
QFileInfoList list = GetDirList(m_ui.OpenDirLE->text());
if (list.size()==0)
{
m_ui.LogTE->setHtml(m_ui.LogTE->toHtml()+"<font color=blue weight=bold size=4>The subdirectores do not contain *.DSA directory !</font>");
return;
}
m_thread = new QThread;
m_pCut->moveToThread(m_thread);
disconnect(m_thread, &QThread::finished,
m_thread, &QThread::deleteLater);
disconnect(m_thread, &QThread::finished,
m_pCut, &QThread::deleteLater);
connect(m_thread, &QThread::finished,
m_thread, &QThread::deleteLater);
connect(m_thread, &QThread::finished,
m_pCut, &QThread::deleteLater);
GetDataStorage()->Remove(GetDataStorage()->GetSubset(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
if (!m_ObserveNode)
{
m_ObserveNode = mitk::DataNode::New();
m_ObserveNode->SetName("Observer");
GetDataStorage()->Add(m_ObserveNode);
}
connect(this, &DSARemoveBoneView::SignalStart, m_pCut, &CutThread::Start);
connect(m_pCut, &CutThread::SignalEnd, this, &DSARemoveBoneView::SlotEnd, Qt::BlockingQueuedConnection);
connect(m_pCut, &CutThread::SignalLog, this, &DSARemoveBoneView::SlotLog);
connect(m_pCut, &CutThread::SignalCurrentResult, this, &DSARemoveBoneView::SlotUpdateCurrentResult, Qt::BlockingQueuedConnection);
// setEnabled(false);
m_thread->start();
emit SignalStart(list, m_ui.OpenDirLE->text(), m_ui.SaveDirLE->text());
m_ui.StartBtn->setEnabled(false);
m_ui.StartBtn->setText("Cutting...");
}
void DSARemoveBoneView::SlotEnd()
{
m_ui.StartBtn->setEnabled(true);
m_ui.StartBtn->setText("Start");
disconnect(this, &DSARemoveBoneView::SignalStart, m_pCut, &CutThread::Start);
disconnect(m_pCut, &CutThread::SignalEnd, this, &DSARemoveBoneView::SlotEnd);
disconnect(m_pCut, &CutThread::SignalLog, this, &DSARemoveBoneView::SlotLog);
disconnect(m_pCut, &CutThread::SignalCurrentResult, this, &DSARemoveBoneView::SlotUpdateCurrentResult);
GetDataStorage()->Remove(m_ObserveNode);
m_ObserveNode = NULL;
RequestRenderWindowUpdate();
m_ui.LogTE->setHtml(m_ui.LogTE->toHtml()+"<font color=green weight=bold size=4>Finished !</font>");
}
void DSARemoveBoneView::SlotUpdateCurrentResult(Int2DImageType* img)
{
mitk::Image::Pointer mitkImage;
mitk::CastToMitkImage<Int2DImageType>(img, mitkImage);
m_ObserveNode->SetData(mitkImage);
m_ObserveNode->SetBoolProperty("binary", false);
m_ObserveNode->SetColor(1.0, 1.0, 1.0);
m_ObserveNode->SetOpacity(1.0);
mitk::LevelWindow lw(0, 1000);
m_ObserveNode->SetLevelWindow(lw);
GetMitkRenderWindowInterface()->Reinit(m_ObserveNode);
}
void DSARemoveBoneView::SlotLog(const QString& logStr, const QString& currentFileName)
{
m_ui.LogTE->setHtml(m_ui.LogTE->toHtml()+logStr);
m_CurrentDSAFileName = currentFileName;
}
void DSARemoveBoneView::Update(const char* szMessage, int iValue /* = 0 */, void* pValue /* = 0 */)
{
if (strcmp("Message_DSACut_Log", szMessage)==0)
{
}
}
|
/* ************************************************************************
* Copyright 2018-2021 Advanced Micro Devices, Inc.
* ************************************************************************ */
#pragma once
#include "bytes.hpp"
#include "cblas_interface.hpp"
#include "flops.hpp"
#include "norm.hpp"
#include "rocblas.hpp"
#include "rocblas_init.hpp"
#include "rocblas_math.hpp"
#include "rocblas_random.hpp"
#include "rocblas_test.hpp"
#include "rocblas_vector.hpp"
#include "unit.hpp"
#include "utility.hpp"
template <typename Ta, typename Tx = Ta, typename Tex = Tx>
void testing_scal_ex_bad_arg(const Arguments& arg)
{
auto rocblas_scal_ex_fn = arg.fortran ? rocblas_scal_ex_fortran : rocblas_scal_ex;
rocblas_datatype alpha_type = rocblas_datatype_f32_r;
rocblas_datatype x_type = rocblas_datatype_f32_r;
rocblas_datatype execution_type = rocblas_datatype_f32_r;
rocblas_int N = 100;
rocblas_int incx = 1;
Ta alpha = (Ta)0.6;
rocblas_local_handle handle{arg};
size_t size_x = N * size_t(incx);
// allocate memory on device
device_vector<Tx> dx(size_x);
CHECK_DEVICE_ALLOCATION(dx.memcheck());
EXPECT_ROCBLAS_STATUS(
(rocblas_scal_ex_fn(handle, N, &alpha, alpha_type, nullptr, x_type, incx, execution_type)),
rocblas_status_invalid_pointer);
EXPECT_ROCBLAS_STATUS(
(rocblas_scal_ex_fn(handle, N, nullptr, alpha_type, dx, x_type, incx, execution_type)),
rocblas_status_invalid_pointer);
EXPECT_ROCBLAS_STATUS(
(rocblas_scal_ex_fn(nullptr, N, &alpha, alpha_type, dx, x_type, incx, execution_type)),
rocblas_status_invalid_handle);
EXPECT_ROCBLAS_STATUS((rocblas_scal_ex_fn(handle,
N,
nullptr,
rocblas_datatype_f32_c,
nullptr,
rocblas_datatype_f64_r,
incx,
rocblas_datatype_f32_c)),
rocblas_status_not_implemented);
}
template <typename Ta, typename Tx = Ta, typename Tex = Tx>
void testing_scal_ex(const Arguments& arg)
{
auto rocblas_scal_ex_fn = arg.fortran ? rocblas_scal_ex_fortran : rocblas_scal_ex;
rocblas_datatype alpha_type = arg.a_type;
rocblas_datatype x_type = arg.b_type;
rocblas_datatype execution_type = arg.compute_type;
rocblas_int N = arg.N;
rocblas_int incx = arg.incx;
Ta h_alpha = arg.get_alpha<Ta>();
rocblas_local_handle handle{arg};
// argument sanity check before allocating invalid memory
if(N <= 0 || incx <= 0)
{
CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host));
CHECK_ROCBLAS_ERROR((rocblas_scal_ex_fn(
handle, N, nullptr, alpha_type, nullptr, x_type, incx, execution_type)));
return;
}
size_t size_x = N * size_t(incx);
// Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice
host_vector<Tx> hx_1(size_x);
host_vector<Tx> hx_2(size_x);
host_vector<Tx> hy_gold(size_x);
// Initial Data on CPU
rocblas_seedrand();
if(rocblas_isnan(arg.alpha))
rocblas_init_nan<Tx>(hx_1, 1, N, incx);
else
rocblas_init<Tx>(hx_1, 1, N, incx);
// copy vector is easy in STL; hy_gold = hx: save a copy in hy_gold which will be output of CPU
// BLAS
hx_2 = hx_1;
hy_gold = hx_1;
// allocate memory on device
device_vector<Tx> dx_1(size_x);
device_vector<Tx> dx_2(size_x);
device_vector<Ta> d_alpha(1);
CHECK_DEVICE_ALLOCATION(dx_1.memcheck());
CHECK_DEVICE_ALLOCATION(dx_2.memcheck());
CHECK_DEVICE_ALLOCATION(d_alpha.memcheck());
// copy data from CPU to device
CHECK_HIP_ERROR(hipMemcpy(dx_1, hx_1, sizeof(Tx) * size_x, hipMemcpyHostToDevice));
double gpu_time_used, cpu_time_used;
double rocblas_error_1 = 0.0;
double rocblas_error_2 = 0.0;
CHECK_HIP_ERROR(hipMemcpy(dx_1, hx_1, sizeof(Tx) * size_x, hipMemcpyHostToDevice));
if(arg.unit_check || arg.norm_check)
{
CHECK_HIP_ERROR(hipMemcpy(dx_2, hx_2, sizeof(Tx) * size_x, hipMemcpyHostToDevice));
CHECK_HIP_ERROR(hipMemcpy(d_alpha, &h_alpha, sizeof(Ta), hipMemcpyHostToDevice));
// GPU BLAS, rocblas_pointer_mode_host
CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host));
CHECK_ROCBLAS_ERROR((rocblas_scal_ex_fn(
handle, N, &h_alpha, alpha_type, dx_1, x_type, incx, execution_type)));
// GPU BLAS, rocblas_pointer_mode_device
CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device));
CHECK_ROCBLAS_ERROR((rocblas_scal_ex_fn(
handle, N, d_alpha, alpha_type, dx_2, x_type, incx, execution_type)));
// copy output from device to CPU
CHECK_HIP_ERROR(hipMemcpy(hx_1, dx_1, sizeof(Tx) * N * incx, hipMemcpyDeviceToHost));
CHECK_HIP_ERROR(hipMemcpy(hx_2, dx_2, sizeof(Tx) * N * incx, hipMemcpyDeviceToHost));
// CPU BLAS
cpu_time_used = get_time_us_no_sync();
cblas_scal(N, h_alpha, (Tx*)hy_gold, incx);
cpu_time_used = get_time_us_no_sync() - cpu_time_used;
if(arg.unit_check)
{
unit_check_general<Tx>(1, N, incx, hy_gold, hx_1);
unit_check_general<Tx>(1, N, incx, hy_gold, hx_2);
}
if(arg.norm_check)
{
rocblas_error_1 = norm_check_general<Tx>('F', 1, N, incx, hy_gold, hx_1);
rocblas_error_2 = norm_check_general<Tx>('F', 1, N, incx, hy_gold, hx_2);
}
} // end of if unit/norm check
if(arg.timing)
{
int number_cold_calls = arg.cold_iters;
int number_hot_calls = arg.iters;
CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host));
for(int iter = 0; iter < number_cold_calls; iter++)
{
rocblas_scal_ex_fn(handle, N, &h_alpha, alpha_type, dx_1, x_type, incx, execution_type);
}
hipStream_t stream;
CHECK_ROCBLAS_ERROR(rocblas_get_stream(handle, &stream));
gpu_time_used = get_time_us_sync(stream); // in microseconds
for(int iter = 0; iter < number_hot_calls; iter++)
{
rocblas_scal_ex_fn(handle, N, &h_alpha, alpha_type, dx_1, x_type, incx, execution_type);
}
gpu_time_used = get_time_us_sync(stream) - gpu_time_used;
ArgumentModel<e_N, e_alpha, e_incx>{}.log_args<Tx>(rocblas_cout,
arg,
gpu_time_used,
scal_gflop_count<Tx, Ta>(N),
scal_gbyte_count<Tx>(N),
cpu_time_used,
rocblas_error_1,
rocblas_error_2);
}
}
|
/// @ref gtc_type_aligned
/// @file glm/gtc/type_aligned.hpp
///
/// @see core (dependence)
///
/// @defgroup gtc_type_aligned GLM_GTC_type_aligned
/// @ingroup gtc
///
/// Include <glm/gtc/type_aligned.hpp> to use the features of this extension.
///
/// Aligned types allowing SIMD optimizations of vectors and matrices types
#pragma once
#if (GLM_CONFIG_ALIGNED_GENTYPES == GLM_DISABLE)
# error "GLM: Aligned gentypes require to enable C++ language extensions. Define GLM_FORCE_ALIGNED_GENTYPES before including GLM headers to use aligned types."
#endif
#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTC_type_aligned extension included")
#endif
#include "../mat4x4.hpp"
#include "../mat4x3.hpp"
#include "../mat4x2.hpp"
#include "../mat3x4.hpp"
#include "../mat3x3.hpp"
#include "../mat3x2.hpp"
#include "../mat2x4.hpp"
#include "../mat2x3.hpp"
#include "../mat2x2.hpp"
#include "../gtc/vec1.hpp"
#include "../vec2.hpp"
#include "../vec3.hpp"
#include "../vec4.hpp"
namespace glm
{
/// @addtogroup gtc_type_aligned
/// @{
// -- *vec1 --
/// 1 component vector aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<1, float, aligned_highp> aligned_highp_vec1;
/// 1 component vector aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<1, float, aligned_mediump> aligned_mediump_vec1;
/// 1 component vector aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<1, float, aligned_lowp> aligned_lowp_vec1;
/// 1 component vector aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<1, double, aligned_highp> aligned_highp_dvec1;
/// 1 component vector aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<1, double, aligned_mediump> aligned_mediump_dvec1;
/// 1 component vector aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<1, double, aligned_lowp> aligned_lowp_dvec1;
/// 1 component vector aligned in memory of signed integer numbers.
typedef vec<1, int, aligned_highp> aligned_highp_ivec1;
/// 1 component vector aligned in memory of signed integer numbers.
typedef vec<1, int, aligned_mediump> aligned_mediump_ivec1;
/// 1 component vector aligned in memory of signed integer numbers.
typedef vec<1, int, aligned_lowp> aligned_lowp_ivec1;
/// 1 component vector aligned in memory of unsigned integer numbers.
typedef vec<1, uint, aligned_highp> aligned_highp_uvec1;
/// 1 component vector aligned in memory of unsigned integer numbers.
typedef vec<1, uint, aligned_mediump> aligned_mediump_uvec1;
/// 1 component vector aligned in memory of unsigned integer numbers.
typedef vec<1, uint, aligned_lowp> aligned_lowp_uvec1;
/// 1 component vector aligned in memory of bool values.
typedef vec<1, bool, aligned_highp> aligned_highp_bvec1;
/// 1 component vector aligned in memory of bool values.
typedef vec<1, bool, aligned_mediump> aligned_mediump_bvec1;
/// 1 component vector aligned in memory of bool values.
typedef vec<1, bool, aligned_lowp> aligned_lowp_bvec1;
/// 1 component vector tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<1, float, packed_highp> packed_highp_vec1;
/// 1 component vector tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<1, float, packed_mediump> packed_mediump_vec1;
/// 1 component vector tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<1, float, packed_lowp> packed_lowp_vec1;
/// 1 component vector tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<1, double, packed_highp> packed_highp_dvec1;
/// 1 component vector tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<1, double, packed_mediump> packed_mediump_dvec1;
/// 1 component vector tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<1, double, packed_lowp> packed_lowp_dvec1;
/// 1 component vector tightly packed in memory of signed integer numbers.
typedef vec<1, int, packed_highp> packed_highp_ivec1;
/// 1 component vector tightly packed in memory of signed integer numbers.
typedef vec<1, int, packed_mediump> packed_mediump_ivec1;
/// 1 component vector tightly packed in memory of signed integer numbers.
typedef vec<1, int, packed_lowp> packed_lowp_ivec1;
/// 1 component vector tightly packed in memory of unsigned integer numbers.
typedef vec<1, uint, packed_highp> packed_highp_uvec1;
/// 1 component vector tightly packed in memory of unsigned integer numbers.
typedef vec<1, uint, packed_mediump> packed_mediump_uvec1;
/// 1 component vector tightly packed in memory of unsigned integer numbers.
typedef vec<1, uint, packed_lowp> packed_lowp_uvec1;
/// 1 component vector tightly packed in memory of bool values.
typedef vec<1, bool, packed_highp> packed_highp_bvec1;
/// 1 component vector tightly packed in memory of bool values.
typedef vec<1, bool, packed_mediump> packed_mediump_bvec1;
/// 1 component vector tightly packed in memory of bool values.
typedef vec<1, bool, packed_lowp> packed_lowp_bvec1;
// -- *vec2 --
/// 2 components vector aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<2, float, aligned_highp> aligned_highp_vec2;
/// 2 components vector aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<2, float, aligned_mediump> aligned_mediump_vec2;
/// 2 components vector aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<2, float, aligned_lowp> aligned_lowp_vec2;
/// 2 components vector aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<2, double, aligned_highp> aligned_highp_dvec2;
/// 2 components vector aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<2, double, aligned_mediump> aligned_mediump_dvec2;
/// 2 components vector aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<2, double, aligned_lowp> aligned_lowp_dvec2;
/// 2 components vector aligned in memory of signed integer numbers.
typedef vec<2, int, aligned_highp> aligned_highp_ivec2;
/// 2 components vector aligned in memory of signed integer numbers.
typedef vec<2, int, aligned_mediump> aligned_mediump_ivec2;
/// 2 components vector aligned in memory of signed integer numbers.
typedef vec<2, int, aligned_lowp> aligned_lowp_ivec2;
/// 2 components vector aligned in memory of unsigned integer numbers.
typedef vec<2, uint, aligned_highp> aligned_highp_uvec2;
/// 2 components vector aligned in memory of unsigned integer numbers.
typedef vec<2, uint, aligned_mediump> aligned_mediump_uvec2;
/// 2 components vector aligned in memory of unsigned integer numbers.
typedef vec<2, uint, aligned_lowp> aligned_lowp_uvec2;
/// 2 components vector aligned in memory of bool values.
typedef vec<2, bool, aligned_highp> aligned_highp_bvec2;
/// 2 components vector aligned in memory of bool values.
typedef vec<2, bool, aligned_mediump> aligned_mediump_bvec2;
/// 2 components vector aligned in memory of bool values.
typedef vec<2, bool, aligned_lowp> aligned_lowp_bvec2;
/// 2 components vector tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<2, float, packed_highp> packed_highp_vec2;
/// 2 components vector tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<2, float, packed_mediump> packed_mediump_vec2;
/// 2 components vector tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<2, float, packed_lowp> packed_lowp_vec2;
/// 2 components vector tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<2, double, packed_highp> packed_highp_dvec2;
/// 2 components vector tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<2, double, packed_mediump> packed_mediump_dvec2;
/// 2 components vector tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<2, double, packed_lowp> packed_lowp_dvec2;
/// 2 components vector tightly packed in memory of signed integer numbers.
typedef vec<2, int, packed_highp> packed_highp_ivec2;
/// 2 components vector tightly packed in memory of signed integer numbers.
typedef vec<2, int, packed_mediump> packed_mediump_ivec2;
/// 2 components vector tightly packed in memory of signed integer numbers.
typedef vec<2, int, packed_lowp> packed_lowp_ivec2;
/// 2 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<2, uint, packed_highp> packed_highp_uvec2;
/// 2 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<2, uint, packed_mediump> packed_mediump_uvec2;
/// 2 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<2, uint, packed_lowp> packed_lowp_uvec2;
/// 2 components vector tightly packed in memory of bool values.
typedef vec<2, bool, packed_highp> packed_highp_bvec2;
/// 2 components vector tightly packed in memory of bool values.
typedef vec<2, bool, packed_mediump> packed_mediump_bvec2;
/// 2 components vector tightly packed in memory of bool values.
typedef vec<2, bool, packed_lowp> packed_lowp_bvec2;
// -- *vec3 --
/// 3 components vector aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<3, float, aligned_highp> aligned_highp_vec3;
/// 3 components vector aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<3, float, aligned_mediump> aligned_mediump_vec3;
/// 3 components vector aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<3, float, aligned_lowp> aligned_lowp_vec3;
/// 3 components vector aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<3, double, aligned_highp> aligned_highp_dvec3;
/// 3 components vector aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<3, double, aligned_mediump> aligned_mediump_dvec3;
/// 3 components vector aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<3, double, aligned_lowp> aligned_lowp_dvec3;
/// 3 components vector aligned in memory of signed integer numbers.
typedef vec<3, int, aligned_highp> aligned_highp_ivec3;
/// 3 components vector aligned in memory of signed integer numbers.
typedef vec<3, int, aligned_mediump> aligned_mediump_ivec3;
/// 3 components vector aligned in memory of signed integer numbers.
typedef vec<3, int, aligned_lowp> aligned_lowp_ivec3;
/// 3 components vector aligned in memory of unsigned integer numbers.
typedef vec<3, uint, aligned_highp> aligned_highp_uvec3;
/// 3 components vector aligned in memory of unsigned integer numbers.
typedef vec<3, uint, aligned_mediump> aligned_mediump_uvec3;
/// 3 components vector aligned in memory of unsigned integer numbers.
typedef vec<3, uint, aligned_lowp> aligned_lowp_uvec3;
/// 3 components vector aligned in memory of bool values.
typedef vec<3, bool, aligned_highp> aligned_highp_bvec3;
/// 3 components vector aligned in memory of bool values.
typedef vec<3, bool, aligned_mediump> aligned_mediump_bvec3;
/// 3 components vector aligned in memory of bool values.
typedef vec<3, bool, aligned_lowp> aligned_lowp_bvec3;
/// 3 components vector tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<3, float, packed_highp> packed_highp_vec3;
/// 3 components vector tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<3, float, packed_mediump> packed_mediump_vec3;
/// 3 components vector tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<3, float, packed_lowp> packed_lowp_vec3;
/// 3 components vector tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<3, double, packed_highp> packed_highp_dvec3;
/// 3 components vector tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<3, double, packed_mediump> packed_mediump_dvec3;
/// 3 components vector tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<3, double, packed_lowp> packed_lowp_dvec3;
/// 3 components vector tightly packed in memory of signed integer numbers.
typedef vec<3, int, packed_highp> packed_highp_ivec3;
/// 3 components vector tightly packed in memory of signed integer numbers.
typedef vec<3, int, packed_mediump> packed_mediump_ivec3;
/// 3 components vector tightly packed in memory of signed integer numbers.
typedef vec<3, int, packed_lowp> packed_lowp_ivec3;
/// 3 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<3, uint, packed_highp> packed_highp_uvec3;
/// 3 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<3, uint, packed_mediump> packed_mediump_uvec3;
/// 3 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<3, uint, packed_lowp> packed_lowp_uvec3;
/// 3 components vector tightly packed in memory of bool values.
typedef vec<3, bool, packed_highp> packed_highp_bvec3;
/// 3 components vector tightly packed in memory of bool values.
typedef vec<3, bool, packed_mediump> packed_mediump_bvec3;
/// 3 components vector tightly packed in memory of bool values.
typedef vec<3, bool, packed_lowp> packed_lowp_bvec3;
// -- *vec4 --
/// 4 components vector aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<4, float, aligned_highp> aligned_highp_vec4;
/// 4 components vector aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<4, float, aligned_mediump> aligned_mediump_vec4;
/// 4 components vector aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<4, float, aligned_lowp> aligned_lowp_vec4;
/// 4 components vector aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<4, double, aligned_highp> aligned_highp_dvec4;
/// 4 components vector aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<4, double, aligned_mediump> aligned_mediump_dvec4;
/// 4 components vector aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<4, double, aligned_lowp> aligned_lowp_dvec4;
/// 4 components vector aligned in memory of signed integer numbers.
typedef vec<4, int, aligned_highp> aligned_highp_ivec4;
/// 4 components vector aligned in memory of signed integer numbers.
typedef vec<4, int, aligned_mediump> aligned_mediump_ivec4;
/// 4 components vector aligned in memory of signed integer numbers.
typedef vec<4, int, aligned_lowp> aligned_lowp_ivec4;
/// 4 components vector aligned in memory of unsigned integer numbers.
typedef vec<4, uint, aligned_highp> aligned_highp_uvec4;
/// 4 components vector aligned in memory of unsigned integer numbers.
typedef vec<4, uint, aligned_mediump> aligned_mediump_uvec4;
/// 4 components vector aligned in memory of unsigned integer numbers.
typedef vec<4, uint, aligned_lowp> aligned_lowp_uvec4;
/// 4 components vector aligned in memory of bool values.
typedef vec<4, bool, aligned_highp> aligned_highp_bvec4;
/// 4 components vector aligned in memory of bool values.
typedef vec<4, bool, aligned_mediump> aligned_mediump_bvec4;
/// 4 components vector aligned in memory of bool values.
typedef vec<4, bool, aligned_lowp> aligned_lowp_bvec4;
/// 4 components vector tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<4, float, packed_highp> packed_highp_vec4;
/// 4 components vector tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<4, float, packed_mediump> packed_mediump_vec4;
/// 4 components vector tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<4, float, packed_lowp> packed_lowp_vec4;
/// 4 components vector tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef vec<4, double, packed_highp> packed_highp_dvec4;
/// 4 components vector tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef vec<4, double, packed_mediump> packed_mediump_dvec4;
/// 4 components vector tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef vec<4, double, packed_lowp> packed_lowp_dvec4;
/// 4 components vector tightly packed in memory of signed integer numbers.
typedef vec<4, int, packed_highp> packed_highp_ivec4;
/// 4 components vector tightly packed in memory of signed integer numbers.
typedef vec<4, int, packed_mediump> packed_mediump_ivec4;
/// 4 components vector tightly packed in memory of signed integer numbers.
typedef vec<4, int, packed_lowp> packed_lowp_ivec4;
/// 4 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<4, uint, packed_highp> packed_highp_uvec4;
/// 4 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<4, uint, packed_mediump> packed_mediump_uvec4;
/// 4 components vector tightly packed in memory of unsigned integer numbers.
typedef vec<4, uint, packed_lowp> packed_lowp_uvec4;
/// 4 components vector tightly packed in memory of bool values.
typedef vec<4, bool, packed_highp> packed_highp_bvec4;
/// 4 components vector tightly packed in memory of bool values.
typedef vec<4, bool, packed_mediump> packed_mediump_bvec4;
/// 4 components vector tightly packed in memory of bool values.
typedef vec<4, bool, packed_lowp> packed_lowp_bvec4;
// -- *mat2 --
/// 2 by 2 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, float, aligned_highp> aligned_highp_mat2;
/// 2 by 2 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, float, aligned_mediump> aligned_mediump_mat2;
/// 2 by 2 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, float, aligned_lowp> aligned_lowp_mat2;
/// 2 by 2 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, double, aligned_highp> aligned_highp_dmat2;
/// 2 by 2 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, double, aligned_mediump> aligned_mediump_dmat2;
/// 2 by 2 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, double, aligned_lowp> aligned_lowp_dmat2;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, float, packed_highp> packed_highp_mat2;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, float, packed_mediump> packed_mediump_mat2;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, float, packed_lowp> packed_lowp_mat2;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, double, packed_highp> packed_highp_dmat2;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, double, packed_mediump> packed_mediump_dmat2;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, double, packed_lowp> packed_lowp_dmat2;
// -- *mat3 --
/// 3 by 3 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, float, aligned_highp> aligned_highp_mat3;
/// 3 by 3 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, float, aligned_mediump> aligned_mediump_mat3;
/// 3 by 3 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, float, aligned_lowp> aligned_lowp_mat3;
/// 3 by 3 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, double, aligned_highp> aligned_highp_dmat3;
/// 3 by 3 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, double, aligned_mediump> aligned_mediump_dmat3;
/// 3 by 3 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, double, aligned_lowp> aligned_lowp_dmat3;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, float, packed_highp> packed_highp_mat3;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, float, packed_mediump> packed_mediump_mat3;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, float, packed_lowp> packed_lowp_mat3;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, double, packed_highp> packed_highp_dmat3;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, double, packed_mediump> packed_mediump_dmat3;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, double, packed_lowp> packed_lowp_dmat3;
// -- *mat4 --
/// 4 by 4 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, float, aligned_highp> aligned_highp_mat4;
/// 4 by 4 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, float, aligned_mediump> aligned_mediump_mat4;
/// 4 by 4 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, float, aligned_lowp> aligned_lowp_mat4;
/// 4 by 4 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, double, aligned_highp> aligned_highp_dmat4;
/// 4 by 4 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, double, aligned_mediump> aligned_mediump_dmat4;
/// 4 by 4 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, double, aligned_lowp> aligned_lowp_dmat4;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, float, packed_highp> packed_highp_mat4;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, float, packed_mediump> packed_mediump_mat4;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, float, packed_lowp> packed_lowp_mat4;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, double, packed_highp> packed_highp_dmat4;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, double, packed_mediump> packed_mediump_dmat4;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, double, packed_lowp> packed_lowp_dmat4;
// -- *mat2x2 --
/// 2 by 2 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, float, aligned_highp> aligned_highp_mat2x2;
/// 2 by 2 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, float, aligned_mediump> aligned_mediump_mat2x2;
/// 2 by 2 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, float, aligned_lowp> aligned_lowp_mat2x2;
/// 2 by 2 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, double, aligned_highp> aligned_highp_dmat2x2;
/// 2 by 2 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, double, aligned_mediump> aligned_mediump_dmat2x2;
/// 2 by 2 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, double, aligned_lowp> aligned_lowp_dmat2x2;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, float, packed_highp> packed_highp_mat2x2;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, float, packed_mediump> packed_mediump_mat2x2;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, float, packed_lowp> packed_lowp_mat2x2;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 2, double, packed_highp> packed_highp_dmat2x2;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 2, double, packed_mediump> packed_mediump_dmat2x2;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 2, double, packed_lowp> packed_lowp_dmat2x2;
// -- *mat2x3 --
/// 2 by 3 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 3, float, aligned_highp> aligned_highp_mat2x3;
/// 2 by 3 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 3, float, aligned_mediump> aligned_mediump_mat2x3;
/// 2 by 3 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 3, float, aligned_lowp> aligned_lowp_mat2x3;
/// 2 by 3 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 3, double, aligned_highp> aligned_highp_dmat2x3;
/// 2 by 3 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 3, double, aligned_mediump> aligned_mediump_dmat2x3;
/// 2 by 3 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 3, double, aligned_lowp> aligned_lowp_dmat2x3;
/// 2 by 3 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 3, float, packed_highp> packed_highp_mat2x3;
/// 2 by 3 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 3, float, packed_mediump> packed_mediump_mat2x3;
/// 2 by 3 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 3, float, packed_lowp> packed_lowp_mat2x3;
/// 2 by 3 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 3, double, packed_highp> packed_highp_dmat2x3;
/// 2 by 3 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 3, double, packed_mediump> packed_mediump_dmat2x3;
/// 2 by 3 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 3, double, packed_lowp> packed_lowp_dmat2x3;
// -- *mat2x4 --
/// 2 by 4 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 4, float, aligned_highp> aligned_highp_mat2x4;
/// 2 by 4 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 4, float, aligned_mediump> aligned_mediump_mat2x4;
/// 2 by 4 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 4, float, aligned_lowp> aligned_lowp_mat2x4;
/// 2 by 4 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 4, double, aligned_highp> aligned_highp_dmat2x4;
/// 2 by 4 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 4, double, aligned_mediump> aligned_mediump_dmat2x4;
/// 2 by 4 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 4, double, aligned_lowp> aligned_lowp_dmat2x4;
/// 2 by 4 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 4, float, packed_highp> packed_highp_mat2x4;
/// 2 by 4 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 4, float, packed_mediump> packed_mediump_mat2x4;
/// 2 by 4 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 4, float, packed_lowp> packed_lowp_mat2x4;
/// 2 by 4 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<2, 4, double, packed_highp> packed_highp_dmat2x4;
/// 2 by 4 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<2, 4, double, packed_mediump> packed_mediump_dmat2x4;
/// 2 by 4 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<2, 4, double, packed_lowp> packed_lowp_dmat2x4;
// -- *mat3x2 --
/// 3 by 2 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 2, float, aligned_highp> aligned_highp_mat3x2;
/// 3 by 2 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 2, float, aligned_mediump> aligned_mediump_mat3x2;
/// 3 by 2 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 2, float, aligned_lowp> aligned_lowp_mat3x2;
/// 3 by 2 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 2, double, aligned_highp> aligned_highp_dmat3x2;
/// 3 by 2 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 2, double, aligned_mediump> aligned_mediump_dmat3x2;
/// 3 by 2 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 2, double, aligned_lowp> aligned_lowp_dmat3x2;
/// 3 by 2 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 2, float, packed_highp> packed_highp_mat3x2;
/// 3 by 2 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 2, float, packed_mediump> packed_mediump_mat3x2;
/// 3 by 2 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 2, float, packed_lowp> packed_lowp_mat3x2;
/// 3 by 2 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 2, double, packed_highp> packed_highp_dmat3x2;
/// 3 by 2 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 2, double, packed_mediump> packed_mediump_dmat3x2;
/// 3 by 2 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 2, double, packed_lowp> packed_lowp_dmat3x2;
// -- *mat3x3 --
/// 3 by 3 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, float, aligned_highp> aligned_highp_mat3x3;
/// 3 by 3 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, float, aligned_mediump> aligned_mediump_mat3x3;
/// 3 by 3 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, float, aligned_lowp> aligned_lowp_mat3x3;
/// 3 by 3 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, double, aligned_highp> aligned_highp_dmat3x3;
/// 3 by 3 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, double, aligned_mediump> aligned_mediump_dmat3x3;
/// 3 by 3 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, double, aligned_lowp> aligned_lowp_dmat3x3;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, float, packed_highp> packed_highp_mat3x3;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, float, packed_mediump> packed_mediump_mat3x3;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, float, packed_lowp> packed_lowp_mat3x3;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 3, double, packed_highp> packed_highp_dmat3x3;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 3, double, packed_mediump> packed_mediump_dmat3x3;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 3, double, packed_lowp> packed_lowp_dmat3x3;
// -- *mat3x4 --
/// 3 by 4 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 4, float, aligned_highp> aligned_highp_mat3x4;
/// 3 by 4 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 4, float, aligned_mediump> aligned_mediump_mat3x4;
/// 3 by 4 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 4, float, aligned_lowp> aligned_lowp_mat3x4;
/// 3 by 4 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 4, double, aligned_highp> aligned_highp_dmat3x4;
/// 3 by 4 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 4, double, aligned_mediump> aligned_mediump_dmat3x4;
/// 3 by 4 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 4, double, aligned_lowp> aligned_lowp_dmat3x4;
/// 3 by 4 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 4, float, packed_highp> packed_highp_mat3x4;
/// 3 by 4 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 4, float, packed_mediump> packed_mediump_mat3x4;
/// 3 by 4 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 4, float, packed_lowp> packed_lowp_mat3x4;
/// 3 by 4 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<3, 4, double, packed_highp> packed_highp_dmat3x4;
/// 3 by 4 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<3, 4, double, packed_mediump> packed_mediump_dmat3x4;
/// 3 by 4 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<3, 4, double, packed_lowp> packed_lowp_dmat3x4;
// -- *mat4x2 --
/// 4 by 2 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 2, float, aligned_highp> aligned_highp_mat4x2;
/// 4 by 2 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 2, float, aligned_mediump> aligned_mediump_mat4x2;
/// 4 by 2 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 2, float, aligned_lowp> aligned_lowp_mat4x2;
/// 4 by 2 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 2, double, aligned_highp> aligned_highp_dmat4x2;
/// 4 by 2 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 2, double, aligned_mediump> aligned_mediump_dmat4x2;
/// 4 by 2 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 2, double, aligned_lowp> aligned_lowp_dmat4x2;
/// 4 by 2 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 2, float, packed_highp> packed_highp_mat4x2;
/// 4 by 2 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 2, float, packed_mediump> packed_mediump_mat4x2;
/// 4 by 2 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 2, float, packed_lowp> packed_lowp_mat4x2;
/// 4 by 2 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 2, double, packed_highp> packed_highp_dmat4x2;
/// 4 by 2 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 2, double, packed_mediump> packed_mediump_dmat4x2;
/// 4 by 2 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 2, double, packed_lowp> packed_lowp_dmat4x2;
// -- *mat4x3 --
/// 4 by 3 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 3, float, aligned_highp> aligned_highp_mat4x3;
/// 4 by 3 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 3, float, aligned_mediump> aligned_mediump_mat4x3;
/// 4 by 3 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 3, float, aligned_lowp> aligned_lowp_mat4x3;
/// 4 by 3 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 3, double, aligned_highp> aligned_highp_dmat4x3;
/// 4 by 3 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 3, double, aligned_mediump> aligned_mediump_dmat4x3;
/// 4 by 3 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 3, double, aligned_lowp> aligned_lowp_dmat4x3;
/// 4 by 3 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 3, float, packed_highp> packed_highp_mat4x3;
/// 4 by 3 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 3, float, packed_mediump> packed_mediump_mat4x3;
/// 4 by 3 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 3, float, packed_lowp> packed_lowp_mat4x3;
/// 4 by 3 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 3, double, packed_highp> packed_highp_dmat4x3;
/// 4 by 3 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 3, double, packed_mediump> packed_mediump_dmat4x3;
/// 4 by 3 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 3, double, packed_lowp> packed_lowp_dmat4x3;
// -- *mat4x4 --
/// 4 by 4 matrix aligned in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, float, aligned_highp> aligned_highp_mat4x4;
/// 4 by 4 matrix aligned in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, float, aligned_mediump> aligned_mediump_mat4x4;
/// 4 by 4 matrix aligned in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, float, aligned_lowp> aligned_lowp_mat4x4;
/// 4 by 4 matrix aligned in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, double, aligned_highp> aligned_highp_dmat4x4;
/// 4 by 4 matrix aligned in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, double, aligned_mediump> aligned_mediump_dmat4x4;
/// 4 by 4 matrix aligned in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, double, aligned_lowp> aligned_lowp_dmat4x4;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, float, packed_highp> packed_highp_mat4x4;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, float, packed_mediump> packed_mediump_mat4x4;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, float, packed_lowp> packed_lowp_mat4x4;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers using high precision arithmetic in term of ULPs.
typedef mat<4, 4, double, packed_highp> packed_highp_dmat4x4;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers using medium precision arithmetic in term of ULPs.
typedef mat<4, 4, double, packed_mediump> packed_mediump_dmat4x4;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers using low precision arithmetic in term of ULPs.
typedef mat<4, 4, double, packed_lowp> packed_lowp_dmat4x4;
// -- default --
#if(defined(GLM_PRECISION_LOWP_FLOAT))
typedef aligned_lowp_vec1 aligned_vec1;
typedef aligned_lowp_vec2 aligned_vec2;
typedef aligned_lowp_vec3 aligned_vec3;
typedef aligned_lowp_vec4 aligned_vec4;
typedef packed_lowp_vec1 packed_vec1;
typedef packed_lowp_vec2 packed_vec2;
typedef packed_lowp_vec3 packed_vec3;
typedef packed_lowp_vec4 packed_vec4;
typedef aligned_lowp_mat2 aligned_mat2;
typedef aligned_lowp_mat3 aligned_mat3;
typedef aligned_lowp_mat4 aligned_mat4;
typedef packed_lowp_mat2 packed_mat2;
typedef packed_lowp_mat3 packed_mat3;
typedef packed_lowp_mat4 packed_mat4;
typedef aligned_lowp_mat2x2 aligned_mat2x2;
typedef aligned_lowp_mat2x3 aligned_mat2x3;
typedef aligned_lowp_mat2x4 aligned_mat2x4;
typedef aligned_lowp_mat3x2 aligned_mat3x2;
typedef aligned_lowp_mat3x3 aligned_mat3x3;
typedef aligned_lowp_mat3x4 aligned_mat3x4;
typedef aligned_lowp_mat4x2 aligned_mat4x2;
typedef aligned_lowp_mat4x3 aligned_mat4x3;
typedef aligned_lowp_mat4x4 aligned_mat4x4;
typedef packed_lowp_mat2x2 packed_mat2x2;
typedef packed_lowp_mat2x3 packed_mat2x3;
typedef packed_lowp_mat2x4 packed_mat2x4;
typedef packed_lowp_mat3x2 packed_mat3x2;
typedef packed_lowp_mat3x3 packed_mat3x3;
typedef packed_lowp_mat3x4 packed_mat3x4;
typedef packed_lowp_mat4x2 packed_mat4x2;
typedef packed_lowp_mat4x3 packed_mat4x3;
typedef packed_lowp_mat4x4 packed_mat4x4;
#elif(defined(GLM_PRECISION_MEDIUMP_FLOAT))
typedef aligned_mediump_vec1 aligned_vec1;
typedef aligned_mediump_vec2 aligned_vec2;
typedef aligned_mediump_vec3 aligned_vec3;
typedef aligned_mediump_vec4 aligned_vec4;
typedef packed_mediump_vec1 packed_vec1;
typedef packed_mediump_vec2 packed_vec2;
typedef packed_mediump_vec3 packed_vec3;
typedef packed_mediump_vec4 packed_vec4;
typedef aligned_mediump_mat2 aligned_mat2;
typedef aligned_mediump_mat3 aligned_mat3;
typedef aligned_mediump_mat4 aligned_mat4;
typedef packed_mediump_mat2 packed_mat2;
typedef packed_mediump_mat3 packed_mat3;
typedef packed_mediump_mat4 packed_mat4;
typedef aligned_mediump_mat2x2 aligned_mat2x2;
typedef aligned_mediump_mat2x3 aligned_mat2x3;
typedef aligned_mediump_mat2x4 aligned_mat2x4;
typedef aligned_mediump_mat3x2 aligned_mat3x2;
typedef aligned_mediump_mat3x3 aligned_mat3x3;
typedef aligned_mediump_mat3x4 aligned_mat3x4;
typedef aligned_mediump_mat4x2 aligned_mat4x2;
typedef aligned_mediump_mat4x3 aligned_mat4x3;
typedef aligned_mediump_mat4x4 aligned_mat4x4;
typedef packed_mediump_mat2x2 packed_mat2x2;
typedef packed_mediump_mat2x3 packed_mat2x3;
typedef packed_mediump_mat2x4 packed_mat2x4;
typedef packed_mediump_mat3x2 packed_mat3x2;
typedef packed_mediump_mat3x3 packed_mat3x3;
typedef packed_mediump_mat3x4 packed_mat3x4;
typedef packed_mediump_mat4x2 packed_mat4x2;
typedef packed_mediump_mat4x3 packed_mat4x3;
typedef packed_mediump_mat4x4 packed_mat4x4;
#else //defined(GLM_PRECISION_HIGHP_FLOAT)
/// 1 component vector aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_vec1 aligned_vec1;
/// 2 components vector aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_vec2 aligned_vec2;
/// 3 components vector aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_vec3 aligned_vec3;
/// 4 components vector aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_vec4 aligned_vec4;
/// 1 component vector tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_vec1 packed_vec1;
/// 2 components vector tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_vec2 packed_vec2;
/// 3 components vector tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_vec3 packed_vec3;
/// 4 components vector tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_vec4 packed_vec4;
/// 2 by 2 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat2 aligned_mat2;
/// 3 by 3 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat3 aligned_mat3;
/// 4 by 4 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat4 aligned_mat4;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat2 packed_mat2;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat3 packed_mat3;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat4 packed_mat4;
/// 2 by 2 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat2x2 aligned_mat2x2;
/// 2 by 3 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat2x3 aligned_mat2x3;
/// 2 by 4 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat2x4 aligned_mat2x4;
/// 3 by 2 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat3x2 aligned_mat3x2;
/// 3 by 3 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat3x3 aligned_mat3x3;
/// 3 by 4 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat3x4 aligned_mat3x4;
/// 4 by 2 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat4x2 aligned_mat4x2;
/// 4 by 3 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat4x3 aligned_mat4x3;
/// 4 by 4 matrix tightly aligned in memory of single-precision floating-point numbers.
typedef aligned_highp_mat4x4 aligned_mat4x4;
/// 2 by 2 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat2x2 packed_mat2x2;
/// 2 by 3 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat2x3 packed_mat2x3;
/// 2 by 4 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat2x4 packed_mat2x4;
/// 3 by 2 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat3x2 packed_mat3x2;
/// 3 by 3 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat3x3 packed_mat3x3;
/// 3 by 4 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat3x4 packed_mat3x4;
/// 4 by 2 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat4x2 packed_mat4x2;
/// 4 by 3 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat4x3 packed_mat4x3;
/// 4 by 4 matrix tightly packed in memory of single-precision floating-point numbers.
typedef packed_highp_mat4x4 packed_mat4x4;
#endif//GLM_PRECISION
#if(defined(GLM_PRECISION_LOWP_DOUBLE))
typedef aligned_lowp_dvec1 aligned_dvec1;
typedef aligned_lowp_dvec2 aligned_dvec2;
typedef aligned_lowp_dvec3 aligned_dvec3;
typedef aligned_lowp_dvec4 aligned_dvec4;
typedef packed_lowp_dvec1 packed_dvec1;
typedef packed_lowp_dvec2 packed_dvec2;
typedef packed_lowp_dvec3 packed_dvec3;
typedef packed_lowp_dvec4 packed_dvec4;
typedef aligned_lowp_dmat2 aligned_dmat2;
typedef aligned_lowp_dmat3 aligned_dmat3;
typedef aligned_lowp_dmat4 aligned_dmat4;
typedef packed_lowp_dmat2 packed_dmat2;
typedef packed_lowp_dmat3 packed_dmat3;
typedef packed_lowp_dmat4 packed_dmat4;
typedef aligned_lowp_dmat2x2 aligned_dmat2x2;
typedef aligned_lowp_dmat2x3 aligned_dmat2x3;
typedef aligned_lowp_dmat2x4 aligned_dmat2x4;
typedef aligned_lowp_dmat3x2 aligned_dmat3x2;
typedef aligned_lowp_dmat3x3 aligned_dmat3x3;
typedef aligned_lowp_dmat3x4 aligned_dmat3x4;
typedef aligned_lowp_dmat4x2 aligned_dmat4x2;
typedef aligned_lowp_dmat4x3 aligned_dmat4x3;
typedef aligned_lowp_dmat4x4 aligned_dmat4x4;
typedef packed_lowp_dmat2x2 packed_dmat2x2;
typedef packed_lowp_dmat2x3 packed_dmat2x3;
typedef packed_lowp_dmat2x4 packed_dmat2x4;
typedef packed_lowp_dmat3x2 packed_dmat3x2;
typedef packed_lowp_dmat3x3 packed_dmat3x3;
typedef packed_lowp_dmat3x4 packed_dmat3x4;
typedef packed_lowp_dmat4x2 packed_dmat4x2;
typedef packed_lowp_dmat4x3 packed_dmat4x3;
typedef packed_lowp_dmat4x4 packed_dmat4x4;
#elif(defined(GLM_PRECISION_MEDIUMP_DOUBLE))
typedef aligned_mediump_dvec1 aligned_dvec1;
typedef aligned_mediump_dvec2 aligned_dvec2;
typedef aligned_mediump_dvec3 aligned_dvec3;
typedef aligned_mediump_dvec4 aligned_dvec4;
typedef packed_mediump_dvec1 packed_dvec1;
typedef packed_mediump_dvec2 packed_dvec2;
typedef packed_mediump_dvec3 packed_dvec3;
typedef packed_mediump_dvec4 packed_dvec4;
typedef aligned_mediump_dmat2 aligned_dmat2;
typedef aligned_mediump_dmat3 aligned_dmat3;
typedef aligned_mediump_dmat4 aligned_dmat4;
typedef packed_mediump_dmat2 packed_dmat2;
typedef packed_mediump_dmat3 packed_dmat3;
typedef packed_mediump_dmat4 packed_dmat4;
typedef aligned_mediump_dmat2x2 aligned_dmat2x2;
typedef aligned_mediump_dmat2x3 aligned_dmat2x3;
typedef aligned_mediump_dmat2x4 aligned_dmat2x4;
typedef aligned_mediump_dmat3x2 aligned_dmat3x2;
typedef aligned_mediump_dmat3x3 aligned_dmat3x3;
typedef aligned_mediump_dmat3x4 aligned_dmat3x4;
typedef aligned_mediump_dmat4x2 aligned_dmat4x2;
typedef aligned_mediump_dmat4x3 aligned_dmat4x3;
typedef aligned_mediump_dmat4x4 aligned_dmat4x4;
typedef packed_mediump_dmat2x2 packed_dmat2x2;
typedef packed_mediump_dmat2x3 packed_dmat2x3;
typedef packed_mediump_dmat2x4 packed_dmat2x4;
typedef packed_mediump_dmat3x2 packed_dmat3x2;
typedef packed_mediump_dmat3x3 packed_dmat3x3;
typedef packed_mediump_dmat3x4 packed_dmat3x4;
typedef packed_mediump_dmat4x2 packed_dmat4x2;
typedef packed_mediump_dmat4x3 packed_dmat4x3;
typedef packed_mediump_dmat4x4 packed_dmat4x4;
#else //defined(GLM_PRECISION_HIGHP_DOUBLE)
/// 1 component vector aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dvec1 aligned_dvec1;
/// 2 components vector aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dvec2 aligned_dvec2;
/// 3 components vector aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dvec3 aligned_dvec3;
/// 4 components vector aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dvec4 aligned_dvec4;
/// 1 component vector tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dvec1 packed_dvec1;
/// 2 components vector tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dvec2 packed_dvec2;
/// 3 components vector tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dvec3 packed_dvec3;
/// 4 components vector tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dvec4 packed_dvec4;
/// 2 by 2 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat2 aligned_dmat2;
/// 3 by 3 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat3 aligned_dmat3;
/// 4 by 4 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat4 aligned_dmat4;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat2 packed_dmat2;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat3 packed_dmat3;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat4 packed_dmat4;
/// 2 by 2 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat2x2 aligned_dmat2x2;
/// 2 by 3 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat2x3 aligned_dmat2x3;
/// 2 by 4 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat2x4 aligned_dmat2x4;
/// 3 by 2 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat3x2 aligned_dmat3x2;
/// 3 by 3 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat3x3 aligned_dmat3x3;
/// 3 by 4 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat3x4 aligned_dmat3x4;
/// 4 by 2 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat4x2 aligned_dmat4x2;
/// 4 by 3 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat4x3 aligned_dmat4x3;
/// 4 by 4 matrix tightly aligned in memory of double-precision floating-point numbers.
typedef aligned_highp_dmat4x4 aligned_dmat4x4;
/// 2 by 2 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat2x2 packed_dmat2x2;
/// 2 by 3 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat2x3 packed_dmat2x3;
/// 2 by 4 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat2x4 packed_dmat2x4;
/// 3 by 2 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat3x2 packed_dmat3x2;
/// 3 by 3 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat3x3 packed_dmat3x3;
/// 3 by 4 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat3x4 packed_dmat3x4;
/// 4 by 2 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat4x2 packed_dmat4x2;
/// 4 by 3 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat4x3 packed_dmat4x3;
/// 4 by 4 matrix tightly packed in memory of double-precision floating-point numbers.
typedef packed_highp_dmat4x4 packed_dmat4x4;
#endif//GLM_PRECISION
#if(defined(GLM_PRECISION_LOWP_INT))
typedef aligned_lowp_ivec1 aligned_ivec1;
typedef aligned_lowp_ivec2 aligned_ivec2;
typedef aligned_lowp_ivec3 aligned_ivec3;
typedef aligned_lowp_ivec4 aligned_ivec4;
#elif(defined(GLM_PRECISION_MEDIUMP_INT))
typedef aligned_mediump_ivec1 aligned_ivec1;
typedef aligned_mediump_ivec2 aligned_ivec2;
typedef aligned_mediump_ivec3 aligned_ivec3;
typedef aligned_mediump_ivec4 aligned_ivec4;
#else //defined(GLM_PRECISION_HIGHP_INT)
/// 1 component vector aligned in memory of signed integer numbers.
typedef aligned_highp_ivec1 aligned_ivec1;
/// 2 components vector aligned in memory of signed integer numbers.
typedef aligned_highp_ivec2 aligned_ivec2;
/// 3 components vector aligned in memory of signed integer numbers.
typedef aligned_highp_ivec3 aligned_ivec3;
/// 4 components vector aligned in memory of signed integer numbers.
typedef aligned_highp_ivec4 aligned_ivec4;
/// 1 component vector tightly packed in memory of signed integer numbers.
typedef packed_highp_ivec1 packed_ivec1;
/// 2 components vector tightly packed in memory of signed integer numbers.
typedef packed_highp_ivec2 packed_ivec2;
/// 3 components vector tightly packed in memory of signed integer numbers.
typedef packed_highp_ivec3 packed_ivec3;
/// 4 components vector tightly packed in memory of signed integer numbers.
typedef packed_highp_ivec4 packed_ivec4;
#endif//GLM_PRECISION
// -- Unsigned integer definition --
#if(defined(GLM_PRECISION_LOWP_UINT))
typedef aligned_lowp_uvec1 aligned_uvec1;
typedef aligned_lowp_uvec2 aligned_uvec2;
typedef aligned_lowp_uvec3 aligned_uvec3;
typedef aligned_lowp_uvec4 aligned_uvec4;
#elif(defined(GLM_PRECISION_MEDIUMP_UINT))
typedef aligned_mediump_uvec1 aligned_uvec1;
typedef aligned_mediump_uvec2 aligned_uvec2;
typedef aligned_mediump_uvec3 aligned_uvec3;
typedef aligned_mediump_uvec4 aligned_uvec4;
#else //defined(GLM_PRECISION_HIGHP_UINT)
/// 1 component vector aligned in memory of unsigned integer numbers.
typedef aligned_highp_uvec1 aligned_uvec1;
/// 2 components vector aligned in memory of unsigned integer numbers.
typedef aligned_highp_uvec2 aligned_uvec2;
/// 3 components vector aligned in memory of unsigned integer numbers.
typedef aligned_highp_uvec3 aligned_uvec3;
/// 4 components vector aligned in memory of unsigned integer numbers.
typedef aligned_highp_uvec4 aligned_uvec4;
/// 1 component vector tightly packed in memory of unsigned integer numbers.
typedef packed_highp_uvec1 packed_uvec1;
/// 2 components vector tightly packed in memory of unsigned integer numbers.
typedef packed_highp_uvec2 packed_uvec2;
/// 3 components vector tightly packed in memory of unsigned integer numbers.
typedef packed_highp_uvec3 packed_uvec3;
/// 4 components vector tightly packed in memory of unsigned integer numbers.
typedef packed_highp_uvec4 packed_uvec4;
#endif//GLM_PRECISION
#if(defined(GLM_PRECISION_LOWP_BOOL))
typedef aligned_lowp_bvec1 aligned_bvec1;
typedef aligned_lowp_bvec2 aligned_bvec2;
typedef aligned_lowp_bvec3 aligned_bvec3;
typedef aligned_lowp_bvec4 aligned_bvec4;
#elif(defined(GLM_PRECISION_MEDIUMP_BOOL))
typedef aligned_mediump_bvec1 aligned_bvec1;
typedef aligned_mediump_bvec2 aligned_bvec2;
typedef aligned_mediump_bvec3 aligned_bvec3;
typedef aligned_mediump_bvec4 aligned_bvec4;
#else //defined(GLM_PRECISION_HIGHP_BOOL)
/// 1 component vector aligned in memory of bool values.
typedef aligned_highp_bvec1 aligned_bvec1;
/// 2 components vector aligned in memory of bool values.
typedef aligned_highp_bvec2 aligned_bvec2;
/// 3 components vector aligned in memory of bool values.
typedef aligned_highp_bvec3 aligned_bvec3;
/// 4 components vector aligned in memory of bool values.
typedef aligned_highp_bvec4 aligned_bvec4;
/// 1 components vector tightly packed in memory of bool values.
typedef packed_highp_bvec1 packed_bvec1;
/// 2 components vector tightly packed in memory of bool values.
typedef packed_highp_bvec2 packed_bvec2;
/// 3 components vector tightly packed in memory of bool values.
typedef packed_highp_bvec3 packed_bvec3;
/// 4 components vector tightly packed in memory of bool values.
typedef packed_highp_bvec4 packed_bvec4;
#endif//GLM_PRECISION
/// @}
}//namespace glm
|
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The Bulwark developers
// Copyright (c) 2018-2019 The FestonCoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "masternode-payments.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "rpcserver.h"
#include "utilmoneystr.h"
#include <univalue.h>
#include <boost/tokenizer.hpp>
#include <fstream>
namespace {
void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
} // noname namespace
void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, AvailableCoinsType coin_type = ALL_COINS)
{
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
string strError;
if (pwalletMain->IsLocked()) {
strError = "Error: Wallet locked, unable to create transaction!";
LogPrintf("SendMoney() : %s", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse FestonCoin address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, coin_type)) {
if (nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
LogPrintf("SendMoney() : %s\n", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue obfuscation(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() == 0)
throw runtime_error(
"obfuscation <festonaddress> <amount>\n"
"festonaddress, reset, or auto (AutoDenominate)"
"<amount> is a real and will be rounded to the next 0.1" +
HelpRequiringPassphrase());
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (params[0].get_str() == "auto") {
if (fMasterNode)
return "ObfuScation is not supported from masternodes";
return "DoAutomaticDenominating " + (obfuScationPool.DoAutomaticDenominating() ? "successful" : ("failed: " + obfuScationPool.GetStatus()));
}
if (params[0].get_str() == "reset") {
obfuScationPool.Reset();
return "successfully reset obfuscation";
}
if (params.size() != 2)
throw runtime_error(
"obfuscation <festonaddress> <amount>\n"
"festonaddress, denominate, or auto (AutoDenominate)"
"<amount> is a real and will be rounded to the next 0.1" +
HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid FestonCoin address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
// string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx, ONLY_DENOMINATED);
SendMoney(address.Get(), nAmount, wtx, ONLY_DENOMINATED);
// if (strError != "")
// throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
UniValue getpoolinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpoolinfo\n"
"\nReturns anonymous pool-related information\n"
"\nResult:\n"
"{\n"
" \"current\": \"addr\", (string) FestonCoin address of current masternode\n"
" \"state\": xxxx, (string) unknown\n"
" \"entries\": xxxx, (numeric) Number of entries\n"
" \"accepted\": xxxx, (numeric) Number of entries accepted\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getpoolinfo", "") + HelpExampleRpc("getpoolinfo", ""));
//fixme: GetCurrentMasterNode add MN level
const auto* currentMasterNode = mnodeman.GetCurrentMasterNode(CMasternode::LevelValue::UNSPECIFIED);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("current_masternode", currentMasterNode ? currentMasterNode->addr.ToString() : std::string{"null"}));
obj.push_back(Pair("state", obfuScationPool.GetState()));
obj.push_back(Pair("entries", obfuScationPool.GetEntriesCount()));
obj.push_back(Pair("entries_accepted", obfuScationPool.GetCountEntriesAccepted()));
return obj;
}
// This command is retained for backwards compatibility, but is depreciated.
// Future removal of this command is planned to keep things clean.
UniValue masternode(const UniValue& params, bool fHelp)
{
string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "start" && strCommand != "start-alias" && strCommand != "start-many" && strCommand != "start-all" && strCommand != "start-missing" &&
strCommand != "start-disabled" && strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "enforce" &&
strCommand != "debug" && strCommand != "current" && strCommand != "winners" && strCommand != "genkey" && strCommand != "connect" &&
strCommand != "outputs" && strCommand != "status" && strCommand != "calcscore"))
throw runtime_error(
"masternode \"command\"...\n"
"\nSet of commands to execute masternode related actions\n"
"This command is depreciated, please see individual command documentation for future reference\n\n"
"\nArguments:\n"
"1. \"command\" (string or set of strings, required) The command to execute\n"
"\nAvailable commands:\n"
" count - Print count information of all known masternodes\n"
" current - Print info on current masternode winner\n"
" debug - Print masternode status\n"
" genkey - Generate new masternodeprivkey\n"
" outputs - Print masternode compatible outputs\n"
" start - Start masternode configured in feston.conf\n"
" start-alias - Start single masternode by assigned alias configured in masternode.conf\n"
" start-<mode> - Start masternodes configured in masternode.conf (<mode>: 'all', 'missing', 'disabled')\n"
" status - Print masternode status information\n"
" list - Print list of all known masternodes (see masternodelist for more info)\n"
" list-conf - Print masternode.conf in JSON format\n"
" winners - Print list of masternode winners\n");
if (strCommand == "list") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return listmasternodes(newParams, fHelp);
}
if (strCommand == "connect") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return masternodeconnect(newParams, fHelp);
}
if (strCommand == "count") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return getmasternodecount(newParams, fHelp);
}
if (strCommand == "current") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return masternodecurrent(newParams, fHelp);
}
if (strCommand == "debug") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return masternodedebug(newParams, fHelp);
}
if (strCommand == "start" || strCommand == "start-alias" || strCommand == "start-many" || strCommand == "start-all" || strCommand == "start-missing" || strCommand == "start-disabled") {
return startmasternode(params, fHelp);
}
if (strCommand == "genkey") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return createmasternodekey(newParams, fHelp);
}
if (strCommand == "list-conf") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return listmasternodeconf(newParams, fHelp);
}
if (strCommand == "outputs") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return getmasternodeoutputs(newParams, fHelp);
}
if (strCommand == "status") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return getmasternodestatus(newParams, fHelp);
}
if (strCommand == "winners") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return getmasternodewinners(newParams, fHelp);
}
if (strCommand == "calcscore") {
UniValue newParams(UniValue::VARR);
// forward params but skip command
for (unsigned int i = 1; i < params.size(); i++) {
newParams.push_back(params[i]);
}
return getmasternodescores(newParams, fHelp);
}
return NullUniValue;
}
UniValue listmasternodes(const UniValue& params, bool fHelp)
{
std::string strFilter = "";
if (params.size() == 1) strFilter = params[0].get_str();
if (fHelp || (params.size() > 1))
throw runtime_error(
"listmasternodes ( \"filter\" )\n"
"\nGet a ranked list of masternodes\n"
"\nArguments:\n"
"1. \"filter\" (string, optional) Filter search text. Partial match by txhash, status, or addr.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"level\": n, (numeric) Masternode Level\n"
" \"rank\": n, (numeric) Masternode Rank (or 0 if not enabled)\n"
" \"txhash\": \"hash\", (string) Collateral transaction hash\n"
" \"outidx\": n, (numeric) Collateral transaction output index\n"
" \"status\": s, (string) Status (ENABLED/EXPIRED/REMOVE/etc)\n"
" \"addr\": \"addr\", (string) Masternode FestonCoin address\n"
" \"version\": v, (numeric) Masternode protocol version\n"
" \"lastseen\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last seen\n"
" \"activetime\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) masternode has been active\n"
" \"lastpaid\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) masternode was last paid\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("masternodelist", "") + HelpExampleRpc("masternodelist", ""));
UniValue ret(UniValue::VARR);
int nHeight;
{
LOCK(cs_main);
CBlockIndex* pindex = chainActive.Tip();
if(!pindex) return 0;
nHeight = pindex->nHeight;
}
std::vector<pair<int, CMasternode> > vMasternodeRanks = mnodeman.GetMasternodeRanks(nHeight);
BOOST_FOREACH (PAIRTYPE(int, CMasternode) & s, vMasternodeRanks) {
UniValue obj(UniValue::VOBJ);
std::string strVin = s.second.vin.prevout.ToStringShort();
std::string strTxHash = s.second.vin.prevout.hash.ToString();
uint32_t oIdx = s.second.vin.prevout.n;
CMasternode* mn = mnodeman.Find(s.second.vin);
if (mn != NULL) {
if (strFilter != "" && strTxHash.find(strFilter) == string::npos &&
mn->Status().find(strFilter) == string::npos &&
CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString().find(strFilter) == string::npos) continue;
std::string strStatus = mn->Status();
std::string strHost;
int port;
SplitHostPort(mn->addr.ToString(), port, strHost);
CNetAddr node = CNetAddr(strHost, false);
std::string strNetwork = GetNetworkName(node.GetNetwork());
obj.push_back(Pair("level", mn->Level()));
obj.push_back(Pair("rank", (strStatus == "ENABLED" ? s.first : 0)));
obj.push_back(Pair("network", strNetwork));
obj.push_back(Pair("txhash", strTxHash));
obj.push_back(Pair("outidx", (uint64_t)oIdx));
obj.push_back(Pair("status", strStatus));
obj.push_back(Pair("addr", CBitcoinAddress(mn->pubKeyCollateralAddress.GetID()).ToString()));
obj.push_back(Pair("version", mn->protocolVersion));
obj.push_back(Pair("lastseen", (int64_t)mn->lastPing.sigTime));
obj.push_back(Pair("activetime", (int64_t)(mn->lastPing.sigTime - mn->sigTime)));
obj.push_back(Pair("lastpaid", (int64_t)mn->GetLastPaid()));
obj.push_back(Pair("netip", mn->addr.ToString()));
ret.push_back(obj);
}
}
return ret;
}
UniValue masternodeconnect(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 1))
throw runtime_error(
"masternodeconnect \"address\"\n"
"\nAttempts to connect to specified masternode address\n"
"\nArguments:\n"
"1. \"address\" (string, required) IP or net address to connect to\n"
"\nExamples:\n" +
HelpExampleCli("masternodeconnect", "\"192.168.0.6:13333\"") + HelpExampleRpc("masternodeconnect", "\"192.168.0.6:13333\""));
std::string strAddress = params[0].get_str();
CService addr = CService(strAddress);
CNode* pnode = ConnectNode((CAddress)addr, NULL, false);
if (pnode) {
pnode->Release();
return NullUniValue;
} else {
throw runtime_error("error connecting\n");
}
}
UniValue getmasternodecount (const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() > 0))
throw runtime_error(
"getmasternodecount\n"
"\nGet masternode count values\n"
"\nResult:\n"
"{\n"
" \"grandtotal\": n, (numeric) Grand Total masternodes\n"
" \"total\": [\n"
" {\n"
" \"level\": n, (numeric) Masternodes level\n"
" \"count\": n (numeric) Total count\n"
" }\n"
" ,...\n"
" ],\n"
" \"enabled\": [\n"
" {\n"
" \"level\": n, (numeric) Masternodes level\n"
" \"count\": n (numeric) Enabled masternodes\n"
" }\n"
" ,...\n"
" ],\n"
" \"obfcompat\": [\n"
" {\n"
" \"level\": n, (numeric) Masternodes level\n"
" \"count\": n (numeric) Obfuscation Compatible\n"
" }\n"
" ,...\n"
" ],\n"
" \"stable\": [\n"
" {\n"
" \"level\": n, (numeric) Masternodes level\n"
" \"count\": n (numeric) Stable count\n"
" }\n"
" ,...\n"
" ],\n"
" \"inqueue\": [\n"
" {\n"
" \"level\": n, (numeric) Masternodes level\n"
" \"count\": n (numeric) Masternodes in queue\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmasternodecount", "") + HelpExampleRpc("getmasternodecount", ""));
UniValue total{UniValue::VARR};
UniValue stable{UniValue::VARR};
UniValue obfcompat{UniValue::VARR};
UniValue enabled{UniValue::VARR};
UniValue inqueue{UniValue::VARR};
auto chain_tip = chainActive.Tip();
for(unsigned l = CMasternode::LevelValue::MIN; l <= CMasternode::LevelValue::MAX; ++l) {
UniValue total_item{UniValue::VOBJ};
total_item.push_back(Pair("level", l));
total_item.push_back(Pair("count", mnodeman.size(l)));
total.push_back(total_item);
UniValue stable_item{UniValue::VOBJ};
stable_item.push_back(Pair("level", l));
stable_item.push_back(Pair("count", mnodeman.stable_size(l)));
stable.push_back(stable_item);
UniValue enabled_item{UniValue::VOBJ};
enabled_item.push_back(Pair("level", l));
enabled_item.push_back(Pair("count", mnodeman.CountEnabled(l)));
enabled.push_back(enabled_item);
UniValue inqueue_item{UniValue::VOBJ};
unsigned inqueue_count = 0u;
if(chain_tip)
mnodeman.GetNextMasternodeInQueueForPayment(chain_tip->nHeight, l, true, inqueue_count);
inqueue_item.push_back(Pair("level", l));
inqueue_item.push_back(Pair("count", inqueue_count));
inqueue.push_back(inqueue_item);
UniValue obfcomat_item{UniValue::VOBJ};
obfcomat_item.push_back(Pair("level", l));
obfcomat_item.push_back(Pair("count", mnodeman.CountEnabled(l, ActiveProtocol())));
obfcompat.push_back(obfcomat_item);
}
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("grandtotal", mnodeman.size()));
obj.push_back(Pair("total", total));
obj.push_back(Pair("enabled", enabled));
obj.push_back(Pair("obfcompat", obfcompat));
obj.push_back(Pair("stable", stable));
obj.push_back(Pair("inqueue", inqueue));
return obj;
}
UniValue masternodecurrent (const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 0))
throw runtime_error(
"masternodecurrent\n"
"\nGet current masternode winner\n"
"\nResult:\n"
"{\n"
" \"protocol\": xxxx, (numeric) Protocol version\n"
" \"txhash\": \"xxxx\", (string) Collateral transaction hash\n"
" \"pubkey\": \"xxxx\", (string) MN Public key\n"
" \"lastseen\": xxx, (numeric) Time since epoch of last seen\n"
" \"activeseconds\": xxx, (numeric) Seconds MN has been active\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("masternodecurrent", "") + HelpExampleRpc("masternodecurrent", ""));
//fixme: GetCurrentMasterNode add MN level
CMasternode* winner = mnodeman.GetCurrentMasterNode(CMasternode::LevelValue::UNSPECIFIED, 1);
if (winner) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("protocol", (int64_t)winner->protocolVersion));
obj.push_back(Pair("txhash", winner->vin.prevout.hash.ToString()));
obj.push_back(Pair("pubkey", CBitcoinAddress(winner->pubKeyCollateralAddress.GetID()).ToString()));
obj.push_back(Pair("lastseen", (winner->lastPing == CMasternodePing()) ? winner->sigTime : (int64_t)winner->lastPing.sigTime));
obj.push_back(Pair("activeseconds", (winner->lastPing == CMasternodePing()) ? 0 : (int64_t)(winner->lastPing.sigTime - winner->sigTime)));
return obj;
}
throw runtime_error("unknown");
}
UniValue masternodedebug (const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 0))
throw runtime_error(
"masternodedebug\n"
"\nPrint masternode status\n"
"\nResult:\n"
"\"status\" (string) Masternode status message\n"
"\nExamples:\n" +
HelpExampleCli("masternodedebug", "") + HelpExampleRpc("masternodedebug", ""));
if (activeMasternode.status != ACTIVE_MASTERNODE_INITIAL || !masternodeSync.IsSynced())
return activeMasternode.GetStatus();
CTxIn vin = CTxIn();
CPubKey pubkey = CScript();
CKey key;
if (!activeMasternode.GetMasterNodeVin(vin, pubkey, key))
throw runtime_error("Missing masternode input, please look at the documentation for instructions on masternode creation\n");
else
return activeMasternode.GetStatus();
}
UniValue startmasternode (const UniValue& params, bool fHelp)
{
std::string strCommand;
if (params.size() >= 1) {
strCommand = params[0].get_str();
// Backwards compatibility with legacy 'masternode' super-command forwarder
if (strCommand == "start") strCommand = "local";
if (strCommand == "start-alias") strCommand = "alias";
if (strCommand == "start-all") strCommand = "all";
if (strCommand == "start-many") strCommand = "many";
if (strCommand == "start-missing") strCommand = "missing";
if (strCommand == "start-disabled") strCommand = "disabled";
}
if (fHelp || params.size() < 2 || params.size() > 3 ||
(params.size() == 2 && (strCommand != "local" && strCommand != "all" && strCommand != "many" && strCommand != "missing" && strCommand != "disabled")) ||
(params.size() == 3 && strCommand != "alias"))
throw runtime_error(
"startmasternode \"local|all|many|missing|disabled|alias\" lockwallet ( \"alias\" )\n"
"\nAttempts to start one or more masternode(s)\n"
"\nArguments:\n"
"1. set (string, required) Specify which set of masternode(s) to start.\n"
"2. lockwallet (boolean, required) Lock wallet after completion.\n"
"3. alias (string) Masternode alias. Required if using 'alias' as the set.\n"
"\nResult: (for 'local' set):\n"
"\"status\" (string) Masternode status message\n"
"\nResult: (for other sets):\n"
"{\n"
" \"overall\": \"xxxx\", (string) Overall status message\n"
" \"detail\": [\n"
" {\n"
" \"node\": \"xxxx\", (string) Node name or alias\n"
" \"result\": \"xxxx\", (string) 'success' or 'failed'\n"
" \"error\": \"xxxx\" (string) Error message, if failed\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("startmasternode", "\"alias\" \"0\" \"my_mn\"") + HelpExampleRpc("startmasternode", "\"alias\" \"0\" \"my_mn\""));
bool fLock = (params[1].get_str() == "true" ? true : false);
if (strCommand == "local") {
if (!fMasterNode) throw runtime_error("you must set masternode=1 in the configuration\n");
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (activeMasternode.status != ACTIVE_MASTERNODE_STARTED) {
activeMasternode.status = ACTIVE_MASTERNODE_INITIAL; // TODO: consider better way
activeMasternode.ManageStatus();
if (fLock)
pwalletMain->Lock();
}
return activeMasternode.GetStatus();
}
if (strCommand == "all" || strCommand == "many" || strCommand == "missing" || strCommand == "disabled") {
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if ((strCommand == "missing" || strCommand == "disabled") &&
(masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_LIST ||
masternodeSync.RequestedMasternodeAssets == MASTERNODE_SYNC_FAILED)) {
throw runtime_error("You can't use this command until masternode list is synced\n");
}
std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries;
mnEntries = masternodeConfig.getEntries();
int successful = 0;
int failed = 0;
UniValue resultsObj(UniValue::VARR);
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
std::string errorMessage;
int nIndex;
if(!mne.castOutputIndex(nIndex))
continue;
CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex));
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
if (strCommand == "missing") continue;
if (strCommand == "disabled" && pmn->IsEnabled()) continue;
}
bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage);
UniValue statusObj(UniValue::VOBJ);
statusObj.push_back(Pair("alias", mne.getAlias()));
statusObj.push_back(Pair("result", result ? "success" : "failed"));
if (result) {
successful++;
statusObj.push_back(Pair("error", ""));
} else {
failed++;
statusObj.push_back(Pair("error", errorMessage));
}
resultsObj.push_back(statusObj);
}
if (fLock)
pwalletMain->Lock();
UniValue returnObj(UniValue::VOBJ);
returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
if (strCommand == "alias") {
std::string alias = params[2].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
bool found = false;
int successful = 0;
int failed = 0;
UniValue resultsObj(UniValue::VARR);
UniValue statusObj(UniValue::VOBJ);
statusObj.push_back(Pair("alias", alias));
for (CMasternodeConfig::CMasternodeEntry mne : masternodeConfig.getEntries()) {
if (mne.getAlias() != alias)
continue;
found = true;
std::string errorMessage;
bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage);
statusObj.push_back(Pair("result", result ? "successful" : "failed"));
if (result) {
successful++;
statusObj.push_back(Pair("error", ""));
} else {
failed++;
statusObj.push_back(Pair("error", errorMessage));
}
break;
}
if (!found) {
failed++;
statusObj.push_back(Pair("result", "failed"));
statusObj.push_back(Pair("error", "could not find alias in config. Verify with list-conf."));
}
resultsObj.push_back(statusObj);
if (fLock)
pwalletMain->Lock();
UniValue returnObj(UniValue::VOBJ);
returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", successful, failed, successful + failed)));
returnObj.push_back(Pair("detail", resultsObj));
return returnObj;
}
return NullUniValue;
}
UniValue createmasternodekey (const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 0))
throw runtime_error(
"createmasternodekey\n"
"\nCreate a new masternode private key\n"
"\nResult:\n"
"\"key\" (string) Masternode private key\n"
"\nExamples:\n" +
HelpExampleCli("createmasternodekey", "") + HelpExampleRpc("createmasternodekey", ""));
CKey secret;
secret.MakeNewKey(false);
return CBitcoinSecret(secret).ToString();
}
UniValue getmasternodeoutputs (const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 0))
throw runtime_error(
"getmasternodeoutputs\n"
"\nPrint all masternode transaction outputs\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txhash\": \"xxxx\", (string) output transaction hash\n"
" \"outputidx\": n (numeric) output index number\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getmasternodeoutputs", "") + HelpExampleRpc("getmasternodeoutputs", ""));
// Find possible candidates
vector<COutput> possibleCoins = activeMasternode.SelectCoinsMasternode();
UniValue ret(UniValue::VARR);
BOOST_FOREACH (COutput& out, possibleCoins) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("txhash", out.tx->GetHash().ToString()));
obj.push_back(Pair("outputidx", out.i));
ret.push_back(obj);
}
return ret;
}
UniValue listmasternodeconf (const UniValue& params, bool fHelp)
{
std::string strFilter = "";
if (params.size() == 1) strFilter = params[0].get_str();
if (fHelp || (params.size() > 1))
throw runtime_error(
"listmasternodeconf ( \"filter\" )\n"
"\nPrint masternode.conf in JSON format\n"
"\nArguments:\n"
"1. \"filter\" (string, optional) Filter search text. Partial match on alias, address, txHash, or status.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"alias\": \"xxxx\", (string) masternode alias\n"
" \"address\": \"xxxx\", (string) masternode IP address\n"
" \"privateKey\": \"xxxx\", (string) masternode private key\n"
" \"txHash\": \"xxxx\", (string) transaction hash\n"
" \"outputIndex\": n, (numeric) transaction output index\n"
" \"status\": \"xxxx\" (string) masternode status\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listmasternodeconf", "") + HelpExampleRpc("listmasternodeconf", ""));
std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries;
mnEntries = masternodeConfig.getEntries();
UniValue ret(UniValue::VARR);
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
int nIndex;
if(!mne.castOutputIndex(nIndex))
continue;
CTxIn vin = CTxIn(uint256(mne.getTxHash()), uint32_t(nIndex));
CMasternode* pmn = mnodeman.Find(vin);
std::string strStatus = pmn ? pmn->Status() : "MISSING";
if (strFilter != "" && mne.getAlias().find(strFilter) == string::npos &&
mne.getIp().find(strFilter) == string::npos &&
mne.getTxHash().find(strFilter) == string::npos &&
strStatus.find(strFilter) == string::npos) continue;
UniValue mnObj(UniValue::VOBJ);
mnObj.push_back(Pair("alias", mne.getAlias()));
mnObj.push_back(Pair("address", mne.getIp()));
mnObj.push_back(Pair("privateKey", mne.getPrivKey()));
mnObj.push_back(Pair("txHash", mne.getTxHash()));
mnObj.push_back(Pair("outputIndex", mne.getOutputIndex()));
mnObj.push_back(Pair("status", strStatus));
ret.push_back(mnObj);
}
return ret;
}
UniValue getmasternodestatus (const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 0))
throw runtime_error(
"getmasternodestatus\n"
"\nPrint masternode status\n"
"\nResult:\n"
"{\n"
" \"txhash\": \"xxxx\", (string) Collateral transaction hash\n"
" \"outputidx\": n, (numeric) Collateral transaction output index number\n"
" \"netaddr\": \"xxxx\", (string) Masternode network address\n"
" \"addr\": \"xxxx\", (string) FestonCoin address for masternode payments\n"
" \"status\": \"xxxx\", (string) Masternode status\n"
" \"message\": \"xxxx\" (string) Masternode status message\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmasternodestatus", "") + HelpExampleRpc("getmasternodestatus", ""));
if (!fMasterNode) throw runtime_error("This is not a masternode");
CMasternode* pmn = mnodeman.Find(activeMasternode.vin);
if (pmn) {
UniValue mnObj(UniValue::VOBJ);
mnObj.push_back(Pair("txhash", activeMasternode.vin.prevout.hash.ToString()));
mnObj.push_back(Pair("outputidx", (uint64_t)activeMasternode.vin.prevout.n));
mnObj.push_back(Pair("netaddr", activeMasternode.service.ToString()));
mnObj.push_back(Pair("addr", CBitcoinAddress(pmn->pubKeyCollateralAddress.GetID()).ToString()));
mnObj.push_back(Pair("status", activeMasternode.status));
mnObj.push_back(Pair("message", activeMasternode.GetStatus()));
return mnObj;
}
throw runtime_error("Masternode not found in the list of available masternodes. Current status: "
+ activeMasternode.GetStatus());
}
UniValue getmasternodewinners(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"getmasternodewinners ( blocks \"filter\" )\n"
"\nPrint the masternode winners for the last n blocks\n"
"\nArguments:\n"
"1. blocks (numeric, optional) Number of previous blocks to show (default: 10)\n"
"2. filter (string, optional) Search filter matching MN address\n"
"\nResult (single winner):\n"
"[\n"
" {\n"
" \"nHeight\": n, (numeric) block height\n"
" \"winner\": {\n"
" \"address\": \"xxxx\", (string) FestonCoin MN Address\n"
" \"level\": n, (numeric) Masternode level\n"
" \"nVotes\": n, (numeric) Number of votes for winner\n"
" }\n"
" }\n"
" ,...\n"
"]\n"
"\nResult (multiple winners):\n"
"[\n"
" {\n"
" \"nHeight\": n, (numeric) block height\n"
" \"winner\": [\n"
" {\n"
" \"address\": \"xxxx\", (string) FestonCoin MN Address\n"
" \"level\": n, (numeric) Masternode level\n"
" \"nVotes\": n, (numeric) Number of votes for winner\n"
" }\n"
" ,...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getmasternodewinners", "") + HelpExampleRpc("getmasternodewinners", ""));
int nHeight;
{
LOCK(cs_main);
CBlockIndex* pindex = chainActive.Tip();
if(!pindex) return 0;
nHeight = pindex->nHeight;
}
int nLast = 10;
std::string strFilter = "";
if(params.size() >= 1)
nLast = atoi(params[0].get_str());
if(params.size() == 2)
strFilter = params[1].get_str();
UniValue ret(UniValue::VARR);
for(int i = nHeight - nLast; i < nHeight + 20; ++i) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("nHeight", i));
std::string strPayment = GetRequiredPaymentsString(i);
if (strFilter != "" && strPayment.find(strFilter) == std::string::npos) continue;
if (strPayment.find(',') != std::string::npos) {
UniValue winner(UniValue::VARR);
boost::char_separator<char> sep(",");
boost::tokenizer< boost::char_separator<char> > tokens(strPayment, sep);
for (const string& t : tokens) {
UniValue addr(UniValue::VOBJ);
std::size_t pos1 = t.find(":");
std::size_t pos2 = t.rfind(":");
std::string strAddress = t.substr(0, pos1);
ltrim(strAddress);
uint64_t level = atoi(t.substr(pos1 + 1, pos2));
uint64_t nVotes = atoi(t.substr(pos2 + 1));
addr.push_back(Pair("address", strAddress));
addr.push_back(Pair("level", level));
addr.push_back(Pair("nVotes", nVotes));
winner.push_back(addr);
}
obj.push_back(Pair("winner", winner));
} else if (strPayment.find("Unknown") == std::string::npos) {
UniValue winner(UniValue::VOBJ);
std::size_t pos1 = strPayment.find(":");
std::size_t pos2 = strPayment.rfind(":");
std::string strAddress = strPayment.substr(0, pos1);
ltrim(strAddress);
uint64_t level = atoi(strPayment.substr(pos1 + 1, pos2));
uint64_t nVotes = atoi(strPayment.substr(pos2 + 1));
winner.push_back(Pair("address", strAddress));
winner.push_back(Pair("level", level));
winner.push_back(Pair("nVotes", nVotes));
obj.push_back(Pair("winner", winner));
} else {
UniValue winner(UniValue::VOBJ);
winner.push_back(Pair("address", strPayment));
winner.push_back(Pair("nVotes", 0));
obj.push_back(Pair("winner", winner));
}
ret.push_back(obj);
}
return ret;
}
UniValue getmasternodescores (const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getmasternodescores ( blocks )\n"
"\nPrint list of winning masternode by score\n"
"\nArguments:\n"
"1. blocks (numeric, optional) Show the last n blocks (default 10)\n"
"\nResult:\n"
"{\n"
" xxxx: \"xxxx\" (numeric : string) Block height : Masternode hash\n"
" ,...\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmasternodescores", "") + HelpExampleRpc("getmasternodescores", ""));
int nLast = 10;
if (params.size() == 1) {
try {
nLast = std::stoi(params[0].get_str());
} catch (const boost::bad_lexical_cast &) {
throw runtime_error("Exception on param 2");
}
}
UniValue obj(UniValue::VOBJ);
std::vector<CMasternode> vMasternodes = mnodeman.GetFullMasternodeVector();
for (int nHeight = chainActive.Tip()->nHeight - nLast; nHeight < chainActive.Tip()->nHeight + 20; nHeight++) {
uint256 nHigh = 0;
CMasternode* pBestMasternode = NULL;
BOOST_FOREACH (CMasternode& mn, vMasternodes) {
uint256 n = mn.CalculateScore(1, nHeight - 100);
if (n > nHigh) {
nHigh = n;
pBestMasternode = &mn;
}
}
if (pBestMasternode)
obj.push_back(Pair(strprintf("%d", nHeight), pBestMasternode->vin.prevout.hash.ToString().c_str()));
}
return obj;
}
|
/*****************************************************************************
* Author: Valient Gough <vgough@pobox.com>
*
*****************************************************************************
* Copyright (c) 2003-2004, Valient Gough
*
* This program 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 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DirNode.h"
#include <cerrno>
#include <cstdio>
#include <cstring>
#ifdef __linux__
#include <sys/fsuid.h>
#endif
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#include <utime.h>
#include "Context.h"
#include "Error.h"
#include "FSConfig.h"
#include "FileNode.h"
#include "FileUtils.h"
#include "Mutex.h"
#include "NameIO.h"
#include "easylogging++.h"
using namespace std;
namespace encfs {
class DirDeleter {
public:
void operator()(DIR *d) { ::closedir(d); }
};
DirTraverse::DirTraverse(std::shared_ptr<DIR> _dirPtr, uint64_t _iv,
std::shared_ptr<NameIO> _naming, bool _root)
: dir(std::move(_dirPtr)), iv(_iv), naming(std::move(_naming)), root(_root) {}
DirTraverse &DirTraverse::operator=(const DirTraverse &src) = default;
DirTraverse::~DirTraverse() {
dir.reset();
iv = 0;
naming.reset();
root = false;
}
static bool _nextName(struct dirent *&de, const std::shared_ptr<DIR> &dir,
int *fileType, ino_t *inode) {
de = ::readdir(dir.get());
if (de != nullptr) {
if (fileType != nullptr) {
#if defined(HAVE_DIRENT_D_TYPE)
*fileType = de->d_type;
#else
#warning "struct dirent.d_type not supported"
*fileType = 0;
#endif
}
if (inode != nullptr) {
*inode = de->d_ino;
}
return true;
}
if (fileType != nullptr) {
*fileType = 0;
}
return false;
}
std::string DirTraverse::nextPlaintextName(int *fileType, ino_t *inode) {
struct dirent *de = nullptr;
while (_nextName(de, dir, fileType, inode)) {
if (root && (strcmp(".encfs6.xml", de->d_name) == 0)) {
VLOG(1) << "skipping filename: " << de->d_name;
continue;
}
try {
uint64_t localIv = iv;
return naming->decodePath(de->d_name, &localIv);
} catch (encfs::Error &ex) {
// .. .problem decoding, ignore it and continue on to next name..
VLOG(1) << "error decoding filename: " << de->d_name;
}
}
return string();
}
std::string DirTraverse::nextInvalid() {
struct dirent *de = nullptr;
// find the first name which produces a decoding error...
while (_nextName(de, dir, (int *)nullptr, (ino_t *)nullptr)) {
if (root && (strcmp(".encfs6.xml", de->d_name) == 0)) {
VLOG(1) << "skipping filename: " << de->d_name;
continue;
}
try {
uint64_t localIv = iv;
naming->decodePath(de->d_name, &localIv);
continue;
} catch (encfs::Error &ex) {
return string(de->d_name);
}
}
return string();
}
struct RenameEl {
// ciphertext names
string oldCName;
string newCName; // intermediate name (not final cname)
// plaintext names
string oldPName;
string newPName;
bool isDirectory;
};
class RenameOp {
private:
DirNode *dn;
std::shared_ptr<list<RenameEl> > renameList;
list<RenameEl>::const_iterator last;
public:
RenameOp(DirNode *_dn, std::shared_ptr<list<RenameEl> > _renameList)
: dn(_dn), renameList(std::move(_renameList)) {
last = renameList->begin();
}
// destructor
~RenameOp();
RenameOp(const RenameOp &src) = delete; // copy contructor
RenameOp(RenameOp&& other) = delete; // move constructor
RenameOp& operator=(const RenameOp& other) = delete; // copy assignment
RenameOp& operator=(RenameOp&& other) = delete; // move assignment
explicit operator bool() const { return renameList != nullptr; }
bool apply();
void undo();
};
RenameOp::~RenameOp() {
if (renameList) {
// got a bunch of decoded filenames sitting in memory.. do a little
// cleanup before leaving..
list<RenameEl>::iterator it;
for (it = renameList->begin(); it != renameList->end(); ++it) {
it->oldPName.assign(it->oldPName.size(), ' ');
it->newPName.assign(it->newPName.size(), ' ');
}
}
}
bool RenameOp::apply() {
try {
while (last != renameList->end()) {
// backing store rename.
VLOG(1) << "renaming " << last->oldCName << " -> " << last->newCName;
struct stat st;
bool preserve_mtime = ::stat(last->oldCName.c_str(), &st) == 0;
// internal node rename..
dn->renameNode(last->oldPName.c_str(), last->newPName.c_str());
// rename on disk..
if (::rename(last->oldCName.c_str(), last->newCName.c_str()) == -1) {
int eno = errno;
RLOG(WARNING) << "Error renaming " << last->oldCName << ": "
<< strerror(eno);
dn->renameNode(last->newPName.c_str(), last->oldPName.c_str(), false);
return false;
}
if (preserve_mtime) {
struct utimbuf ut;
ut.actime = st.st_atime;
ut.modtime = st.st_mtime;
::utime(last->newCName.c_str(), &ut);
}
++last;
}
return true;
} catch (encfs::Error &err) {
RLOG(WARNING) << err.what();
return false;
}
}
void RenameOp::undo() {
VLOG(1) << "in undoRename";
if (last == renameList->begin()) {
VLOG(1) << "nothing to undo";
return; // nothing to undo
}
// list has to be processed backwards, otherwise we may rename
// directories and directory contents in the wrong order!
int undoCount = 0;
auto it = last;
while (it != renameList->begin()) {
--it;
VLOG(1) << "undo: renaming " << it->newCName << " -> " << it->oldCName;
::rename(it->newCName.c_str(), it->oldCName.c_str());
try {
dn->renameNode(it->newPName.c_str(), it->oldPName.c_str(), false);
} catch (encfs::Error &err) {
RLOG(WARNING) << err.what();
// continue on anyway...
}
++undoCount;
};
RLOG(WARNING) << "Undo rename count: " << undoCount;
}
DirNode::DirNode(EncFS_Context *_ctx, const string &sourceDir,
const FSConfigPtr &_config) {
pthread_mutex_init(&mutex, nullptr);
Lock _lock(mutex);
ctx = _ctx;
rootDir = sourceDir; // .. and fsConfig->opts->mountPoint have trailing slash
fsConfig = _config;
naming = fsConfig->nameCoding;
}
DirNode::~DirNode() = default;
bool DirNode::hasDirectoryNameDependency() const {
return naming ? naming->getChainedNameIV() : false;
}
string DirNode::rootDirectory() {
// don't update last access here, otherwise 'du' would cause lastAccess to
// be reset.
// chop off '/' terminator from root dir.
return string(rootDir, 0, rootDir.length() - 1);
}
bool DirNode::touchesMountpoint(const char *realPath) const {
const string &mountPoint = fsConfig->opts->mountPoint;
// compare mountPoint up to the leading slash.
// examples:
// mountPoint = /home/user/Junk/experiment/
// realPath = /home/user/Junk/experiment
// realPath = /home/user/Junk/experiment/abc
const ssize_t len = mountPoint.length() - 1;
if (mountPoint.compare(0, len, realPath, len) == 0) {
// if next character is a NUL or a slash, then we're referencing our
// mount point:
// .../experiment => true
// .../experiment/... => true
// .../experiment2/abc => false
return realPath[len] == '\0' || realPath[len] == '/';
}
return false;
}
/**
* Encrypt a plain-text file path to the ciphertext path with the
* ciphertext root directory name prefixed.
*
* Example:
* $ encfs -f -v cipher plain
* $ cd plain
* $ touch foobar
* cipherPath: /foobar encoded to cipher/NKAKsn2APtmquuKPoF4QRPxS
*/
string DirNode::cipherPath(const char *plaintextPath) {
return rootDir + naming->encodePath(plaintextPath);
}
/**
* Same as cipherPath(), but does not prefix the ciphertext root directory
*/
string DirNode::cipherPathWithoutRoot(const char *plaintextPath) {
return naming->encodePath(plaintextPath);
}
/**
* Return the decrypted version of cipherPath
*
* In reverse mode, returns the encrypted version of cipherPath
*/
string DirNode::plainPath(const char *cipherPath_) {
try {
// Handle special absolute path encodings.
char mark = '+';
string prefix = "/";
if (fsConfig->reverseEncryption) {
mark = '/';
prefix = "+";
}
if (cipherPath_[0] == mark) {
return prefix +
naming->decodeName(cipherPath_ + 1, strlen(cipherPath_ + 1));
}
// Default.
return naming->decodePath(cipherPath_);
} catch (encfs::Error &err) {
RLOG(ERROR) << "decode err: " << err.what();
return string();
}
}
string DirNode::relativeCipherPath(const char *plaintextPath) {
try {
// use '+' prefix to indicate special decoding.
char mark = fsConfig->reverseEncryption ? '+' : '/';
if (plaintextPath[0] == mark) {
return string(fsConfig->reverseEncryption ? "/" : "+") +
naming->encodeName(plaintextPath + 1, strlen(plaintextPath + 1));
}
return naming->encodePath(plaintextPath);
} catch (encfs::Error &err) {
RLOG(ERROR) << "encode err: " << err.what();
return string();
}
}
DirTraverse DirNode::openDir(const char *plaintextPath) {
string cyName = rootDir + naming->encodePath(plaintextPath);
DIR *dir = ::opendir(cyName.c_str());
if (dir == nullptr) {
int eno = errno;
VLOG(1) << "opendir error " << strerror(eno);
return DirTraverse(shared_ptr<DIR>(), 0, std::shared_ptr<NameIO>(), false);
}
std::shared_ptr<DIR> dp(dir, DirDeleter());
uint64_t iv = 0;
// if we're using chained IV mode, then compute the IV at this
// directory level..
try {
if (naming->getChainedNameIV()) {
naming->encodePath(plaintextPath, &iv);
}
} catch (encfs::Error &err) {
RLOG(ERROR) << "encode err: " << err.what();
}
return DirTraverse(dp, iv, naming, (strlen(plaintextPath) == 1));
}
bool DirNode::genRenameList(list<RenameEl> &renameList, const char *fromP,
const char *toP) {
uint64_t fromIV = 0, toIV = 0;
// compute the IV for both paths
string fromCPart = naming->encodePath(fromP, &fromIV);
string toCPart = naming->encodePath(toP, &toIV);
// where the files live before the rename..
string sourcePath = rootDir + fromCPart;
// ok..... we wish it was so simple.. should almost never happen
if (fromIV == toIV) {
return true;
}
// generate the real destination path, where we expect to find the files..
VLOG(1) << "opendir " << sourcePath;
std::shared_ptr<DIR> dir =
std::shared_ptr<DIR>(opendir(sourcePath.c_str()), DirDeleter());
if (!dir) {
return false;
}
struct dirent *de = nullptr;
while ((de = ::readdir(dir.get())) != nullptr) {
// decode the name using the oldIV
uint64_t localIV = fromIV;
string plainName;
if ((de->d_name[0] == '.') &&
((de->d_name[1] == '\0') ||
((de->d_name[1] == '.') && (de->d_name[2] == '\0')))) {
// skip "." and ".."
continue;
}
try {
plainName = naming->decodePath(de->d_name, &localIV);
} catch (encfs::Error &ex) {
// if filename can't be decoded, then ignore it..
continue;
}
// any error in the following will trigger a rename failure.
try {
// re-encode using the new IV..
localIV = toIV;
string newName = naming->encodePath(plainName.c_str(), &localIV);
// store rename information..
string oldFull = sourcePath + '/' + de->d_name;
string newFull = sourcePath + '/' + newName;
RenameEl ren;
ren.oldCName = oldFull;
ren.newCName = newFull;
ren.oldPName = string(fromP) + '/' + plainName;
ren.newPName = string(toP) + '/' + plainName;
bool isDir;
#if defined(HAVE_DIRENT_D_TYPE)
if (de->d_type != DT_UNKNOWN) {
isDir = (de->d_type == DT_DIR);
} else
#endif
{
isDir = isDirectory(oldFull.c_str());
}
ren.isDirectory = isDir;
if (isDir) {
// recurse.. We want to add subdirectory elements before the
// parent, as that is the logical rename order..
if (!genRenameList(renameList, ren.oldPName.c_str(),
ren.newPName.c_str())) {
return false;
}
}
VLOG(1) << "adding file " << oldFull << " to rename list";
renameList.push_back(ren);
} catch (encfs::Error &err) {
// We can't convert this name, because we don't have a valid IV for
// it (or perhaps a valid key).. It will be inaccessible..
RLOG(WARNING) << "Aborting rename: error on file: "
<< fromCPart.append(1, '/').append(de->d_name);
RLOG(WARNING) << err.what();
// abort.. Err on the side of safety and disallow rename, rather
// then loosing files..
return false;
}
}
return true;
}
/*
A bit of a pain.. If a directory is renamed in a filesystem with
directory initialization vector chaining, then we have to recursively
rename every descendent of this directory, as all initialization vectors
will have changed..
Returns a list of renamed items on success, a null list on failure.
*/
std::shared_ptr<RenameOp> DirNode::newRenameOp(const char *fromP,
const char *toP) {
// Do the rename in two stages to avoid chasing our tail
// Undo everything if we encounter an error!
std::shared_ptr<list<RenameEl> > renameList(new list<RenameEl>);
if (!genRenameList(*renameList.get(), fromP, toP)) {
RLOG(WARNING) << "Error during generation of recursive rename list";
return std::shared_ptr<RenameOp>();
}
return std::make_shared<RenameOp>(this, renameList);
}
int DirNode::mkdir(const char *plaintextPath, mode_t mode, uid_t uid,
gid_t gid) {
string cyName = rootDir + naming->encodePath(plaintextPath);
rAssert(!cyName.empty());
VLOG(1) << "mkdir on " << cyName;
// if uid or gid are set, then that should be the directory owner
int olduid = -1;
int oldgid = -1;
if (gid != 0) {
oldgid = setfsgid(gid);
if (oldgid == -1) {
int eno = errno;
RLOG(DEBUG) << "setfsgid error: " << strerror(eno);
return -EPERM;
}
}
if (uid != 0) {
olduid = setfsuid(uid);
if (olduid == -1) {
int eno = errno;
RLOG(DEBUG) << "setfsuid error: " << strerror(eno);
return -EPERM;
}
}
int res = ::mkdir(cyName.c_str(), mode);
if (res == -1) {
int eno = errno;
RLOG(WARNING) << "mkdir error on " << cyName << " mode " << mode << ": "
<< strerror(eno);
res = -eno;
}
if (olduid >= 0) {
if(setfsuid(olduid) == -1) {
int eno = errno;
RLOG(DEBUG) << "setfsuid back error: " << strerror(eno);
// does not return error here as initial setfsuid worked
}
}
if (oldgid >= 0) {
if(setfsgid(oldgid) == -1) {
int eno = errno;
RLOG(DEBUG) << "setfsgid back error: " << strerror(eno);
// does not return error here as initial setfsgid worked
}
}
return res;
}
int DirNode::rename(const char *fromPlaintext, const char *toPlaintext) {
Lock _lock(mutex);
string fromCName = rootDir + naming->encodePath(fromPlaintext);
string toCName = rootDir + naming->encodePath(toPlaintext);
rAssert(!fromCName.empty());
rAssert(!toCName.empty());
VLOG(1) << "rename " << fromCName << " -> " << toCName;
std::shared_ptr<FileNode> toNode = findOrCreate(toPlaintext);
std::shared_ptr<RenameOp> renameOp;
if (hasDirectoryNameDependency() && isDirectory(fromCName.c_str())) {
VLOG(1) << "recursive rename begin";
renameOp = newRenameOp(fromPlaintext, toPlaintext);
if (!renameOp || !renameOp->apply()) {
if (renameOp) {
renameOp->undo();
}
RLOG(WARNING) << "rename aborted";
return -EACCES;
}
VLOG(1) << "recursive rename end";
}
int res = 0;
try {
struct stat st;
bool preserve_mtime = ::stat(fromCName.c_str(), &st) == 0;
renameNode(fromPlaintext, toPlaintext);
res = ::rename(fromCName.c_str(), toCName.c_str());
if (res == -1) {
// undo
res = -errno;
renameNode(toPlaintext, fromPlaintext, false);
if (renameOp) {
renameOp->undo();
}
}
else {
#ifdef __CYGWIN__
// When renaming a file, Windows first opens it, renames it and then closes it
// We then must decrease the target openFiles count
// We could recreate the source so that close will not (silently) fails,
// however it will update modification time of the file, so break what we do below.
// Let's simply warn in eraseNode().
if (!isDirectory(toCName.c_str())) {
std::shared_ptr<FileNode> toNode = findOrCreate(toPlaintext);
ctx->eraseNode(toPlaintext, toNode);
//ctx->putNode(fromPlaintext, toNode);
}
#endif
if (preserve_mtime) {
struct utimbuf ut;
ut.actime = st.st_atime;
ut.modtime = st.st_mtime;
::utime(toCName.c_str(), &ut);
}
}
} catch (encfs::Error &err) {
// exception from renameNode, just show the error and continue..
RLOG(WARNING) << err.what();
res = -EIO;
}
if (res != 0) {
VLOG(1) << "rename failed: " << strerror(-res);
}
return res;
}
int DirNode::link(const char *to, const char *from) {
Lock _lock(mutex);
string toCName = rootDir + naming->encodePath(to);
string fromCName = rootDir + naming->encodePath(from);
rAssert(!toCName.empty());
rAssert(!fromCName.empty());
VLOG(1) << "link " << fromCName << " -> " << toCName;
int res = -EPERM;
if (fsConfig->config->externalIVChaining) {
VLOG(1) << "hard links not supported with external IV chaining!";
} else {
res = ::link(toCName.c_str(), fromCName.c_str());
if (res == -1) {
res = -errno;
} else {
res = 0;
}
}
return res;
}
/*
The node is keyed by filename, so a rename means the internal node names
must be changed.
*/
std::shared_ptr<FileNode> DirNode::renameNode(const char *from,
const char *to) {
return renameNode(from, to, true);
}
std::shared_ptr<FileNode> DirNode::renameNode(const char *from, const char *to,
bool forwardMode) {
std::shared_ptr<FileNode> node = findOrCreate(from);
if (node) {
uint64_t newIV = 0;
string cname = rootDir + naming->encodePath(to, &newIV);
VLOG(1) << "renaming internal node " << node->cipherName() << " -> "
<< cname;
if (node->setName(to, cname.c_str(), newIV, forwardMode)) {
if (ctx != nullptr) {
ctx->renameNode(from, to);
}
} else {
// rename error! - put it back
RLOG(ERROR) << "renameNode failed";
throw Error("Internal node name change failed!");
}
}
return node;
}
// findOrCreate checks if we already have a FileNode for "plainName" and
// creates a new one if we don't. Returns the FileNode.
std::shared_ptr<FileNode> DirNode::findOrCreate(const char *plainName) {
std::shared_ptr<FileNode> node;
// See if we already have a FileNode for this path.
if (ctx != nullptr) {
node = ctx->lookupNode(plainName);
// If we don't, create a new one.
if (!node) {
uint64_t iv = 0;
string cipherName = naming->encodePath(plainName, &iv);
uint64_t fuseFh = ctx->nextFuseFh();
node.reset(new FileNode(this, fsConfig, plainName,
(rootDir + cipherName).c_str(), fuseFh));
if (fsConfig->config->externalIVChaining) {
node->setName(nullptr, nullptr, iv);
}
VLOG(1) << "created FileNode for " << node->cipherName();
}
}
return node;
}
shared_ptr<FileNode> DirNode::lookupNode(const char *plainName,
const char * /* requestor */) {
Lock _lock(mutex);
return findOrCreate(plainName);
}
/*
Similar to lookupNode, except that we also call open() and only return a
node on sucess. This is done in one step to avoid any race conditions
with the stored state of the file.
"result" is set to -1 on failure, a value >= 0 on success.
*/
std::shared_ptr<FileNode> DirNode::openNode(const char *plainName,
const char *requestor, int flags,
int *result) {
(void)requestor;
rAssert(result != nullptr);
Lock _lock(mutex);
std::shared_ptr<FileNode> node = findOrCreate(plainName);
if (node && (*result = node->open(flags)) >= 0) {
return node;
}
return std::shared_ptr<FileNode>();
}
int DirNode::unlink(const char *plaintextName) {
string cyName = naming->encodePath(plaintextName);
VLOG(1) << "unlink " << cyName;
Lock _lock(mutex);
// Windows does not allow deleting opened files, so no need to check
// There is this "issue" however : https://github.com/billziss-gh/winfsp/issues/157
#ifndef __CYGWIN__
if ((ctx != nullptr) && ctx->lookupNode(plaintextName)) {
// If FUSE is running with "hard_remove" option where it doesn't
// hide open files for us, then we can't allow an unlink of an open
// file..
RLOG(WARNING) << "Refusing to unlink open file: " << cyName
<< ", hard_remove option "
"is probably in effect";
return -EBUSY;
}
#endif
int res = 0;
string fullName = rootDir + cyName;
res = ::unlink(fullName.c_str());
if (res == -1) {
res = -errno;
VLOG(1) << "unlink error: " << strerror(-res);
}
return res;
}
} // namespace encfs
|
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2016 Sky UK
*
* 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: DobbyBundleConfig.cpp
*
*/
#include "DobbyBundleConfig.h"
#include "IDobbyUtils.h"
#include <array>
#include <grp.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/sysinfo.h>
// -----------------------------------------------------------------------------
/**
* @brief Constructor that parses an OCI bundle's config file to be used by Dobby.
* Plugins under 'rdkPlugins' and 'legacyPlugins' are parsed if found (OCI bundle*).
*
* @param[in] utils The daemon utils object.
* @param[in] settings Dobby settings object.
* @param[in] id Container ID.
* @param[in] bundlePath Path to OCI bundle.
*/
DobbyBundleConfig::DobbyBundleConfig(const std::shared_ptr<IDobbyUtils>& utils,
const std::shared_ptr<const IDobbySettings>& settings,
const ContainerId& id,
const std::string& bundlePath)
: mUtilities(utils)
, mSettings(settings)
, mConf(nullptr)
, mUserId(-1)
, mGroupId(-1)
, mRestartOnCrash(false)
, mGpuEnabled(false)
, mGpuMemLimit(GPU_MEMLIMIT_DEFAULT)
, mSystemDbus(IDobbyIPCUtils::BusType::NoneBus)
, mSessionDbus(IDobbyIPCUtils::BusType::NoneBus)
, mDebugDbus(IDobbyIPCUtils::BusType::NoneBus)
, mConsoleDisabled(true)
, mConsoleLimit(-1)
, mRootfsPath("rootfs")
{
// because jsoncpp can throw exceptions if we fail to check the json types
// before performing conversions we wrap the whole parse operation in a
// try / catch
try
{
// go and parse the OCI config file for plugins to use
mValid = parseOCIConfig(bundlePath);
// deserialise config.json
parser_error err;
std::string configPath = bundlePath + "/config.json";
mConf = std::shared_ptr<rt_dobby_schema>(
rt_dobby_schema_parse_file(configPath.c_str(), nullptr, &err),
free_rt_dobby_schema);
if (mConf.get() == nullptr || err)
{
AI_LOG_ERROR_EXIT("Failed to parse bundle config, err '%s'", err);
mValid = false;
}
else
{
// convert OCI config to compliant using libocispec
mValid &= DobbyConfig::convertToCompliant(id, mConf, bundlePath);
}
}
catch (const Json::Exception& e)
{
AI_LOG_ERROR("exception thrown during config parsing - %s", e.what());
mValid = false;
}
}
DobbyBundleConfig::~DobbyBundleConfig()
{
}
bool DobbyBundleConfig::isValid() const
{
return mValid;
}
uid_t DobbyBundleConfig::userId() const
{
return mUserId;
}
gid_t DobbyBundleConfig::groupId() const
{
return mGroupId;
}
const std::string& DobbyBundleConfig::rootfsPath() const
{
return mRootfsPath;
}
bool DobbyBundleConfig::restartOnCrash() const
{
return mRestartOnCrash;
}
bool DobbyBundleConfig::gpuEnabled() const
{
return mGpuEnabled;
}
size_t DobbyBundleConfig::gpuMemLimit() const
{
return mGpuMemLimit;
}
IDobbyIPCUtils::BusType DobbyBundleConfig::systemDbus() const
{
return mSystemDbus;
}
IDobbyIPCUtils::BusType DobbyBundleConfig::sessionDbus() const
{
return mSessionDbus;
}
IDobbyIPCUtils::BusType DobbyBundleConfig::debugDbus() const
{
return mDebugDbus;
}
bool DobbyBundleConfig::consoleDisabled() const
{
return mConsoleDisabled;
}
ssize_t DobbyBundleConfig::consoleLimit() const
{
return mConsoleLimit;
}
const std::string& DobbyBundleConfig::consolePath() const
{
return mConsolePath;
}
const std::map<std::string, Json::Value>& DobbyBundleConfig::legacyPlugins() const
{
return mLegacyPlugins;
}
const std::map<std::string, Json::Value>& DobbyBundleConfig::rdkPlugins() const
{
return mRdkPlugins;
}
const std::list<std::string> DobbyBundleConfig::sysHooks() const
{
return mEnabledSysHooks;
}
std::shared_ptr<rt_dobby_schema> DobbyBundleConfig::config() const
{
return mValid ? std::shared_ptr<rt_dobby_schema>(mConf) : nullptr;
}
// -----------------------------------------------------------------------------
/**
* @brief Parses the bundle config's contents that are needed by plugins
*
* The function is atomic, therefore if it returns true you can
* guarantee it stuck and will be set for the lifetime of the function.
*
* @param[in] bundlePath path to the container's OCI bundle
*
* @return true if the path was set, otherwise false.
*/
bool DobbyBundleConfig::parseOCIConfig(const std::string& bundlePath)
{
AI_LOG_FN_ENTRY();
std::lock_guard<std::mutex> locker(mLock);
// Parse config.json to a Json::Value type
std::ifstream bundleConfigFs(bundlePath + "/config.json", std::ifstream::binary);
if (!bundleConfigFs)
{
AI_LOG_ERROR_EXIT("failed to open bundle config file at '%s'", bundlePath.c_str());
return false;
}
bundleConfigFs.seekg(0, std::ifstream::end);
ssize_t length = bundleConfigFs.tellg();
bundleConfigFs.seekg(0, std::ifstream::beg);
char* buffer = new char[length];
bundleConfigFs.read(buffer, length);
std::string jsonConfigString(buffer, length);
delete [] buffer;
std::istringstream sin(jsonConfigString);
sin >> mConfig;
// Populate the object with any needed values
mUserId = mConfig["process"]["user"]["uid"].asInt();
mGroupId = mConfig["process"]["user"]["gid"].asInt();
mRootfsPath = mConfig["root"]["path"].asString();
// Parse legacy plugins if present & not null
if (mConfig.isMember("legacyPlugins") && mConfig["legacyPlugins"].isObject())
{
if (!processLegacyPlugins(mConfig["legacyPlugins"]))
{
return false;
}
}
// Parse rdk plugins if present & not null
if (mConfig.isMember("rdkPlugins") && mConfig["rdkPlugins"].isObject())
{
Json::Value rdkPlugins = mConfig["rdkPlugins"];
if (!rdkPlugins.isObject())
{
AI_LOG_ERROR("invalid rdkPlugins field");
}
for (const auto &rdkPluginName : rdkPlugins.getMemberNames())
{
mRdkPlugins.emplace(rdkPluginName, rdkPlugins[rdkPluginName]);
}
// Parse Logging plugin
if (rdkPlugins.isMember(RDK_LOGGING_PLUGIN_NAME))
{
if (!processLogging(rdkPlugins[RDK_LOGGING_PLUGIN_NAME]))
{
return false;
}
}
// Parse GPU plugin
if (rdkPlugins.isMember(RDK_GPU_PLUGIN_NAME))
{
if (!processGpu(rdkPlugins[RDK_GPU_PLUGIN_NAME]))
{
return false;
}
}
// Parse IPC plugin
if (rdkPlugins.isMember(RDK_IPC_PLUGIN_NAME))
{
if (!processIpc(rdkPlugins[RDK_IPC_PLUGIN_NAME]))
{
return false;
}
}
// Parse DRM plugin
if (rdkPlugins.isMember(RDK_DRM_PLUGIN_NAME))
{
if (!processDrm(rdkPlugins[RDK_DRM_PLUGIN_NAME]))
{
return false;
}
}
// Parse RDK Services plugin
if (rdkPlugins.isMember(RDK_RDKSERVICES_PLUGIN_NAME))
{
if (!processRdkServices(rdkPlugins[RDK_RDKSERVICES_PLUGIN_NAME]))
{
return false;
}
}
}
// enable syshooks for use whilst RDK plugins are developed
setSysHooksAndRdkPlugins();
AI_LOG_FN_EXIT();
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Processes the logging plugin field
*
* Example json in rdkPlugins.logging:
*
* "data":{
* "console": {
* "enabled":true,
* "path":"/tmp/data/console.log",
* "limit":1048576
* }
* }
*
* The console settings aren't given to the crun, instead it determines the
* type of stream that we attach to read the console output.
*
* Typically on debug builds the console will be redirected to a file on the
* flash. On release builds it is redirected to /dev/null.
*
* If console is null, then the terminal stdin / stdout & stderr are all
* redirected to /dev/null. If not null then stdout & stderr are redirected
* into the supplied file, with an optional size limit on it.
*
* @param[in] value The rdkPlugins.logging field from extended bundle
* config.
*
* @return true if correctly processed the value, otherwise false.
*/
bool DobbyBundleConfig::processLogging(const Json::Value& value)
{
if (!value.isObject() || !value.isMember("data") || !value["data"].isObject())
{
AI_LOG_ERROR("invalid rdkPlugin.logging.data field");
return false;
}
Json::Value data = value["data"];
if (data.isMember("console"))
{
const Json::Value& consoleData = data["console"];
if (!consoleData.isObject())
{
AI_LOG_ERROR("invalid logging.data.console field");
return false;
}
if (consoleData["enabled"].asBool() == false)
{
mConsoleDisabled = true;
return true;
}
const Json::Value& path = consoleData["path"];
if (path.isNull())
{
mConsoleDisabled = true;
}
else if (path.isString())
{
mConsolePath = path.asString();
}
else
{
AI_LOG_ERROR("invalid logging.data.console.path field");
return false;
}
const Json::Value& limit = consoleData["limit"];
if (limit.isNull())
{
mConsoleLimit = -1;
}
else if (limit.isIntegral())
{
mConsoleLimit = limit.asInt();
mConsoleLimit = std::max<ssize_t>(mConsoleLimit, -1);
}
else
{
AI_LOG_ERROR("invalid logging.data.console.limit field");
return false;
}
mConsoleDisabled = false;
}
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Processes the ipc plugin field
*
* Example json in rdkPlugins.ipc:
*
* "data":{
* "session": "ai-public",
* "system": "system",
* "debug": "ai-private"
* }
*
* This config options allow you to specify what bus to map into the container
* and what to call it inside the container.
*
* @param[in] value The rdkPlugins.ipc field from extended bundle config.
*
* @return true if correctly processed the value, otherwise false.
*/
bool DobbyBundleConfig::processIpc(const Json::Value& value)
{
if (!value.isObject() || !value.isMember("data") || !value["data"].isObject())
{
AI_LOG_ERROR("invalid rdkPlugin.ipc.data field");
return false;
}
Json::Value data = value["data"];
static const std::map<std::string, IDobbyIPCUtils::BusType> busTypes =
{
{ "system", IDobbyIPCUtils::BusType::SystemBus },
{ "ai-public", IDobbyIPCUtils::BusType::AIPublicBus },
{ "ai-private", IDobbyIPCUtils::BusType::AIPrivateBus },
};
// process the system dbus field
{
const Json::Value& system = data["system"];
if (system.isString())
{
std::map<std::string, IDobbyIPCUtils::BusType>::const_iterator it = busTypes.find(system.asString());
if (it == busTypes.end())
{
AI_LOG_ERROR("invalid 'ipc.data.system' field");
return false;
}
mSystemDbus = it->second;
}
else if (!system.isNull())
{
AI_LOG_ERROR("invalid 'ipc.data.system' field");
return false;
}
}
// process the session dbus field
{
const Json::Value& session = data["session"];
if (session.isString())
{
std::map<std::string, IDobbyIPCUtils::BusType>::const_iterator it = busTypes.find(session.asString());
if (it == busTypes.end())
{
AI_LOG_ERROR("invalid 'ipc.data.session' field");
return false;
}
mSessionDbus = it->second;
}
else if (!session.isNull())
{
AI_LOG_ERROR("invalid 'ipc.data.session' field");
return false;
}
}
#if (AI_BUILD_TYPE == AI_DEBUG)
// process the debug dbus field
{
const Json::Value& debug = data["debug"];
if (debug.isString())
{
std::map<std::string, IDobbyIPCUtils::BusType>::const_iterator it = busTypes.find(debug.asString());
if (it == busTypes.end())
{
AI_LOG_ERROR("invalid 'ipc.data.debug' field");
return false;
}
mDebugDbus = it->second;
}
else if (!debug.isNull())
{
AI_LOG_ERROR("invalid 'ipc.data.debug' field");
return false;
}
}
#endif
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Processes the gpu plugin field
*
* Example json in rdkPlugins.gpu:
*
* "data":{
* "memory": 67108864
* }
*
* @param[in] value The rdkPlugins.gpu field from extended bundle config.
*
* @return true if correctly processed the value, otherwise false.
*/
bool DobbyBundleConfig::processGpu(const Json::Value& value)
{
if (!value.isObject() || !value.isMember("data") || !value["data"].isObject())
{
AI_LOG_ERROR("invalid rdkPlugin.gpu.data field");
return false;
}
Json::Value data = value["data"];
const Json::Value& memLimit = data["memory"];
mGpuEnabled = true;
if (memLimit.isIntegral())
{
mGpuMemLimit = memLimit.asUInt();
}
else if (memLimit.isNull())
{
mGpuMemLimit = GPU_MEMLIMIT_DEFAULT;
}
else
{
AI_LOG_ERROR("invalid 'gpu.data.memory' field");
return false;
}
// lazily init the GPU dev nodes mapping - we used to do this at start-up
// but hit an issue on broadcom platforms where the dev nodes aren't
// created until the gpu library is used
if (!mInitialisedGpuDevNodes)
{
DobbyConfig::initGpuDevNodes(mSettings->gpuDeviceNodes());
}
// check if a special 'GPU' group id is needed
const int gpuGroupId = mSettings->gpuGroupId();
if (gpuGroupId > 0)
{
// If gidMappings doesn't exist in bundle config, add it
if (!mConfig["linux"]["gidMappings"].isArray())
{
mConfig["linux"]["gidMappings"] = Json::arrayValue;
}
Json::Value newGid;
newGid["hostID"] = gpuGroupId;
newGid["containerID"] = gpuGroupId;
newGid["size"] = 1;
mConfig["linux"]["gidMappings"].append(newGid);
}
// add any extra mounts (i.e. ipc sockets, shared memory files, etc)
Json::Value newMount;
if (mSettings->gpuHasExtraMounts())
{
const std::list<IDobbySettings::GpuExtraMount> extraMounts =
mSettings->gpuExtraMounts();
for (const IDobbySettings::GpuExtraMount& extraMount : extraMounts)
{
newMount["destination"] = extraMount.source;
newMount["type"] = extraMount.target;
newMount["source"] = extraMount.type;
for (const std::string& flag : extraMount.flags)
{
newMount["options"].append(flag);
}
mConfig["mounts"].append(newMount);
}
}
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Processes the legacy plugins field.
*
* This parses the legacy Dobby plugins to mPlugins.
*
* @param[in] value The legacyPlugins field from extended bundle config.
*
* @return true if correctly processed the value, otherwise false.
*/
bool DobbyBundleConfig::processLegacyPlugins(const Json::Value& value)
{
if (!value.isObject())
{
AI_LOG_ERROR("invalid legacyPlugins field");
return false;
}
for (const std::string& id : value.getMemberNames())
{
const Json::Value& plugin = value.get(id, "");
if (!plugin.isObject())
{
AI_LOG_ERROR("invalid legacyPlugin entry %s", id.c_str());
return false;
}
// the name field must be a string
const Json::Value& name = id;
if (!name.isString())
{
AI_LOG_ERROR("invalid legacyPlugin.name entry %s", id.c_str());
return false;
}
// the data can be anything, we don't place any restrictions on it since
// it's just passed to the hook library for processing
Json::Value data = plugin["data"];
// add the hook to the list
mLegacyPlugins.emplace(name.asString(), std::move(data));
}
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Processes the rdkServices plugin field
*
* Example json in rdkPlugins.rdkServices:
*
* "data":{
* }
*
* @param[in] value The rdkPlugins.rdkServices field from extended bundle
* config.
*
* @return true if correctly processed the value, otherwise false.
*/
bool DobbyBundleConfig::processRdkServices(const Json::Value& value)
{
AI_LOG_ERROR("rdkServices plugin is not supported yet.");
return false;
}
// -----------------------------------------------------------------------------
/**
* @brief Processes the drm plugin field
*
* Example json in rdkPlugins.drm:
*
* "data":{
* }
*
* @param[in] value The rdkPlugins.drm field from extended bundle config.
*
* @return true if correctly processed the value, otherwise false.
*/
bool DobbyBundleConfig::processDrm(const Json::Value& value)
{
AI_LOG_ERROR("drm plugin is not supported yet.");
return false;
}
// -----------------------------------------------------------------------------
/**
* @brief Sets the placeholder Dobby syshooks and removes RDK plugins in
* development.
*
* NOTE: This should only be used until the RDK plugin is fully developed.
*
* With this in place, we can have syshooks turned on or off selectively.
*/
void DobbyBundleConfig::setSysHooksAndRdkPlugins(void)
{
// iterate through all rdk plugins in development to decide which syshooks
// should still be used. The RDK plugins are listed in the static variable
// DobbyConfig::mRdkPluginsInDevelopment
std::map<std::string, std::list<std::string>>::const_iterator it = mRdkPluginsInDevelopment.begin();
for (; it != mRdkPluginsInDevelopment.end(); ++it)
{
std::string rdkPluginName = it->first;
std::list<std::string> pluginSysHooks = it->second;
// if rdk plugin is turned on for this container, use syshooks instead
if (mRdkPlugins.find(rdkPluginName) != mRdkPlugins.end())
{
mRdkPlugins.erase(rdkPluginName);
std::list<std::string>::const_iterator jt = pluginSysHooks.begin();
for (; jt != pluginSysHooks.end(); ++jt)
{
mEnabledSysHooks.emplace_back(*jt);
}
}
}
}
|
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/Sound.hpp>
#include <catch2/catch.hpp>
#include <chrono>
#include <thread>
std::filesystem::path GetResourceDir();
SCENARIO("Sound", "[AUDIO][SOUND]")
{
GIVEN("A sound")
{
Nz::Sound sound;
WHEN("We load our sound")
{
REQUIRE(sound.LoadFromFile(GetResourceDir() / "Engine/Audio/Cat.flac"));
THEN("We can ask the informations of the file")
{
CHECK(sound.GetDuration() == 8192);
CHECK(sound.GetStatus() == Nz::SoundStatus::Stopped);
CHECK_FALSE(sound.IsLooping());
CHECK(sound.IsPlayable());
CHECK(sound.IsSpatializationEnabled());
CHECK(sound.GetMinDistance() == 1.f);
CHECK(sound.GetPitch() == 1.f);
CHECK(sound.GetPlayingOffset() == 0);
CHECK(sound.GetPosition() == Nz::Vector3f::Zero());
CHECK(sound.GetVelocity() == Nz::Vector3f::Zero());
CHECK(sound.GetVolume() == 1.f);
}
THEN("We can play it and get the time offset")
{
Nz::Audio::Instance()->GetDefaultDevice()->SetGlobalVolume(0.f);
sound.Play();
std::this_thread::sleep_for(std::chrono::seconds(1));
CHECK(sound.GetPlayingOffset() >= 950);
std::this_thread::sleep_for(std::chrono::milliseconds(200));
CHECK(sound.GetPlayingOffset() <= 1500);
sound.Pause();
CHECK(sound.GetStatus() == Nz::SoundStatus::Paused);
sound.SetPlayingOffset(3500);
CHECK(sound.GetPlayingOffset() == 3500);
Nz::Audio::Instance()->GetDefaultDevice()->SetGlobalVolume(100.f);
}
}
}
}
|
/****************************************************************************
** Meta object code from reading C++ file 'rvcalc.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../CroCo/rvcalc.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'rvcalc.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_RVCalc_t {
QByteArrayData data[20];
char stringdata0[429];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_RVCalc_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_RVCalc_t qt_meta_stringdata_RVCalc = {
{
QT_MOC_LITERAL(0, 0, 6), // "RVCalc"
QT_MOC_LITERAL(1, 7, 31), // "on_doubleSpinBox_9_valueChanged"
QT_MOC_LITERAL(2, 39, 0), // ""
QT_MOC_LITERAL(3, 40, 23), // "on_pushButton_2_clicked"
QT_MOC_LITERAL(4, 64, 25), // "on_lineEdit_2_textChanged"
QT_MOC_LITERAL(5, 90, 23), // "on_spinBox_valueChanged"
QT_MOC_LITERAL(6, 114, 21), // "on_checkBox_3_clicked"
QT_MOC_LITERAL(7, 136, 21), // "on_checkBox_4_clicked"
QT_MOC_LITERAL(8, 158, 23), // "on_pushButton_3_clicked"
QT_MOC_LITERAL(9, 182, 24), // "on_lineEdit_4_textEdited"
QT_MOC_LITERAL(10, 207, 24), // "on_lineEdit_5_textEdited"
QT_MOC_LITERAL(11, 232, 23), // "on_pushButton_4_clicked"
QT_MOC_LITERAL(12, 256, 23), // "on_pushButton_5_clicked"
QT_MOC_LITERAL(13, 280, 23), // "on_pushButton_6_clicked"
QT_MOC_LITERAL(14, 304, 8), // "findroot"
QT_MOC_LITERAL(15, 313, 23), // "on_pushButton_7_clicked"
QT_MOC_LITERAL(16, 337, 21), // "on_checkBox_6_clicked"
QT_MOC_LITERAL(17, 359, 21), // "on_checkBox_7_clicked"
QT_MOC_LITERAL(18, 381, 23), // "on_pushButton_8_clicked"
QT_MOC_LITERAL(19, 405, 23) // "on_pushButton_9_clicked"
},
"RVCalc\0on_doubleSpinBox_9_valueChanged\0"
"\0on_pushButton_2_clicked\0"
"on_lineEdit_2_textChanged\0"
"on_spinBox_valueChanged\0on_checkBox_3_clicked\0"
"on_checkBox_4_clicked\0on_pushButton_3_clicked\0"
"on_lineEdit_4_textEdited\0"
"on_lineEdit_5_textEdited\0"
"on_pushButton_4_clicked\0on_pushButton_5_clicked\0"
"on_pushButton_6_clicked\0findroot\0"
"on_pushButton_7_clicked\0on_checkBox_6_clicked\0"
"on_checkBox_7_clicked\0on_pushButton_8_clicked\0"
"on_pushButton_9_clicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_RVCalc[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
18, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 104, 2, 0x08 /* Private */,
3, 0, 105, 2, 0x08 /* Private */,
4, 0, 106, 2, 0x08 /* Private */,
5, 0, 107, 2, 0x08 /* Private */,
6, 0, 108, 2, 0x08 /* Private */,
7, 0, 109, 2, 0x08 /* Private */,
8, 0, 110, 2, 0x08 /* Private */,
9, 0, 111, 2, 0x08 /* Private */,
10, 0, 112, 2, 0x08 /* Private */,
11, 0, 113, 2, 0x08 /* Private */,
12, 0, 114, 2, 0x08 /* Private */,
13, 0, 115, 2, 0x08 /* Private */,
14, 0, 116, 2, 0x08 /* Private */,
15, 0, 117, 2, 0x08 /* Private */,
16, 0, 118, 2, 0x08 /* Private */,
17, 0, 119, 2, 0x08 /* Private */,
18, 0, 120, 2, 0x08 /* Private */,
19, 0, 121, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void RVCalc::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
RVCalc *_t = static_cast<RVCalc *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_doubleSpinBox_9_valueChanged(); break;
case 1: _t->on_pushButton_2_clicked(); break;
case 2: _t->on_lineEdit_2_textChanged(); break;
case 3: _t->on_spinBox_valueChanged(); break;
case 4: _t->on_checkBox_3_clicked(); break;
case 5: _t->on_checkBox_4_clicked(); break;
case 6: _t->on_pushButton_3_clicked(); break;
case 7: _t->on_lineEdit_4_textEdited(); break;
case 8: _t->on_lineEdit_5_textEdited(); break;
case 9: _t->on_pushButton_4_clicked(); break;
case 10: _t->on_pushButton_5_clicked(); break;
case 11: _t->on_pushButton_6_clicked(); break;
case 12: _t->findroot(); break;
case 13: _t->on_pushButton_7_clicked(); break;
case 14: _t->on_checkBox_6_clicked(); break;
case 15: _t->on_checkBox_7_clicked(); break;
case 16: _t->on_pushButton_8_clicked(); break;
case 17: _t->on_pushButton_9_clicked(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject RVCalc::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_RVCalc.data,
qt_meta_data_RVCalc, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *RVCalc::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *RVCalc::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_RVCalc.stringdata0))
return static_cast<void*>(const_cast< RVCalc*>(this));
return QDialog::qt_metacast(_clname);
}
int RVCalc::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 18)
qt_static_metacall(this, _c, _id, _a);
_id -= 18;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 18)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 18;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
// -----------------------------------------------------------------------------
//
// Copyright (C) The BioDynaMo Project.
// 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include "default_force.h"
#include "backend.h"
#include "cell.h"
#include "compile_time_param.h"
#include "gtest/gtest.h"
#include "neuroscience/compile_time_param.h"
#include "neuroscience/neurite_element.h"
#include "unit/test_util.h"
#include "biodynamo.h"
namespace bdm {
using experimental::neuroscience::NeuriteElement;
template <typename TBackend>
struct CompileTimeParam
: public DefaultCompileTimeParam<TBackend>,
public experimental::neuroscience::DefaultCompileTimeParam<TBackend> {};
/// Tests the forces that are created between the reference sphere and its
/// overlapping neighbors
/// implementation uses virual bigger radii to have distant interaction
TEST(DefaultForce, GeneralSphere) {
Cell cell({1.1, 1.0, 0.9});
cell.SetDiameter(8);
Cell nb({0, 0, 0});
nb.SetDiameter(5);
DefaultForce force;
auto result = force.GetForce(&cell, &nb);
EXPECT_NEAR(7.1429184067241138, result[0], abs_error<double>::value);
EXPECT_NEAR(6.4935621879310119, result[1], abs_error<double>::value);
EXPECT_NEAR(5.8442059691379109, result[2], abs_error<double>::value);
nb.SetDiameter(10);
nb.SetPosition({5, 5, 0});
result = force.GetForce(&cell, &nb);
EXPECT_NEAR(-5.7454658831720176, result[0], abs_error<double>::value);
EXPECT_NEAR(-5.892785521202069, result[1], abs_error<double>::value);
EXPECT_NEAR(1.3258767422704656, result[2], abs_error<double>::value);
}
/// Tests the special case that non of the neighbors overlap
/// with the reference cell
TEST(DefaultForce, AllNonOverlappingSphere) {
Cell cell({0, 0, 0});
cell.SetDiameter(8);
Cell nb({11.01, 0, 0});
nb.SetDiameter(8);
DefaultForce force;
auto result = force.GetForce(&cell, &nb);
EXPECT_NEAR(0, result[0], abs_error<double>::value);
EXPECT_NEAR(0, result[1], abs_error<double>::value);
EXPECT_NEAR(0, result[2], abs_error<double>::value);
}
/// Tests the special case that neighbor and reference cell
/// are at the same position -> should return random force
TEST(DefaultForce, AllAtSamePositionSphere) {
Cell cell({0, 0, 0});
cell.SetDiameter(8);
Cell nb({0, 0, 0});
nb.SetDiameter(8);
DefaultForce force;
auto result = force.GetForce(&cell, &nb);
// random number must be in interval [-3.0, 3.0]
EXPECT_NEAR(0, result[0], 3);
EXPECT_NEAR(0, result[1], 3);
EXPECT_NEAR(0, result[2], 3);
}
/// Tests the forces that are created between the reference sphere and its
/// overlapping cylinder
TEST(DefaultForce, GeneralSphereCylinder) {
NeuriteElement cylinder;
cylinder.SetMassLocation({2, 0, 0});
cylinder.SetSpringAxis({-5, -1, -3}); // -> proximal end = {7, 1, 3}
cylinder.SetDiameter(4);
Cell sphere({0, 0, 0});
sphere.SetDiameter(10);
EXPECT_ARR_NEAR({7, 1, 3}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(5, result1[0], abs_error<double>::value);
EXPECT_NEAR(0, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(0, result1[3], abs_error<double>::value);
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({-5, 0, 0}, result2);
}
TEST(DISABLED_DefaultForce, GeneralCylinder) {
NeuriteElement cylinder1;
cylinder1.SetMassLocation({0, 0, 0});
cylinder1.SetSpringAxis({-5, 0, 0}); // -> proximal end = {5, 0, 0}
cylinder1.SetDiameter(4);
EXPECT_ARR_NEAR({5, 0, 0}, cylinder1.ProximalEnd());
NeuriteElement cylinder2;
cylinder2.SetMassLocation({1, -2, 1});
cylinder2.SetSpringAxis({-10, -4, -0.5}); // -> proximal end = {11, 2, 1.5}
cylinder2.SetDiameter(6);
EXPECT_ARR_NEAR({11, 2, 1.5}, cylinder2.ProximalEnd());
DefaultForce force;
auto result = force.GetForce(&cylinder1, &cylinder2);
EXPECT_NEAR(-38.290598290598311, result[0], abs_error<double>::value);
EXPECT_NEAR(9.5726495726495653, result[1], abs_error<double>::value);
EXPECT_NEAR(-76.581196581196579, result[2], abs_error<double>::value);
EXPECT_NEAR(1, result[3], abs_error<double>::value);
result = force.GetForce(&cylinder2, &cylinder1);
EXPECT_NEAR(38.290598290598311, result[0], abs_error<double>::value);
EXPECT_NEAR(-9.5726495726495653, result[1], abs_error<double>::value);
EXPECT_NEAR(76.581196581196579, result[2], abs_error<double>::value);
EXPECT_NEAR(0.46153846153846156, result[3],
abs_error<double>::value); // FIXME not symmetric
}
TEST(DefaultForce, CylinderIntersectingAxis) {
NeuriteElement cylinder1;
cylinder1.SetMassLocation({0, 0, 0});
cylinder1.SetSpringAxis({-5, 0, 0}); // -> proximal end = {5, 0, 0}
cylinder1.SetDiameter(4);
EXPECT_ARR_NEAR({5, 0, 0}, cylinder1.ProximalEnd());
NeuriteElement cylinder2;
cylinder2.SetMassLocation({2, -2, 0});
cylinder2.SetSpringAxis({0, -4, 0}); // -> proximal end = {2, 2, 0}
cylinder2.SetDiameter(6);
EXPECT_ARR_NEAR({2, 2, 0}, cylinder2.ProximalEnd());
DefaultForce force;
auto result = force.GetForce(&cylinder1, &cylinder2);
EXPECT_NEAR(0, result[0], 30);
EXPECT_NEAR(0, result[1], 30);
EXPECT_NEAR(0, result[2], 30);
EXPECT_NEAR(0.4, result[3], abs_error<double>::value);
result = force.GetForce(&cylinder2, &cylinder1);
EXPECT_NEAR(0, result[0], 30);
EXPECT_NEAR(0, result[1], 30);
EXPECT_NEAR(0, result[2], 30);
EXPECT_NEAR(0.5, result[3], abs_error<double>::value);
}
TEST(DefaultForce, NotTouchingParallelCylinders) {
NeuriteElement cylinder1;
cylinder1.SetMassLocation({0, 0, 0});
cylinder1.SetSpringAxis({-5, 0, 0}); // -> proximal end = {5, 0, 0}
cylinder1.SetDiameter(4);
EXPECT_ARR_NEAR({5, 0, 0}, cylinder1.ProximalEnd());
NeuriteElement cylinder2;
cylinder2.SetMassLocation({0, -5, 0});
cylinder2.SetSpringAxis({-5, 0, 0}); // -> proximal end = {5, -5, 0}
cylinder2.SetDiameter(6);
EXPECT_ARR_NEAR({5, -5, 0}, cylinder2.ProximalEnd());
DefaultForce force;
auto result = force.GetForce(&cylinder1, &cylinder2);
EXPECT_NEAR(0, result[0], abs_error<double>::value);
EXPECT_NEAR(0, result[1], abs_error<double>::value);
EXPECT_NEAR(0, result[2], abs_error<double>::value);
EXPECT_NEAR(0.5, result[3], abs_error<double>::value);
result = force.GetForce(&cylinder2, &cylinder1);
EXPECT_NEAR(0, result[0], abs_error<double>::value);
EXPECT_NEAR(0, result[1], abs_error<double>::value);
EXPECT_NEAR(0, result[2], abs_error<double>::value);
EXPECT_NEAR(0.5, result[3], abs_error<double>::value);
}
// test I case of ForceOnACylinderFromASphere() function, ie if cylinder length
// < sphere radius
// sphere-cylinder interaction is done at the center and in the horizontal
// orientation of the cylinder
TEST(DefaultForce, SphereSmallCylinderHorizontal) {
Cell sphere({0, 0, 0});
sphere.SetDiameter(50);
NeuriteElement cylinder;
cylinder.SetMassLocation({-4, 24.5, 0});
cylinder.SetSpringAxis({-8, 0, 0}); // -> proximal end = {4, 24.5, 0}
cylinder.SetDiameter(4);
EXPECT_ARR_NEAR({4, 24.5, 0}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(-0.196774255282483, result1[0], abs_error<double>::value);
EXPECT_NEAR(2.41048462721042, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(0, result1[3], abs_error<double>::value);
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({0.196774255282483, -2.41048462721042, 0}, result2);
}
// test I case of ForceOnACylinderFromASphere() function, ie if cylinder length
// < sphere radius
// sphere-cylinder interaction is done vertically at the tip of the cylinder
// (mass location)
TEST(DefaultForce, SphereSmallCylinderVertical) {
Cell sphere({0, 0, 0});
sphere.SetDiameter(50);
ResourceManager<>::Get()->push_back(sphere);
NeuriteElement cylinder;
cylinder.SetMassLocation({0, 24, 0});
cylinder.SetSpringAxis({0, -8, 0}); // -> proximal end = {0, 32, 0}
cylinder.SetDiameter(4);
EXPECT_ARR_NEAR({0, 32, 0}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(0, result1[0], abs_error<double>::value);
EXPECT_NEAR(1, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(0, result1[3], abs_error<double>::value);
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({0, -1, 0}, result2);
}
// opposit case of Vertical: cylinder is below the cell
TEST(DefaultForce, SphereSmallCylinderVertical2) {
Cell sphere({0, 0, 0});
sphere.SetDiameter(50);
ResourceManager<>::Get()->push_back(sphere);
NeuriteElement cylinder;
cylinder.SetMassLocation({0, -24, 0});
cylinder.SetSpringAxis({0, 8, 0}); // -> proximal end = {0, -32, 0}
cylinder.SetDiameter(4);
EXPECT_ARR_NEAR({0, -32, 0}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(0, result1[0], abs_error<double>::value);
EXPECT_NEAR(-1, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(0, result1[3], abs_error<double>::value);
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({0, 1, 0}, result2);
}
// test the II case of ForceOnACylinderFromASphere() function, ie if cylinder
// length > sphere radius
// sphere-cylinder interaction is done at the center and in the horizontal
// orientation of the cylinder
TEST(DefaultForce, SphereLongCylinderHorizontalCenter) {
Cell sphere({0, 0, 0});
sphere.SetDiameter(10);
NeuriteElement cylinder;
cylinder.SetMassLocation({-10, 14.5, 0});
cylinder.SetSpringAxis({-20, 0, 0}); // -> proximal end = {10, 14.5, 0}
cylinder.SetDiameter(20);
EXPECT_ARR_NEAR({10, 14.5, 0}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(0, result1[0], abs_error<double>::value);
EXPECT_NEAR(0.5, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(
0.5, result1[3],
abs_error<double>::value); // 0.5 force is transmited to proximalEnd
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({0, -0.5, 0}, result2);
}
// test the II case of ForceOnACylinderFromASphere() function, ie if cylinder
// length > sphere radius
// sphere-cylinder interaction is done at the proximal end and in the horizontal
// orientation of the cylinder
TEST(DefaultForce, SphereLongCylinderHorizontalpP) {
Cell sphere({0, 0, 0});
sphere.SetDiameter(10);
NeuriteElement cylinder;
cylinder.SetMassLocation({-19.5, 14.5, 0});
cylinder.SetSpringAxis({-20, 0, 0}); // -> proximal end = {0.5, 14.5, 0}
cylinder.SetDiameter(20);
EXPECT_ARR_NEAR({0.5, 14.5, 0}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(0, result1[0], abs_error<double>::value);
EXPECT_NEAR(0.5, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(
0.975, result1[3],
abs_error<double>::value); // 0.975 force is transmited to proximalEnd
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({0, -0.5, 0}, result2);
}
// test the II case of ForceOnACylinderFromASphere() function, ie if cylinder
// length > sphere radius
// sphere-cylinder interaction is done at the distal point and in the horizontal
// orientation of the cylinder
TEST(DefaultForce, SphereLongCylinderHorizontalpD) {
Cell sphere({0, 0, 0});
sphere.SetDiameter(10);
NeuriteElement cylinder;
cylinder.SetMassLocation({-0.5, 14.5, 0});
cylinder.SetSpringAxis({-20, 0, 0}); // -> proximal end = {19.5, 14.5, 0}
cylinder.SetDiameter(20);
EXPECT_ARR_NEAR({19.5, 14.5, 0}, cylinder.ProximalEnd());
DefaultForce force;
auto result1 = force.GetForce(&cylinder, &sphere);
EXPECT_NEAR(0, result1[0], abs_error<double>::value);
EXPECT_NEAR(0.5, result1[1], abs_error<double>::value);
EXPECT_NEAR(0, result1[2], abs_error<double>::value);
EXPECT_NEAR(
0.025, result1[3],
abs_error<double>::value); // 0.025 force is transmited to proximalEnd
auto result2 = force.GetForce(&sphere, &cylinder);
EXPECT_ARR_NEAR({0, -0.5, 0}, result2);
}
} // namespace bdm
|
// A C++ program to implement greedy algorithm for graph coloring
#include <iostream>
#include <list>
using namespace std;
// A class that represents an undirected graph
class Graph
{
int V; // No. of vertices
list<int> *adj; // A dynamic array of adjacency lists
public:
// Constructor and destructor
Graph(int V) { this->V = V; adj = new list<int>[V]; }
~Graph() { delete [] adj; }
// function to add an edge to graph
void addEdge(int v, int w);
// Prints greedy coloring of the vertices
void greedyColoring();
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v); // Note: the graph is undirected
}
// Assigns colors (starting from 0) to all vertices and prints
// the assignment of colors
void Graph::greedyColoring()
{
int result[V];
// Assign the first color to first vertex
result[0] = 0;
// Initialize remaining V-1 vertices as unassigned
for (int u = 1; u < V; u++)
result[u] = -1; // no color is assigned to u
// A temporary array to store the available colors. True
// value of available[cr] would mean that the color cr is
// assigned to one of its adjacent vertices
bool available[V];
for (int cr = 0; cr < V; cr++)
available[cr] = false;
// Assign colors to remaining V-1 vertices
for (int u = 1; u < V; u++)
{
// Process all adjacent vertices and flag their colors
// as unavailable
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (result[*i] != -1)
available[result[*i]] = true;
// Find the first available color
int cr;
for (cr = 0; cr < V; cr++)
if (available[cr] == false)
break;
result[u] = cr; // Assign the found color
// Reset the values back to false for the next iteration
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (result[*i] != -1)
available[result[*i]] = false;
}
// print the result
for (int u = 0; u < V; u++)
cout << "Vertex " << u << " ---> Color "
<< result[u] << endl;
}
// Driver program to test above function
int main()
{
Graph g1(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
cout << "Coloring of graph 1 \n";
g1.greedyColoring();
Graph g2(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
cout << "\nColoring of graph 2 \n";
g2.greedyColoring();
return 0;
}
|
/*
* Copyright (C) 2013, Jules Colding <jcolding@gmail.com>.
*
* All Rights Reserved.
*/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* (1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* (3) Neither the name of the copyright holder 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 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 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.
*/
#include "fix_types.h"
#ifdef HAVE_CONFIG_H
#include "ac_config.h"
#endif
const struct FIX_Tag fix42_std_tags[] =
{
{1, ft_String},
{2, ft_String},
{3, ft_String},
{4, ft_char},
{5, ft_String},
{6, ft_Price},
{7, ft_int},
{8, ft_String},
{9, ft_int},
{10, ft_String},
{11, ft_String},
{12, ft_Amt},
{13, ft_char},
{14, ft_Qty},
{15, ft_Currency},
{16, ft_int},
{17, ft_String},
{18, ft_MultipleCharValue},
{19, ft_String},
{20, ft_char},
{21, ft_char},
{22, ft_String},
{23, ft_String},
{24, ft_char},
{25, ft_char},
{26, ft_String},
{27, ft_String},
{28, ft_char},
{29, ft_char},
{30, ft_Exchange},
{31, ft_Price},
{32, ft_Qty},
{33, ft_int},
{34, ft_int},
{35, ft_String},
{36, ft_int},
{37, ft_String},
{38, ft_Qty},
{39, ft_char},
{40, ft_char},
{41, ft_String},
{42, ft_UTCTimestamp},
{43, ft_Boolean},
{44, ft_Price},
{45, ft_int},
{46, ft_String},
{47, ft_char},
{48, ft_String},
{49, ft_String},
{50, ft_String},
{51, ft_LocalMktDate},
{52, ft_UTCTimestamp},
{53, ft_Qty},
{54, ft_char},
{55, ft_String},
{56, ft_String},
{57, ft_String},
{58, ft_String},
{59, ft_char},
{60, ft_UTCTimestamp},
{61, ft_char},
{62, ft_UTCTimestamp},
{63, ft_char},
{64, ft_LocalMktDate},
{65, ft_String},
{66, ft_String},
{67, ft_int},
{68, ft_int},
{69, ft_String},
{70, ft_String},
{71, ft_char},
{72, ft_String},
{73, ft_int},
{74, ft_int},
{75, ft_LocalMktDate},
{76, ft_String},
{77, ft_char},
{78, ft_int},
{79, ft_String},
{80, ft_Qty},
{81, ft_char},
{82, ft_int},
{83, ft_int},
{84, ft_Qty},
{85, ft_int},
{86, ft_String},
{87, ft_int},
{88, ft_int},
{89, ft_data},
{90, ft_Length},
{91, ft_data},
{92, ft_String},
{93, ft_Length},
{94, ft_char},
{95, ft_Length},
{96, ft_data},
{97, ft_Boolean},
{98, ft_int},
{99, ft_Price},
{100, ft_Exchange},
{102, ft_int},
{103, ft_int},
{104, ft_char},
{105, ft_String},
{106, ft_String},
{107, ft_String},
{108, ft_int},
{109, ft_String},
{110, ft_Qty},
{111, ft_Qty},
{112, ft_String},
{113, ft_Boolean},
{114, ft_Boolean},
{115, ft_String},
{116, ft_String},
{117, ft_String},
{118, ft_Amt},
{119, ft_Amt},
{120, ft_Currency},
{121, ft_Boolean},
{122, ft_UTCTimestamp},
{123, ft_Boolean},
{124, ft_int},
{125, ft_char},
{126, ft_UTCTimestamp},
{127, ft_char},
{128, ft_String},
{129, ft_String},
{130, ft_Boolean},
{131, ft_String},
{132, ft_Price},
{133, ft_Price},
{134, ft_Qty},
{135, ft_Qty},
{136, ft_int},
{137, ft_Amt},
{138, ft_Currency},
{139, ft_char},
{140, ft_Price},
{141, ft_Boolean},
{142, ft_String},
{143, ft_String},
{144, ft_String},
{145, ft_String},
{146, ft_int},
{147, ft_String},
{148, ft_String},
{149, ft_String},
{150, ft_char},
{151, ft_Qty},
{152, ft_Qty},
{153, ft_Price},
{154, ft_Amt},
{155, ft_float},
{156, ft_char},
{157, ft_int},
{158, ft_float},
{159, ft_Amt},
{160, ft_char},
{161, ft_String},
{162, ft_String},
{163, ft_char},
{164, ft_String},
{165, ft_char},
{166, ft_String},
{167, ft_String},
{168, ft_UTCTimestamp},
{169, ft_int},
{170, ft_String},
{171, ft_String},
{172, ft_int},
{173, ft_String},
{174, ft_String},
{175, ft_String},
{176, ft_String},
{177, ft_String},
{178, ft_String},
{179, ft_String},
{180, ft_String},
{181, ft_String},
{182, ft_String},
{183, ft_String},
{184, ft_String},
{185, ft_String},
{186, ft_String},
{187, ft_String},
{188, ft_Price},
{189, ft_Price},
{190, ft_Price},
{191, ft_Price},
{192, ft_Qty},
{193, ft_LocalMktDate},
{194, ft_Price},
{195, ft_Price},
{196, ft_String},
{197, ft_int},
{198, ft_String},
{199, ft_int},
{200, ft_MonthYear},
{201, ft_int},
{202, ft_Price},
{203, ft_int},
{204, ft_int},
{205, ft_DayOfMonth},
{206, ft_char},
{207, ft_Exchange},
{208, ft_Boolean},
{209, ft_int},
{210, ft_Qty},
{211, ft_Price},
{212, ft_Length},
{213, ft_data},
{214, ft_String},
{215, ft_int},
{216, ft_int},
{217, ft_String},
{218, ft_Price},
{219, ft_char},
{223, ft_float},
{231, ft_float},
{262, ft_String},
{263, ft_char},
{264, ft_int},
{265, ft_int},
{266, ft_Boolean},
{267, ft_int},
{268, ft_int},
{269, ft_char},
{270, ft_Price},
{271, ft_Qty},
{272, ft_UTCDateOnly},
{273, ft_UTCTimeOnly},
{274, ft_char},
{275, ft_Exchange},
{276, ft_MultipleStringValue},
{277, ft_MultipleStringValue},
{278, ft_String},
{279, ft_char},
{280, ft_String},
{281, ft_char},
{282, ft_String},
{283, ft_String},
{284, ft_String},
{285, ft_char},
{286, ft_char},
{287, ft_int},
{288, ft_String},
{289, ft_String},
{290, ft_int},
{291, ft_char},
{292, ft_char},
{293, ft_Qty},
{294, ft_Qty},
{295, ft_int},
{296, ft_int},
{297, ft_int},
{298, ft_int},
{299, ft_String},
{300, ft_int},
{301, ft_int},
{302, ft_String},
{303, ft_int},
{304, ft_int},
{305, ft_String},
{306, ft_String},
{307, ft_String},
{308, ft_Exchange},
{309, ft_String},
{310, ft_String},
{311, ft_String},
{312, ft_String},
{313, ft_MonthYear},
{314, ft_DayOfMonth},
{315, ft_int},
{316, ft_Price},
{317, ft_char},
{318, ft_Currency},
{319, ft_Qty},
{320, ft_String},
{321, ft_int},
{322, ft_String},
{323, ft_int},
{324, ft_String},
{325, ft_Boolean},
{326, ft_int},
{327, ft_char},
{328, ft_Boolean},
{329, ft_Boolean},
{330, ft_Qty},
{331, ft_Qty},
{332, ft_Price},
{333, ft_Price},
{334, ft_int},
{335, ft_String},
{336, ft_String},
{337, ft_String},
{338, ft_int},
{339, ft_int},
{340, ft_int},
{341, ft_UTCTimestamp},
{342, ft_UTCTimestamp},
{343, ft_UTCTimestamp},
{344, ft_UTCTimestamp},
{345, ft_UTCTimestamp},
{346, ft_int},
{347, ft_String},
{348, ft_Length},
{349, ft_data},
{350, ft_Length},
{351, ft_data},
{352, ft_Length},
{353, ft_data},
{354, ft_Length},
{355, ft_data},
{356, ft_Length},
{357, ft_data},
{358, ft_Length},
{359, ft_data},
{360, ft_Length},
{361, ft_data},
{362, ft_Length},
{363, ft_data},
{364, ft_Length},
{365, ft_data},
{366, ft_Price},
{367, ft_UTCTimestamp},
{368, ft_int},
{369, ft_int},
{370, ft_UTCTimestamp},
{371, ft_int},
{372, ft_String},
{373, ft_int},
{374, ft_char},
{375, ft_String},
{376, ft_String},
{377, ft_Boolean},
{378, ft_int},
{379, ft_String},
{380, ft_int},
{381, ft_Amt},
{382, ft_int},
{383, ft_int},
{384, ft_int},
{385, ft_char},
{386, ft_int},
{387, ft_Qty},
{388, ft_char},
{389, ft_Price},
{390, ft_String},
{391, ft_String},
{392, ft_String},
{393, ft_int},
{394, ft_int},
{395, ft_int},
{396, ft_Amt},
{397, ft_Amt},
{398, ft_int},
{399, ft_int},
{400, ft_String},
{401, ft_int},
{402, ft_float},
{403, ft_float},
{404, ft_Amt},
{405, ft_float},
{406, ft_Amt},
{407, ft_float},
{408, ft_Amt},
{409, ft_int},
{410, ft_float},
{411, ft_Boolean},
{412, ft_Amt},
{413, ft_float},
{414, ft_int},
{415, ft_int},
{416, ft_int},
{417, ft_int},
{418, ft_char},
{419, ft_char},
{420, ft_int},
{421, ft_String},
{422, ft_int},
{423, ft_int},
{424, ft_Qty},
{425, ft_Qty},
{426, ft_Price},
{427, ft_int},
{428, ft_int},
{429, ft_int},
{430, ft_int},
{431, ft_int},
{432, ft_LocalMktDate},
{433, ft_char},
{434, ft_char},
{435, ft_float},
{436, ft_float},
{437, ft_Qty},
{438, ft_UTCTimestamp},
{439, ft_String},
{440, ft_String},
{441, ft_int},
{442, ft_char},
{443, ft_UTCTimestamp},
{444, ft_String},
{445, ft_Length},
{446, ft_data},
{0, ft_int}, // terminating 0 tag
};
const struct FIX_Tag fix42_std_data_tags[] =
{
{89, ft_data},
{91, ft_data},
{96, ft_data},
{213, ft_data},
{349, ft_data},
{351, ft_data},
{353, ft_data},
{355, ft_data},
{357, ft_data},
{359, ft_data},
{361, ft_data},
{363, ft_data},
{365, ft_data},
{446, ft_data},
{0, ft_int}, // terminating 0 tag
};
|
/*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
}
b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
}
void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0)
{
m_angularMass = 1.0 / m_angularMass;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
// Solve angular friction
{
float32 Cdot = wB - wA;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2FrictionJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2FrictionJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2FrictionJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0);
m_maxForce = force;
}
float32 b2FrictionJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2FrictionJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0);
m_maxTorque = torque;
}
float32 b2FrictionJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2FrictionJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2FrictionJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
|
/*
* Copyright (C) 2008 Apple 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:
* 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 APPLE INC. ``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 APPLE INC. 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 "config.h"
#include "CallData.h"
#include "Executable.h"
#include "Interpreter.h"
#include "JSFunction.h"
namespace JSC {
JSValue call(ExecState* exec, JSValue functionObject, CallType callType, const CallData& callData, JSValue thisValue, const ArgList& args)
{
ASSERT(callType == CallTypeJS || callType == CallTypeHost);
ASSERT(isValidThisObject(thisValue, exec));
return exec->interpreter()->executeCall(exec, asObject(functionObject), callType, callData, thisValue, args);
}
} // namespace JSC
|
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef unsigned int ui;
typedef vector<int> vi;
typedef vector<ui> vui;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<string> vs;
typedef vector<vi> vvi;
typedef vector<vui> vvui;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
typedef vector<vs> vvs;
typedef string ss;
#define forr(i,b) for(int i = 0; i < b; i++)
#define ford(i,b) for(int i = b; i >= 0; i--)
#define fore(v,a) for(auto& v:a)
#define ff for(;;)
#define pb push_back
#define bb(a,b,c) max(min(b,c),a)
template<typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); }
int gcd(int a, int b) { if(a == 0) return b; return gcd(b % a, a); }
int ncr(int n, int k) { int r = 1; if(k > n - k) k = n - k; for(int i=0;i<k;i++) { r *= n - i; r /= i + 1; } return r; }
template<typename T> void printa(vector<T> arr) { for(ui i = 0; i < arr.size(); i++) if(i != arr.size() - 1) cout << arr[i] << ' '; else cout << arr[i] << '\n'; }
bool fn(ss s, char c) { return s.find(c) != ss::npos; }
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vi a(n);
int maxIdx = -1, maxVal = INT_MIN;
int minIdx = -1, minVal = INT_MAX;
forr (i, n) {
cin >> a[i];
if (a[i] > maxVal || (a[i] == maxVal && i < maxIdx)) {
maxVal = a[i];
maxIdx = i;
}
if (a[i] < minVal || (a[i] == minVal && i > minIdx)) {
minVal = a[i];
minIdx = i;
}
}
int ans = maxIdx + (n - 1 - minIdx);
if (maxIdx > minIdx)
ans -= 1;
cout << ans << '\n';
return 0;
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/imaging/hd/tokens.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_DEFINE_PUBLIC_TOKENS(HdTokens, HD_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdReprTokens, HD_REPR_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdPerfTokens, HD_PERF_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdShaderTokens, HD_SHADER_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdRenderTagTokens, HD_RENDERTAG_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdMaterialTagTokens, HD_MATERIALTAG_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdMaterialTerminalTokens, HD_MATERIAL_TERMINAL_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdOptionTokens, HD_OPTION_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdPrimTypeTokens, HD_PRIMTYPE_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdPrimvarRoleTokens, HD_PRIMVAR_ROLE_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdAovTokens, HD_AOV_TOKENS);
TF_DEFINE_PUBLIC_TOKENS(HdRenderSettingsTokens, HD_RENDER_SETTINGS_TOKENS);
TfToken HdAovTokensMakePrimvar(TfToken const& primvar)
{
return TfToken(
HdAovTokens->primvars.GetString() +
primvar.GetString());
}
TfToken HdAovTokensMakeLpe(TfToken const& lpe)
{
return TfToken(
HdAovTokens->lpe.GetString() +
lpe.GetString());
}
TfToken HdAovTokensMakeShader(TfToken const& shader)
{
return TfToken(
HdAovTokens->shader.GetString() +
shader.GetString());
}
PXR_NAMESPACE_CLOSE_SCOPE
|
/*****************************************************************************
DistAttract.hpp
Author: Laurent de Soras, 2018
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if ! defined (mfx_dsp_shape_DistAttract_CODEHEADER_INCLUDED)
#define mfx_dsp_shape_DistAttract_CODEHEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/Approx.h"
#include <algorithm>
#include <cassert>
#include <cmath>
namespace mfx
{
namespace dsp
{
namespace shape
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
float DistAttract::process_sample (float x)
{
const float env_val = _env.process_sample (x) + 1e-5f; // + small cst to avoid log(0) later
attract (x, env_val);
return _cur_val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
void DistAttract::attract (float x, float env_val)
{
assert (env_val > 0);
if (_mad_flag)
{
const float dest = _lvl_b * _sign;
const float dist = dest - _cur_val;
const float f = std::copysign (1.0f / 16, dist);
_speed += f * _ratio_f;
const float speed_limit = std::max (
fstb::Approx::log2 (env_val) * 0.25f - 1,
_speed_lim_min
);
assert (speed_limit > 0);
_speed = fstb::limit (_speed, -speed_limit, speed_limit);
_cur_val += _speed * _ratio_f;
if (_cur_val * _sign > _lvl_b)
{
_sign = -_sign;
}
if ( fabs (x) < fabs (_cur_val)
&& fabs (_cur_val) < _lvl_b)
{
_mad_flag = false;
}
}
else
{
if (fabs (x) < 1e-3f)
{
_cur_val = x;
}
else
{
const float amount = 1 - 1 / (fabs (x) * 4 + 1);
const Polarity pol = val_to_pol (x);
const float attract_point = _lvl_a [pol];
const float dist_a = attract_point - _cur_val;
const float comp_a = dist_a * amount;
const float dist_x = x - _cur_val;
const float comp_x = dist_x * (1 - amount);
const float comp_all = comp_x + comp_a;
const float step = comp_all * _ratio_f;
_cur_val += step;
if (fabs (x) >= _lvl_b)
{
_mad_flag = true;
_sign = (_cur_val < 0) ? 1.0f : -1.0f;
_speed = 0;
}
}
}
}
constexpr DistAttract::Polarity DistAttract::val_to_pol (float val)
{
return ((val < 0) ? Polarity_NEG : Polarity_POS);
}
constexpr float DistAttract::pol_to_val (Polarity polarity)
{
#if __cplusplus >= 201402L
assert (polarity >= 0);
assert (polarity < Polarity_NBR_ELT);
#endif
return (polarity != Polarity_POS) ? -1.f : 1.f;
}
} // namespace shape
} // namespace dsp
} // namespace mfx
#endif // mfx_dsp_shape_DistAttract_CODEHEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "LandscapeEditorCommands.h"
#define LOCTEXT_NAMESPACE "LandscapeEditorCommands"
void FLandscapeEditorCommands::RegisterCommands()
{
UI_COMMAND(ManageMode, "Mode - Manage", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("ToolMode_Manage", ManageMode);
UI_COMMAND(SculptMode, "Mode - Sculpt", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("ToolMode_Sculpt", SculptMode);
UI_COMMAND(PaintMode, "Mode - Paint", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("ToolMode_Paint", PaintMode);
UI_COMMAND(NewLandscape, "Tool - New Landscape", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_NewLandscape", NewLandscape);
UI_COMMAND(ResizeLandscape, "Tool - Change Component Size", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_ResizeLandscape", ResizeLandscape);
UI_COMMAND(SculptTool, "Tool - Sculpt", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Sculpt", SculptTool);
UI_COMMAND(PaintTool, "Tool - Paint", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Paint", PaintTool);
UI_COMMAND(SmoothTool, "Tool - Smooth", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Smooth", SmoothTool);
UI_COMMAND(FlattenTool, "Tool - Flatten", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Flatten", FlattenTool);
UI_COMMAND(RampTool, "Tool - Ramp", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Ramp", RampTool);
UI_COMMAND(ErosionTool, "Tool - Erosion", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Erosion", ErosionTool);
UI_COMMAND(HydroErosionTool, "Tool - Hydraulic Erosion", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_HydraErosion", HydroErosionTool);
UI_COMMAND(NoiseTool, "Tool - Noise", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Noise", NoiseTool);
UI_COMMAND(RetopologizeTool, "Tool - Retopologize", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Retopologize", RetopologizeTool);
UI_COMMAND(VisibilityTool, "Tool - Visibility", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Visibility", VisibilityTool);
UI_COMMAND(SelectComponentTool, "Tool - Component Selection", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Select", SelectComponentTool);
UI_COMMAND(AddComponentTool, "Tool - Add Components", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_AddComponent", AddComponentTool);
UI_COMMAND(DeleteComponentTool, "Tool - Delete Components", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_DeleteComponent", DeleteComponentTool);
UI_COMMAND(MoveToLevelTool, "Tool - Move to Level", "Moves the selected landscape components to the current streaming level", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_MoveToLevel", MoveToLevelTool);
UI_COMMAND(RegionSelectTool, "Tool - Region Selection", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Mask", RegionSelectTool);
UI_COMMAND(RegionCopyPasteTool, "Tool - Copy/Paste", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_CopyPaste", RegionCopyPasteTool);
UI_COMMAND(MirrorTool, "Tool - Mirror", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Mirror", MirrorTool);
UI_COMMAND(SplineTool, "Tool - Edit Splines", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Tool_Splines", SplineTool);
UI_COMMAND(CircleBrush, "Brush - Circle", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("BrushSet_Circle", CircleBrush);
UI_COMMAND(AlphaBrush, "Brush - Alpha", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("BrushSet_Alpha", AlphaBrush);
UI_COMMAND(AlphaBrush_Pattern, "Brush - Pattern", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("BrushSet_Pattern", AlphaBrush_Pattern);
UI_COMMAND(ComponentBrush, "Brush - Component", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("BrushSet_Component", ComponentBrush);
UI_COMMAND(GizmoBrush, "Brush - Gizmo", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("BrushSet_Gizmo", GizmoBrush);
NameToCommandMap.Add("BrushSet_Splines", SplineTool);
UI_COMMAND(CircleBrush_Smooth, "Circle Brush - Smooth Falloff", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Circle_Smooth", CircleBrush_Smooth);
UI_COMMAND(CircleBrush_Linear, "Circle Brush - Linear Falloff", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Circle_Linear", CircleBrush_Linear);
UI_COMMAND(CircleBrush_Spherical, "Circle Brush - Spherical Falloff", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Circle_Spherical", CircleBrush_Spherical);
UI_COMMAND(CircleBrush_Tip, "Circle Brush - Tip Falloff", "", EUserInterfaceActionType::RadioButton, FInputChord());
NameToCommandMap.Add("Circle_Tip", CircleBrush_Tip);
UI_COMMAND(ViewModeNormal, "Normal", "", EUserInterfaceActionType::RadioButton, FInputChord());
UI_COMMAND(ViewModeLOD, "LOD", "", EUserInterfaceActionType::RadioButton, FInputChord());
UI_COMMAND(ViewModeLayerUsage, "Layer Usage", "", EUserInterfaceActionType::RadioButton, FInputChord());
UI_COMMAND(ViewModeLayerDensity, "Layer Density", "", EUserInterfaceActionType::RadioButton, FInputChord());
UI_COMMAND(ViewModeLayerDebug, "Layer Debug", "", EUserInterfaceActionType::RadioButton, FInputChord());
UI_COMMAND(ViewModeWireframeOnTop, "Wireframe on Top", "", EUserInterfaceActionType::RadioButton, FInputChord());
}
#undef LOCTEXT_NAMESPACE
|
/* Copyright 2017 The TensorFlow Authors. 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.
==============================================================================*/
// The purpose of the benchmark library is to support building an aot binary
// with minimal dependencies, to demonstrate small binary sizes.
//
// KEEP THE DEPENDENCIES MINIMAL.
#include "tensorflow/compiler/aot/benchmark.h"
#include <sys/time.h>
#include <algorithm>
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace tfcompile {
namespace benchmark {
// Returns current wall time in micros.
//
// TODO(b/33546473): Refactor tensorflow::Env::NowMicros() so that we can re-use
// the implementation without pulling in all of the Env dependencies.
static double NowMicros() {
struct timeval tv;
gettimeofday(&tv, nullptr);
return static_cast<uint64>(tv.tv_sec) * 1000000 + tv.tv_usec;
}
void DumpStatsToStdout(const Stats& stats) {
// Compute stats.
std::vector<int64> sorted_us(stats.per_iter_us);
std::sort(sorted_us.begin(), sorted_us.end());
const size_t count_us = sorted_us.size();
double sum_us = 0;
size_t count_us_trimmed = 0;
double sum_us_trimmed = 0;
size_t count_us_best = 0;
double sum_us_best = 0;
static constexpr float trim_ratio = 0.25;
static constexpr float best_ratio = 0.1;
const size_t count_trimmed = count_us * trim_ratio;
const size_t count_best = count_us * best_ratio;
for (size_t i = 0; i < sorted_us.size(); ++i) {
const int64 us = sorted_us[i];
sum_us += us;
if (i >= count_trimmed && i < count_us - count_trimmed) {
sum_us_trimmed += us;
++count_us_trimmed;
}
if (i < count_best) {
sum_us_best += us;
++count_us_best;
}
}
// Prepare nicely-formatted data.
const int kBufSize = 1000;
char buf[kBufSize];
snprintf(buf, kBufSize, "Mean with %2.0f%% trimmed:", trim_ratio * 100);
const string label_trimmed(buf);
snprintf(buf, kBufSize, "Mean of %2.0f%% best:", best_ratio * 100);
const string label_best(buf);
std::vector<std::pair<string, double>> groups = {
{"Best:", sorted_us.front()},
{"Worst:", sorted_us.back()},
{"Median:", sorted_us[count_us / 2]},
{"Mean:", sum_us / count_us},
{label_trimmed, sum_us_trimmed / count_us_trimmed},
{label_best, sum_us_best / count_us_best},
};
int max_label_size = 0;
double max_us = 0;
for (const auto& g : groups) {
if (g.first.size() > max_label_size) {
max_label_size = g.first.size();
}
if (g.second > max_us) {
max_us = g.second;
}
}
int max_digits = 1;
while (max_us >= 10.0) {
max_us /= 10.0;
++max_digits;
}
// Dump stats out.
printf("Benchmark ran %zu iterations over %lld us\n", count_us,
stats.total_us);
for (const auto& g : groups) {
printf(" %-*s %*.3f us\n", max_label_size, g.first.c_str(), max_digits + 4,
g.second);
}
}
void Benchmark(const Options& options, const BenchmarkFn& fn, Stats* stats) {
// If neither max_seconds or max_iters is set, stop at kDefaultMicros.
const int64 max_us = (options.max_micros <= 0 && options.max_iters <= 0)
? Options::kDefaultMicros
: options.max_micros;
printf("Running benchmark for %lld us\n", max_us);
const int64 start_us = NowMicros();
int64 iters = 0;
while (true) {
const int64 iter_start_us = NowMicros();
fn();
const int64 end_us = NowMicros();
// Collect stats and decide whether to stop.
stats->per_iter_us.push_back(end_us - iter_start_us);
const int64 total_us = end_us - start_us;
++iters;
if ((max_us > 0 && total_us >= max_us) ||
(options.max_iters > 0 && iters >= options.max_iters)) {
stats->total_us = total_us;
break;
}
}
}
} // namespace benchmark
} // namespace tfcompile
} // namespace tensorflow
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/aw_browser_main_parts.h"
#include "android_webview/browser/aw_browser_context.h"
#include "android_webview/browser/aw_dev_tools_discovery_provider.h"
#include "android_webview/browser/aw_media_client_android.h"
#include "android_webview/browser/aw_result_codes.h"
#include "android_webview/browser/deferred_gpu_command_service.h"
#include "android_webview/common/aw_resource.h"
#include "android_webview/common/aw_switches.h"
#include "base/android/apk_assets.h"
#include "base/android/build_info.h"
#include "base/android/locale_utils.h"
#include "base/android/memory_pressure_listener_android.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "components/crash/content/browser/crash_micro_dump_manager_android.h"
#include "content/public/browser/android/synchronous_compositor.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "media/base/android/media_client_android.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/resource_bundle_android.h"
#include "ui/base/ui_base_paths.h"
#include "ui/gl/gl_surface.h"
namespace android_webview {
AwBrowserMainParts::AwBrowserMainParts(AwBrowserContext* browser_context)
: browser_context_(browser_context) {
}
AwBrowserMainParts::~AwBrowserMainParts() {
}
void AwBrowserMainParts::PreEarlyInitialization() {
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
// Android WebView does not use default MessageLoop. It has its own
// Android specific MessageLoop. Also see MainMessageLoopRun.
DCHECK(!main_message_loop_.get());
main_message_loop_.reset(new base::MessageLoopForUI);
base::MessageLoopForUI::current()->Start();
}
int AwBrowserMainParts::PreCreateThreads() {
ui::SetLocalePaksStoredInApk(true);
std::string locale = ui::ResourceBundle::InitSharedInstanceWithLocale(
base::android::GetDefaultLocale(),
NULL,
ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
if (locale.empty()) {
LOG(WARNING) << "Failed to load locale .pak from the apk. "
"Bringing up WebView without any locale";
}
// Try to directly mmap the webviewchromium.pak from the apk. Fall back to
// load from file, using PATH_SERVICE, otherwise.
base::FilePath pak_file_path;
PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &pak_file_path);
pak_file_path = pak_file_path.AppendASCII("webviewchromium.pak");
ui::LoadMainAndroidPackFile("assets/webviewchromium.pak", pak_file_path);
base::android::MemoryPressureListenerAndroid::RegisterSystemCallback(
base::android::AttachCurrentThread());
DeferredGpuCommandService::SetInstance();
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kSingleProcess)) {
// Create the renderers crash manager on the UI thread.
breakpad::CrashMicroDumpManager::GetInstance();
}
return content::RESULT_CODE_NORMAL_EXIT;
}
void AwBrowserMainParts::PreMainMessageLoopRun() {
browser_context_->PreMainMessageLoopRun();
AwDevToolsDiscoveryProvider::Install();
media::SetMediaClientAndroid(
new AwMediaClientAndroid(AwResource::GetConfigKeySystemUuidMapping()));
content::RenderFrameHost::AllowInjectingJavaScriptForAndroidWebView();
}
void AwBrowserMainParts::PostMainMessageLoopRun() {
browser_context_->PostMainMessageLoopRun();
}
bool AwBrowserMainParts::MainMessageLoopRun(int* result_code) {
// Android WebView does not use default MessageLoop. It has its own
// Android specific MessageLoop.
return true;
}
} // namespace android_webview
|
#include "types/Enumerable.hpp"
#include "types/Enumerator.hpp"
#include "types/Array.hpp"
#include "types/Hash.hpp"
#include "types/Proc.hpp"
#include "Function.hpp"
#include <sstream>
#include <algorithm>
#include <deque>
namespace slim
{
//Need to make an object that keeps "this" alive, but also can call a function not derived from Object
template<class T>
Ptr<Enumerator> make_enumerator(
ObjectPtr save_self,
T *forward_self,
ObjectPtr(T::*func)(const FunctionArgs &args),
const char *name,
const FunctionArgs &args = {})
{
return create_object<FunctionEnumerator>(
[save_self, forward_self, func](const FunctionArgs &args) { return (forward_self->*func)(args); },
args);
}
ObjectPtr Enumerable::each2(
const FunctionArgs &args,
std::function<ObjectPtr(const FunctionArgs &args)> func)
{
auto args2 = args;
args2.push_back(create_object<FunctionProc>(func));
return each(args2);
}
ObjectPtr Enumerable::each_single(
const FunctionArgs &args,
std::function<ObjectPtr(Object *arg)> func)
{
return each2(args, [func](const FunctionArgs &args) {
auto v = args.size() == 1 ? args[0] : make_value(args);
return func(v.get());
});
}
Ptr<Boolean> Enumerable::all_q(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
try
{
if (proc)
{
each2({}, [proc](const FunctionArgs &args) {
if(!proc->call(args)->is_true())
throw SpecialFlowException();
else return NIL_VALUE;
});
}
else
{
each2({}, [](const FunctionArgs &args) {
if (args.size() == 1 && !args[0]->is_true())
throw SpecialFlowException();
else return NIL_VALUE;
});
}
return TRUE_VALUE;
}
catch (const SpecialFlowException &) { return FALSE_VALUE; }
}
Ptr<Boolean> Enumerable::any_q(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
try
{
if (proc)
{
each2({}, [proc](const FunctionArgs &args) {
if (proc->call(args)->is_true())
throw SpecialFlowException();
else return NIL_VALUE;
});
}
else
{
each2({}, [](const FunctionArgs &args) {
if ((args.size() > 1 || args[0]->is_true()))
throw SpecialFlowException();
else return NIL_VALUE;
});
}
return FALSE_VALUE;
}
catch (const SpecialFlowException &) { return TRUE_VALUE; }
}
Ptr<Number> Enumerable::count(const FunctionArgs &args)
{
unsigned count = 0;
if (args.empty())
{
each2({}, [&count](const FunctionArgs &args) {
return ++count, NIL_VALUE;
});
}
else if (args.size() == 1)
{
auto proc = dynamic_cast<Proc*>(args[0].get());
if (proc)
{
each2({}, [proc, &count](const FunctionArgs &args) {
if (proc->call(args)->is_true()) ++count;
return NIL_VALUE;
});
}
else
{
auto itm = args[0].get();
each2({}, [itm, &count](const FunctionArgs &args) {
if (eq(itm, args[0].get())) ++count;
return NIL_VALUE;
});
}
}
else throw ArgumentCountError(args.size(), 0, 1);
return make_value(count);
}
Ptr<Array> Enumerable::drop(Number *n)
{
auto ret = create_object<Array>();
unsigned i = 0;
each_single([&ret, &i, n](Object *arg) {
if (++i > n->get_value())
ret->push_back(arg);
return NIL_VALUE;
});
return ret;
}
ObjectPtr Enumerable::drop_while(const FunctionArgs &args)
{
if (args.empty()) return make_enumerator(this_obj(), this, &Enumerable::drop_while, "drop_while");
else if (args.size() == 1)
{
auto ret = create_object<Array>();
bool start = false;
auto proc = coerce<Proc>(args[0].get());
each2({}, [proc, &ret, &start](const FunctionArgs &args) {
start = start || !proc->call(args)->is_true();
if (start)
{
if (args.size() == 1) ret->push_back(args[0]);
else ret->push_back(make_value(args));
}
return NIL_VALUE;
});
return ret;
}
else throw ArgumentCountError(args.size(), 0, 1);
}
ObjectPtr Enumerable::each_with_index(const FunctionArgs &args)
{
Proc *proc = nullptr;
if (!args.empty()) proc = dynamic_cast<Proc*>(args.back().get());
if (proc)
{
auto args2 = args;
args2.pop_back();
unsigned i = 0;
return each_single(args2, [&i, proc](Object *arg) {
return proc->call({ arg->shared_from_this(), make_value(i++) });
});
}
else
{
return make_enumerator(this_obj(), this, &Enumerable::each_with_index, "each_with_index", args);
}
}
ObjectPtr Enumerable::find(const FunctionArgs &args)
{
if (args.size() > 2) throw ArgumentCountError(args.size(), 0, 2);
auto proc = args.empty() ? nullptr : dynamic_cast<Proc*>(args.back().get());
if (proc)
{
try
{
each2({}, [proc](const FunctionArgs &args) {
if (proc->call(args)->is_true())
throw SpecialFlowException(args.size() == 1 ? args[0] : make_value(args));
return NIL_VALUE;
});
return args.size() == 2 ? args.front() : NIL_VALUE;
}
catch (const SpecialFlowException &e) { return e.value; }
}
else
{
if (args.size() > 1) throw TypeError(args.back().get(), Proc::name());
return make_enumerator(this_obj(), this, &Enumerable::find, "find", args);
}
}
ObjectPtr Enumerable::find_index(const FunctionArgs &args)
{
if (args.empty()) return make_enumerator(this_obj(), this, &Enumerable::find_index, "find_index", args);
if (args.size() > 1) throw ArgumentCountError(args.size(), 0, 1);
try
{
unsigned i = 0;
if (auto proc = dynamic_cast<Proc*>(args[0].get()))
{
each2({}, [&i, proc](const FunctionArgs &args) {
if (proc->call(args)->is_true())
throw SpecialFlowException(make_value(i));
++i;
return NIL_VALUE;
});
}
else //find value
{
auto value = args[0].get();
each2({}, [&i, value](const FunctionArgs &args) {
if (eq(value, args.size() == 1 ? args[0].get() : make_value(args).get()))
throw SpecialFlowException(make_value(i));
++i;
return NIL_VALUE;
});
}
return NIL_VALUE;
}
catch (const SpecialFlowException &e) { return e.value; }
}
ObjectPtr Enumerable::first(const FunctionArgs &args)
{
if (args.empty())
{
try
{
each_single([](Object *arg) -> ObjectPtr {
throw SpecialFlowException(arg->shared_from_this());
});
return NIL_VALUE;
}
catch (const SpecialFlowException &e) { return e.value; }
}
else
{
Number *n;
unpack(args, &n);
return take(n);
}
}
ObjectPtr Enumerable::flat_map(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto arr = create_object<Array>();
each2({}, [&arr, proc](const FunctionArgs &args) {
auto value = proc->call(args);
if (auto value_arr = dynamic_cast<Array*>(value.get()))
for (auto &i : *value_arr) arr->push_back(i);
else arr->push_back(value);
return NIL_VALUE;
});
return arr;
}
else return make_enumerator(this_obj(), this, &Enumerable::flat_map, "flat_map");
}
ObjectPtr Enumerable::group_by(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto hash = create_object<Hash>();
each2({}, [&hash, proc](const FunctionArgs &args) {
auto key = proc->call(args);
auto arr = coerce<Array>(hash->get_or_create<Array>(key));
arr->push_back(args.size() == 1 ? args[0] : make_value(args));
return NIL_VALUE;
});
return hash;
}
else return make_enumerator(this_obj(), this, &Enumerable::group_by, "group_by");
}
Ptr<Boolean> Enumerable::include_q(Object *obj)
{
try
{
each_single([obj](Object *arg) {
if (arg->eq(obj)) throw SpecialFlowException(arg->shared_from_this());
return NIL_VALUE;
});
return FALSE_VALUE;
}
catch (const SpecialFlowException &) { return TRUE_VALUE; }
}
ObjectPtr Enumerable::map(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto ret = create_object<Array>();
each2({}, [ret, proc](const FunctionArgs &args) {
ret->push_back(proc->call(args));
return NIL_VALUE;
});
return ret;
}
else return make_enumerator(this_obj(), this, &Enumerable::map, "map");
}
namespace
{
void minmax_args(const FunctionArgs &args, Proc **proc, int *n)
{
if (args.size() == 0)
{
*proc = nullptr;
*n = 1;
}
else if (args.size() == 1)
{
*proc = dynamic_cast<Proc*>(args[0].get());
if (*proc) *n = 1;
else *n = (int)coerce<Number>(args[0])->get_value();
}
else if (args.size() == 2)
{
*n = (int)coerce<Number>(args[0])->get_value();
*proc = coerce<Proc>(args[1]).get();
}
else throw ArgumentCountError(args.size(), 0, 2);
}
template<class T> ObjectPtr do_min(Enumerable *self, int n, T cmp)
{
if (n == 0) return make_array({});
else if (n == 1)
{
ObjectPtr min = nullptr;
self->each_single([&min, cmp](Object *nextp) {
auto next = nextp->shared_from_this();
if (!min) min = next;
else if (cmp(next, min)) min = next;
return NIL_VALUE;
});
return min ? min : NIL_VALUE;
}
else if (n > 1)
{
std::deque<ObjectPtr> arr;
self->each_single([&arr, cmp, n](Object *nextp) {
auto next = nextp->shared_from_this();
arr.insert(std::upper_bound(arr.begin(), arr.end(), next, cmp), next);
if (arr.size() > (size_t)n) arr.pop_back();
return NIL_VALUE;
});
return make_array({arr.begin(), arr.end()});
}
else throw ArgumentError("negative size (" + std::to_string(n) + ")");
}
}
ObjectPtr Enumerable::max(const FunctionArgs &args)
{
Proc *proc;
int n;
minmax_args(args, &proc, &n);
if (proc)
{
return do_min(this, n, [proc](ObjectPtr a, ObjectPtr b) {
return coerce<Number>(proc->call({ a, b }))->get_value() > 0;
});
}
else
{
return do_min(this, n, [](ObjectPtr a, ObjectPtr b) {
return slim::cmp(a.get(), b.get()) > 0;
});
}
}
ObjectPtr Enumerable::max_by(const FunctionArgs &args)
{
Proc *proc;
int n;
minmax_args(args, &proc, &n);
if (proc)
{
return do_min(this, n, [proc](ObjectPtr a, ObjectPtr b) {
return slim::cmp(proc->call({a}).get(), proc->call({b}).get()) > 0;
});
}
else return make_enumerator(this_obj(), this, &Enumerable::max_by, "max_by", args);
}
ObjectPtr Enumerable::min(const FunctionArgs &args)
{
Proc *proc;
int n;
minmax_args(args, &proc, &n);
if (proc)
{
return do_min(this, n, [proc](ObjectPtr a, ObjectPtr b) {
return coerce<Number>(proc->call({ a, b }))->get_value() < 0;
});
}
else
{
return do_min(this, n, [](ObjectPtr a, ObjectPtr b) {
return slim::cmp(a.get(), b.get()) < 0;
});
}
}
ObjectPtr Enumerable::min_by(const FunctionArgs &args)
{
Proc *proc;
int n;
minmax_args(args, &proc, &n);
if (proc)
{
return do_min(this, n, [proc](ObjectPtr a, ObjectPtr b) {
return slim::cmp(proc->call({ a }).get(), proc->call({ b }).get()) < 0;
});
}
else return make_enumerator(this_obj(), this, &Enumerable::min_by, "min_by", args);
}
namespace
{
template<class T> ObjectPtr do_minmax(Enumerable *self, T cmp)
{
ObjectPtr min = nullptr, max = nullptr;
self->each_single([&min, &max, cmp](Object *nextp) {
auto next = nextp->shared_from_this();
if (!min) min = max = next;
else
{
if (cmp(next, min) < 0) min = next;
if (cmp(next, max) > 0) max = next;
}
return NIL_VALUE;
});
return make_array({min ? min : NIL_VALUE, max ? max : NIL_VALUE});
}
}
ObjectPtr Enumerable::minmax(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
return do_minmax(this, [proc](ObjectPtr a, ObjectPtr b) {
return (int)coerce<Number>(proc->call({ a, b }))->get_value();
});
}
else
{
return do_minmax(this, [](ObjectPtr a, ObjectPtr b) {
return slim::cmp(a.get(), b.get());
});
}
}
ObjectPtr Enumerable::minmax_by(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
return do_minmax(this, [proc](ObjectPtr a, ObjectPtr b) {
return slim::cmp(proc->call({a}).get(), proc->call({b}).get());
});
}
else return make_enumerator(this_obj(), this, &Enumerable::minmax_by, "minmax_by");
}
Ptr<Boolean> Enumerable::none_q(const FunctionArgs &args)
{
return make_value(!any_q(args)->is_true());
}
Ptr<Boolean> Enumerable::one_q(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
try
{
bool found = false;
if (proc)
{
each2({}, [&found, proc](const FunctionArgs &args) {
if (proc->call(args)->is_true())
{
if (found) throw SpecialFlowException();
else found = true;
}
return NIL_VALUE;
});
}
else
{
each2({}, [&found](const FunctionArgs &args) {
if ((args.size() > 1 || args[0]->is_true()))
{
if (found) throw SpecialFlowException();
else found = true;
}
return NIL_VALUE;
});
}
return make_value(found);
}
catch (const SpecialFlowException &) { return FALSE_VALUE; }
}
ObjectPtr Enumerable::partition(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto true_arr = create_object<Array>();
auto false_arr = create_object<Array>();
each2({}, [proc, true_arr, false_arr](const FunctionArgs &args) {
(proc->call(args)->is_true() ? true_arr : false_arr)->push_back(
args.size() == 1 ? args[0] : make_array(args));
return NIL_VALUE;
});
return make_array({true_arr, false_arr});
}
else return make_enumerator(this_obj(), this, &Enumerable::partition, "partition");
}
ObjectPtr Enumerable::reduce(const FunctionArgs &args)
{
ObjectPtr value = nullptr;
Proc *proc;
if (args.size() == 1) proc = coerce<Proc>(args[0].get());
else if (args.size() == 2)
{
value = args[0];
proc = coerce<Proc>(args[1].get());
}
else throw ArgumentCountError(args.size(), 1, 2);
each_single({}, [&value, proc](Object *el) {
if (value) value = proc->call({value, el ->shared_from_this()});
else value = el->shared_from_this();
return NIL_VALUE;
});
return value ? value : NIL_VALUE;
}
ObjectPtr Enumerable::reject(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto ret = create_object<Array>();
each2({}, [ret, proc](const FunctionArgs &args) {
if (!proc->call(args)->is_true())
ret->push_back(args.size() == 1 ? args[0] : make_value(args));
return NIL_VALUE;
});
return ret;
}
else return make_enumerator(this_obj(), this, &Enumerable::reject, "reject", args);
}
ObjectPtr Enumerable::reverse_each(const FunctionArgs &args)
{
Proc *proc = nullptr;
if (!args.empty()) proc = dynamic_cast<Proc*>(args.back().get());
if (proc)
{
FunctionArgs args2 = {args.begin(), args.end() - 1};
auto arr = to_a(args2);
return arr->reverse_each({proc->shared_from_this()});
}
else return make_enumerator(this_obj(), this, &Enumerable::reverse_each, "reverse_each", args);
}
ObjectPtr Enumerable::select(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto ret = create_object<Array>();
each2({}, [ret, proc](const FunctionArgs &args) {
if (proc->call(args)->is_true())
ret->push_back(args.size() == 1 ? args[0] : make_value(args));
return NIL_VALUE;
});
return ret;
}
else return make_enumerator(this_obj(), this, &Enumerable::select, "select", args);
}
Ptr<Array> Enumerable::sort(const FunctionArgs &args)
{
return to_a({})->sort(args);
}
ObjectPtr Enumerable::sort_by(const FunctionArgs &args)
{
return to_a({})->sort_by(args);
}
Ptr<Array> Enumerable::take(Number *n_obj)
{
int n = (int)n_obj->get_value();
if (n < 0) throw ArgumentError("negative array size");
auto ret = create_object<Array>();
try
{
each_single([ret, n](Object *arg) -> ObjectPtr {
ret->push_back(arg->shared_from_this());
if (ret->get_value().size() >= (size_t)n)
throw SpecialFlowException();
else return NIL_VALUE;
});
}
catch (const SpecialFlowException &) {}
return ret;
}
ObjectPtr Enumerable::take_while(const FunctionArgs &args)
{
Proc *proc = nullptr;
unpack<0>(args, &proc);
if (proc)
{
auto ret = create_object<Array>();
try
{
each2({}, [ret, proc](const FunctionArgs &args) {
if (!proc->call(args)->is_true())
throw SpecialFlowException();
ret->push_back(args.size() == 1 ? args[0] : make_value(args));
return NIL_VALUE;
});
}
catch (const SpecialFlowException &) {}
return ret;
}
else return make_enumerator(this_obj(), this, &Enumerable::take_while, "take_while", args);
}
Ptr<Array> Enumerable::to_a(const FunctionArgs &args)
{
auto ret = create_object<Array>();
each2(args, [ret](const FunctionArgs &args)
{
if (args.size() == 1) ret->push_back(args[0]);
else ret->push_back(make_value(args));
return NIL_VALUE;
});
return ret;
}
Ptr<Hash> Enumerable::to_h(const FunctionArgs &args)
{
auto ret = create_object<Hash>();
each2(args, [ret](const FunctionArgs &args)
{
if (args.size() == 2) ret->set(args[0], args[1]);
else if (args.size() == 1)
{
auto arr = coerce<Array>(args[0]);
if (arr->get_value().size() == 2)
{
ret->set(arr->get_value()[0], arr->get_value()[1]);
}
else
{
std::stringstream ss;
ss << "wrong array length. expected 2, was " << arr->get_value().size();
throw ArgumentError(ss.str());
}
}
else throw ArgumentCountError(args.size(), 2, 2);
return NIL_VALUE;
});
return ret;
}
}
|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/sys/inspect/cpp/component.h>
#include <lib/syslog/global.h>
#include <lib/trace-provider/provider.h>
#include <lib/trace/event.h>
#include "dart_runner.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/trace_event.h"
#include "logging.h"
#include "platform/utils.h"
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/tempfs.h"
#include "third_party/dart/runtime/include/dart_api.h"
#if !defined(DART_PRODUCT)
// Register native symbol information for the Dart VM's profiler.
static void RegisterProfilerSymbols(const char* symbols_path,
const char* dso_name) {
std::string* symbols = new std::string();
if (dart_utils::ReadFileToString(symbols_path, symbols)) {
Dart_AddSymbols(dso_name, symbols->data(), symbols->size());
} else {
FML_LOG(ERROR) << "Failed to load " << symbols_path;
FML_CHECK(false);
}
}
#endif // !defined(DART_PRODUCT)
int main(int argc, const char** argv) {
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
// Create our component context which is served later.
auto context = sys::ComponentContext::Create();
sys::ComponentInspector inspector(context.get());
inspect::Node& root = inspector.inspector()->GetRoot();
dart::SetDartVmNode(std::make_unique<inspect::Node>(root.CreateChild("vm")));
std::unique_ptr<trace::TraceProviderWithFdio> provider;
{
bool already_started;
// Use CreateSynchronously to prevent loss of early events.
trace::TraceProviderWithFdio::CreateSynchronously(
loop.dispatcher(), "dart_runner", &provider, &already_started);
}
#if !defined(DART_PRODUCT)
#if defined(AOT_RUNTIME)
RegisterProfilerSymbols("pkg/data/dart_aot_runner.dartprofilersymbols", "");
#else
RegisterProfilerSymbols("pkg/data/dart_jit_runner.dartprofilersymbols", "");
#endif // defined(AOT_RUNTIME)
#endif // !defined(DART_PRODUCT)
dart_utils::RunnerTemp runner_temp;
dart_runner::DartRunner runner(context.get());
// Wait to serve until we have finished all of our setup.
context->outgoing()->ServeFromStartupInfo();
loop.Run();
return 0;
}
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cdb/v20170320/model/DeviceNetInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdb::V20170320::Model;
using namespace std;
DeviceNetInfo::DeviceNetInfo() :
m_connHasBeenSet(false),
m_packageInHasBeenSet(false),
m_packageOutHasBeenSet(false),
m_flowInHasBeenSet(false),
m_flowOutHasBeenSet(false)
{
}
CoreInternalOutcome DeviceNetInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Conn") && !value["Conn"].IsNull())
{
if (!value["Conn"].IsArray())
return CoreInternalOutcome(Core::Error("response `DeviceNetInfo.Conn` is not array type"));
const rapidjson::Value &tmpValue = value["Conn"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_conn.push_back((*itr).GetInt64());
}
m_connHasBeenSet = true;
}
if (value.HasMember("PackageIn") && !value["PackageIn"].IsNull())
{
if (!value["PackageIn"].IsArray())
return CoreInternalOutcome(Core::Error("response `DeviceNetInfo.PackageIn` is not array type"));
const rapidjson::Value &tmpValue = value["PackageIn"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_packageIn.push_back((*itr).GetInt64());
}
m_packageInHasBeenSet = true;
}
if (value.HasMember("PackageOut") && !value["PackageOut"].IsNull())
{
if (!value["PackageOut"].IsArray())
return CoreInternalOutcome(Core::Error("response `DeviceNetInfo.PackageOut` is not array type"));
const rapidjson::Value &tmpValue = value["PackageOut"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_packageOut.push_back((*itr).GetInt64());
}
m_packageOutHasBeenSet = true;
}
if (value.HasMember("FlowIn") && !value["FlowIn"].IsNull())
{
if (!value["FlowIn"].IsArray())
return CoreInternalOutcome(Core::Error("response `DeviceNetInfo.FlowIn` is not array type"));
const rapidjson::Value &tmpValue = value["FlowIn"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_flowIn.push_back((*itr).GetInt64());
}
m_flowInHasBeenSet = true;
}
if (value.HasMember("FlowOut") && !value["FlowOut"].IsNull())
{
if (!value["FlowOut"].IsArray())
return CoreInternalOutcome(Core::Error("response `DeviceNetInfo.FlowOut` is not array type"));
const rapidjson::Value &tmpValue = value["FlowOut"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_flowOut.push_back((*itr).GetInt64());
}
m_flowOutHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void DeviceNetInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_connHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Conn";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_conn.begin(); itr != m_conn.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetInt64(*itr), allocator);
}
}
if (m_packageInHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PackageIn";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_packageIn.begin(); itr != m_packageIn.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetInt64(*itr), allocator);
}
}
if (m_packageOutHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PackageOut";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_packageOut.begin(); itr != m_packageOut.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetInt64(*itr), allocator);
}
}
if (m_flowInHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FlowIn";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_flowIn.begin(); itr != m_flowIn.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetInt64(*itr), allocator);
}
}
if (m_flowOutHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FlowOut";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_flowOut.begin(); itr != m_flowOut.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetInt64(*itr), allocator);
}
}
}
vector<int64_t> DeviceNetInfo::GetConn() const
{
return m_conn;
}
void DeviceNetInfo::SetConn(const vector<int64_t>& _conn)
{
m_conn = _conn;
m_connHasBeenSet = true;
}
bool DeviceNetInfo::ConnHasBeenSet() const
{
return m_connHasBeenSet;
}
vector<int64_t> DeviceNetInfo::GetPackageIn() const
{
return m_packageIn;
}
void DeviceNetInfo::SetPackageIn(const vector<int64_t>& _packageIn)
{
m_packageIn = _packageIn;
m_packageInHasBeenSet = true;
}
bool DeviceNetInfo::PackageInHasBeenSet() const
{
return m_packageInHasBeenSet;
}
vector<int64_t> DeviceNetInfo::GetPackageOut() const
{
return m_packageOut;
}
void DeviceNetInfo::SetPackageOut(const vector<int64_t>& _packageOut)
{
m_packageOut = _packageOut;
m_packageOutHasBeenSet = true;
}
bool DeviceNetInfo::PackageOutHasBeenSet() const
{
return m_packageOutHasBeenSet;
}
vector<int64_t> DeviceNetInfo::GetFlowIn() const
{
return m_flowIn;
}
void DeviceNetInfo::SetFlowIn(const vector<int64_t>& _flowIn)
{
m_flowIn = _flowIn;
m_flowInHasBeenSet = true;
}
bool DeviceNetInfo::FlowInHasBeenSet() const
{
return m_flowInHasBeenSet;
}
vector<int64_t> DeviceNetInfo::GetFlowOut() const
{
return m_flowOut;
}
void DeviceNetInfo::SetFlowOut(const vector<int64_t>& _flowOut)
{
m_flowOut = _flowOut;
m_flowOutHasBeenSet = true;
}
bool DeviceNetInfo::FlowOutHasBeenSet() const
{
return m_flowOutHasBeenSet;
}
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "cell_type.h"
#include <stdio.h>
#include <cstdlib>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/util/stringfmt.h>
using vespalib::make_string_short::fmt;
namespace vespalib::eval {
uint32_t
CellTypeUtils::alignment(CellType cell_type)
{
return TypifyCellType::resolve(cell_type, [](auto t)->uint32_t
{
using T = decltype(t)::type;
return alignof(T);
});
}
size_t
CellTypeUtils::mem_size(CellType cell_type, size_t sz)
{
return TypifyCellType::resolve(cell_type, [sz](auto t)->size_t
{
using T = decltype(t)::type;
return (sz * sizeof(T));
});
}
std::vector<CellType>
CellTypeUtils::list_types()
{
return {CellType::FLOAT, CellType::DOUBLE};
}
}
|
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
#ifndef SIM_TOPLOGICAL_REPRESENTATION_TOPOLOGICAL_REPRESENTATION_DEFAULT_HXX
#define SIM_TOPLOGICAL_REPRESENTATION_TOPOLOGICAL_REPRESENTATION_DEFAULT_HXX
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/config.hxx>
#if (XSD_INT_VERSION != 4000000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
namespace xml_schema
{
// anyType and anySimpleType.
//
typedef ::xsd::cxx::tree::type type;
typedef ::xsd::cxx::tree::simple_type< char, type > simple_type;
typedef ::xsd::cxx::tree::type container;
// 8-bit
//
typedef signed char byte;
typedef unsigned char unsigned_byte;
// 16-bit
//
typedef short short_;
typedef unsigned short unsigned_short;
// 32-bit
//
typedef int int_;
typedef unsigned int unsigned_int;
// 64-bit
//
typedef long long long_;
typedef unsigned long long unsigned_long;
// Supposed to be arbitrary-length integral types.
//
typedef long long integer;
typedef long long non_positive_integer;
typedef unsigned long long non_negative_integer;
typedef unsigned long long positive_integer;
typedef long long negative_integer;
// Boolean.
//
typedef bool boolean;
// Floating-point types.
//
typedef float float_;
typedef double double_;
typedef double decimal;
// String types.
//
typedef ::xsd::cxx::tree::string< char, simple_type > string;
typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string;
typedef ::xsd::cxx::tree::token< char, normalized_string > token;
typedef ::xsd::cxx::tree::name< char, token > name;
typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken;
typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens;
typedef ::xsd::cxx::tree::ncname< char, name > ncname;
typedef ::xsd::cxx::tree::language< char, token > language;
// ID/IDREF.
//
typedef ::xsd::cxx::tree::id< char, ncname > id;
typedef ::xsd::cxx::tree::idref< char, ncname, type > idref;
typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs;
// URI.
//
typedef ::xsd::cxx::tree::uri< char, simple_type > uri;
// Qualified name.
//
typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname;
// Binary.
//
typedef ::xsd::cxx::tree::buffer< char > buffer;
typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary;
typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary;
// Date/time.
//
typedef ::xsd::cxx::tree::time_zone time_zone;
typedef ::xsd::cxx::tree::date< char, simple_type > date;
typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time;
typedef ::xsd::cxx::tree::duration< char, simple_type > duration;
typedef ::xsd::cxx::tree::gday< char, simple_type > gday;
typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth;
typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day;
typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear;
typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month;
typedef ::xsd::cxx::tree::time< char, simple_type > time;
// Entity.
//
typedef ::xsd::cxx::tree::entity< char, ncname > entity;
typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities;
typedef ::xsd::cxx::tree::content_order content_order;
// Flags and properties.
//
typedef ::xsd::cxx::tree::flags flags;
typedef ::xsd::cxx::tree::properties< char > properties;
// Parsing/serialization diagnostics.
//
typedef ::xsd::cxx::tree::severity severity;
typedef ::xsd::cxx::tree::error< char > error;
typedef ::xsd::cxx::tree::diagnostics< char > diagnostics;
// Exceptions.
//
typedef ::xsd::cxx::tree::exception< char > exception;
typedef ::xsd::cxx::tree::bounds< char > bounds;
typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id;
typedef ::xsd::cxx::tree::parsing< char > parsing;
typedef ::xsd::cxx::tree::expected_element< char > expected_element;
typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element;
typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute;
typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator;
typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content;
typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping;
typedef ::xsd::cxx::tree::no_type_info< char > no_type_info;
typedef ::xsd::cxx::tree::not_derived< char > not_derived;
// Error handler callback interface.
//
typedef ::xsd::cxx::xml::error_handler< char > error_handler;
// DOM interaction.
//
namespace dom
{
// Automatic pointer for DOMDocument.
//
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
// DOM user data key for back pointers to tree nodes.
//
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
// Forward declarations.
//
namespace schema
{
namespace simxml
{
namespace ResourcesGeometry
{
class SimToplogicalRepresentation_TopologicalRepresentation_Default;
}
}
}
#include <memory> // ::std::auto_ptr
#include <limits> // std::numeric_limits
#include <algorithm> // std::binary_search
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/containers.hxx>
#include <xsd/cxx/tree/list.hxx>
#include <xsd/cxx/xml/dom/parsing-header.hxx>
#include "simtoplogicalrepresentation_topologicalrepresentation.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeometry
{
class SimToplogicalRepresentation_TopologicalRepresentation_Default: public ::schema::simxml::ResourcesGeometry::SimToplogicalRepresentation_TopologicalRepresentation
{
public:
// Constructors.
//
SimToplogicalRepresentation_TopologicalRepresentation_Default ();
SimToplogicalRepresentation_TopologicalRepresentation_Default (const RefId_type&);
SimToplogicalRepresentation_TopologicalRepresentation_Default (const ::xercesc::DOMElement& e,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
SimToplogicalRepresentation_TopologicalRepresentation_Default (const SimToplogicalRepresentation_TopologicalRepresentation_Default& x,
::xml_schema::flags f = 0,
::xml_schema::container* c = 0);
virtual SimToplogicalRepresentation_TopologicalRepresentation_Default*
_clone (::xml_schema::flags f = 0,
::xml_schema::container* c = 0) const;
virtual
~SimToplogicalRepresentation_TopologicalRepresentation_Default ();
};
}
}
}
#include <iosfwd>
#include <xercesc/sax/InputSource.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMErrorHandler.hpp>
namespace schema
{
namespace simxml
{
namespace ResourcesGeometry
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // SIM_TOPLOGICAL_REPRESENTATION_TOPOLOGICAL_REPRESENTATION_DEFAULT_HXX
|
//
// UIImagePickerCell.cpp
// DigMMMac
//
// Created by Raptis, Nicholas on 7/3/18.
// Copyright © 2018 Darkswarm LLC. All rights reserved.
//
#include "UIImagePickerCell.hpp"
#include "UIImagePicker.hpp"
UIImagePickerCell::UIImagePickerCell() {
mName = "Image Cell (Blank)";
mDestroySprite = false;
mSprite = 0;
mTouchCanceled = false;
}
UIImagePickerCell::UIImagePickerCell(FSprite *pSprite, bool pDestroy) {
mName = "Image Cell (Sprite)";
mDestroySprite = pDestroy;
mSprite = pSprite;
}
UIImagePickerCell::UIImagePickerCell(const char *pPath) {
mName = "Image Cell (Sprite File)";
mSprite = new FSprite();
mSprite->Load(pPath);
mDestroySprite = true;
}
UIImagePickerCell::~UIImagePickerCell() {
if (mDestroySprite == true) {
if (mSprite != 0) {
delete mSprite;
mSprite = 0;
}
}
}
void UIImagePickerCell::SetUp(float pWidth, float pHeight) {
SetUp(mX, mY, mWidth, mHeight);
}
void UIImagePickerCell::SetUp(float pX, float pY, float pWidth, float pHeight) {
SetFrame(pX, pY, pWidth, pHeight);
mSpriteQuad.SetQuad(0.0f, 0.0f, pWidth, 0.0f, 0.0f, pHeight, pWidth, pHeight);
if (mSprite) {
mSpriteQuad.SetTextureAspectFit(mSprite);
}
}
void UIImagePickerCell::Update()
{
}
void UIImagePickerCell::Draw()
{
Graphics::SetColor();
if (mSprite) {
mSpriteQuad.Draw(mSprite);
}
if (mTouchDownInside) {
Graphics::SetColor(1.0f, 0.15f, 0.15f, 0.75f);
}
else Graphics::SetColor(0.85f, 0.85f, 0.85f, 0.75f);
Graphics::OutlineRectInside(0.0f, 0.0f, mWidth, mHeight, 2);
Graphics::SetColor();
}
void UIImagePickerCell::TouchUp(float pX, float pY, void *pData) {
if ((mTouchCanceled == false) && (mParent != 0)) {
if (mParent) {
if (mParent->mParent) {
mParent->mParent->Notify(this, "pick_image");
}
}
}
mTouchCanceled = false;
}
UIImagePickerCellSequence::UIImagePickerCellSequence() {
mSequence = 0;
mFrame = 0;
mFrameMax = 1.0f;
}
UIImagePickerCellSequence::UIImagePickerCellSequence(FSpriteSequence *pSequence, bool pDestroy) {
mSequence = pSequence;
if (mSequence) {
mFrameMax = mSequence->GetMaxFrame();
mDestroySprite = pDestroy;
}
mFrame = 0;
mFrameMax = 1.0f;
}
UIImagePickerCellSequence::~UIImagePickerCellSequence() {
if (mDestroySprite) {
if (mSequence != 0) {
delete mSequence;
}
mSequence = 0;
}
}
void UIImagePickerCellSequence::SetUp(float pWidth, float pHeight) {
SetUp(mX, mY, pWidth, pHeight);
}
void UIImagePickerCellSequence::SetUp(float pX, float pY, float pWidth, float pHeight) {
if (mSequence) {
mSprite = mSequence->Get(mFrame);
mFrameMax = mSequence->GetMaxFrame();
}
UIImagePickerCell::SetUp(pX, pY, pWidth, pHeight);
if (mSequence) {
mSprite = 0;
}
}
void UIImagePickerCellSequence::Update() {
UIImagePickerCell::Update();
if (mSequence) {
mFrameMax = mSequence->GetMaxFrame();
mFrame += 0.15f;
if(mFrame >= mFrameMax)mFrame -= mFrameMax;
}
}
void UIImagePickerCellSequence::Draw() {
if (mSequence) {
FSprite *aSprite = mSequence->GetSprite(mFrame);
SetUp(mX, mY, mWidth, mHeight);
mSprite = aSprite;
}
UIImagePickerCell::Draw();
mSprite = 0;
}
void UIImagePickerCellSequence::TouchUp(float pX, float pY, void *pData) {
if ((mTouchCanceled == false) && (mParent != 0)) {
if (mParent) {
if (mParent->mParent) {
mParent->mParent->Notify(this, "pick_image_sequence");
}
}
}
mTouchCanceled = false;
}
|
/*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
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 University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 02/12/2011
Tom Zhou, 01/11/2013, support secure flag for authentication
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Packet Header |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | |
// ~ Data / Control Information Field ~
// | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0|s| Sequence Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |ff |o| Message Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Time Stamp |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Destination Socket ID |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Message Authentication Code |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// bit 0:
// 0: Data Packet
// 1: Control Packet
// bit s: TBD...
// 0: Not Secure Packet
// 1: Secure Packet
// bit ff:
// 11: solo message packet
// 10: first packet of a message
// 01: last packet of a message
// bit o:
// 0: in order delivery not required
// 1: in order delivery required
//
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |1|s| Type | Reserved |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Additional Info |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Time Stamp |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Destination Socket ID |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Message Authentication Code |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// bit s: TBD...
// 0: Not Secure Packet
// 1: Secure Packet
// bit 1-15:
// 0: Protocol Connection Handshake
// Add. Info: Undefined
// Control Info: Handshake information (see CHandShake)
// 1: Keep-alive
// Add. Info: Undefined
// Control Info: None
// 2: Acknowledgement (ACK)
// Add. Info: The ACK sequence number
// Control Info: The sequence number to which (but not include) all the previous packets have beed received
// Optional: RTT
// RTT Variance
// available receiver buffer size (in bytes)
// advertised flow window size (number of packets)
// estimated bandwidth (number of packets per second)
// 3: Negative Acknowledgement (NAK)
// Add. Info: Undefined
// Control Info: Loss list (see loss list coding below)
// 4: Congestion/Delay Warning
// Add. Info: Undefined
// Control Info: None
// 5: Shutdown
// Add. Info: Undefined
// Control Info: None
// 6: Acknowledgement of Acknowledement (ACK-square)
// Add. Info: The ACK sequence number
// Control Info: None
// 7: Message Drop Request
// Add. Info: Message ID
// Control Info: first sequence number of the message
// last seqeunce number of the message
// 8: Error Signal from the Peer Side
// Add. Info: Error code
// Control Info: None
// 0x7FFF: Explained by bits 16 - 31
//
// bit 16 - 31:
// This space is used for future expansion or user defined control packets.
//
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |1| Sequence Number a (first) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0| Sequence Number b (last) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0| Sequence Number (single) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// Loss List Field Coding:
// For any consectutive lost seqeunce numbers that the differnece between
// the last and first is more than 1, only record the first (a) and the
// the last (b) sequence numbers in the loss list field, and modify the
// the first bit of a to 1.
// For any single loss or consectutive loss less than 2 packets, use
// the original sequence numbers in the field.
#include <cstring>
#include "md5.h"
#include "packet.h"
const int CPacket::m_iPktHdrSize = 20; // 128-bit standard header + 32-bit MAC
const int CHandShake::m_iContentSize = 48;
// Set up the aliases in the constructure
CPacket::CPacket():
m_iSeqNo((int32_t&)(m_nHeader[0])),
m_iMsgNo((int32_t&)(m_nHeader[1])),
m_iTimeStamp((int32_t&)(m_nHeader[2])),
m_iID((int32_t&)(m_nHeader[3])),
m_iMAC((int32_t&)(m_nHeader[4])),
m_pcData((char*&)(m_PacketVector[1].iov_base)),
__pad(0)
{
for (int i = 0; i < 5; ++ i)
m_nHeader[i] = 0;
m_PacketVector[0].iov_base = (char *)m_nHeader;
m_PacketVector[0].iov_len = CPacket::m_iPktHdrSize;
m_PacketVector[1].iov_base = NULL;
m_PacketVector[1].iov_len = 0;
}
CPacket::~CPacket()
{
}
int CPacket::getLength() const
{
return m_PacketVector[1].iov_len;
}
void CPacket::setLength(int len)
{
m_PacketVector[1].iov_len = len;
}
void CPacket::pack(int pkttype, void* lparam, void* rparam, int size)
{
pkttype &= 0x3FFF;
// Set (bit-0 = 1), (bit-1 = secure flag reserved) and (bit-2~15 = type)
m_nHeader[0] = 0x80000000 | (pkttype << 16);
// Set additional information and control information field
switch (pkttype)
{
case 2: //0010 - Acknowledgement (ACK)
// ACK packet seq. no.
if (NULL != lparam)
m_nHeader[1] = *(int32_t *)lparam;
// data ACK seq. no.
// optional: RTT (microsends), RTT variance (microseconds) advertised flow window size (packets), and estimated link capacity (packets per second)
m_PacketVector[1].iov_base = (char *)rparam;
m_PacketVector[1].iov_len = size;
break;
case 6: //0110 - Acknowledgement of Acknowledgement (ACK-2)
// ACK packet seq. no.
m_nHeader[1] = *(int32_t *)lparam;
// control info field should be none
// but "writev" does not allow this
m_PacketVector[1].iov_base = (char *)&__pad; //NULL;
m_PacketVector[1].iov_len = 4; //0;
break;
case 3: //0011 - Loss Report (NAK)
// loss list
m_PacketVector[1].iov_base = (char *)rparam;
m_PacketVector[1].iov_len = size;
break;
case 4: //0100 - Congestion Warning
// control info field should be none
// but "writev" does not allow this
m_PacketVector[1].iov_base = (char *)&__pad; //NULL;
m_PacketVector[1].iov_len = 4; //0;
break;
case 1: //0001 - Keep-alive and used to hole punching before connect
// control info field should be none
// but "writev" does not allow this
m_PacketVector[1].iov_base = (char *)&__pad; //NULL;
m_PacketVector[1].iov_len = 4; //0;
break;
case 0: //0000 - Handshake
// control info filed is handshake info
m_PacketVector[1].iov_base = (char *)rparam;
m_PacketVector[1].iov_len = size; //sizeof(CHandShake);
break;
case 5: //0101 - Shutdown
// control info field should be none
// but "writev" does not allow this
m_PacketVector[1].iov_base = (char *)&__pad; //NULL;
m_PacketVector[1].iov_len = 4; //0;
break;
case 7: //0111 - Message Drop Request
// msg id
m_nHeader[1] = *(int32_t *)lparam;
//first seq no, last seq no
m_PacketVector[1].iov_base = (char *)rparam;
m_PacketVector[1].iov_len = size;
break;
case 8: //1000 - Error Signal from the Peer Side
// Error type
m_nHeader[1] = *(int32_t *)lparam;
// control info field should be none
// but "writev" does not allow this
m_PacketVector[1].iov_base = (char *)&__pad; //NULL;
m_PacketVector[1].iov_len = 4; //0;
break;
case 16383: //0x3FFF - Reserved for user defined control packets
// for extended control packet
// "lparam" contains the extended type information for bit 16 - 31
// "rparam" is the control information
m_nHeader[0] |= *(int32_t *)lparam;
if (NULL != rparam)
{
m_PacketVector[1].iov_base = (char *)rparam;
m_PacketVector[1].iov_len = size;
}
else
{
m_PacketVector[1].iov_base = (char *)&__pad;
m_PacketVector[1].iov_len = 4;
}
break;
default:
break;
}
}
iovec* CPacket::getPacketVector()
{
return m_PacketVector;
}
int CPacket::getFlag() const
{
// read bit 0
return m_nHeader[0] >> 31;
}
int CPacket::getType() const
{
// read bit 2~15
return (m_nHeader[0] >> 16) & 0x00003FFF;
}
uint32_t CPacket::getMAC() const
{
if (m_nHeader[0] & 0x40000000) {
// read bit 128-159
return m_nHeader[4];
} else {
// invalid MAC
return 0;
}
}
// calculating MAC using MD5
int CPacket::setMAC(const unsigned char* key, const int len)
{
md5_state_t state;
uint32_t digest[4];
/*printf("pkt.type %d,setMAC:", getType());
for (int i=0; i<len; i++) {
printf("%02x ", key[i]);
}
printf("\n");
*/
// nothing to do again
if (m_nHeader[0] & 0x40000000) {
return m_nHeader[4];
}
// set security flag
m_nHeader[0] |= 0x40000000;
m_nHeader[4] = 0x0;
// round 1
md5_init_key(&state, key, len);
md5_append(&state, (const md5_byte_t *)m_PacketVector[0].iov_base, m_PacketVector[0].iov_len);
if (m_PacketVector[1].iov_base && m_PacketVector[1].iov_len) {
md5_append(&state, (const md5_byte_t *)m_PacketVector[1].iov_base, m_PacketVector[1].iov_len);
}
md5_finish(&state, (md5_byte_t *)digest);
// round 2
md5_init_key(&state, key, len);
md5_append(&state, (const md5_byte_t *)digest, sizeof(digest));
md5_finish(&state, (md5_byte_t *)digest);
m_nHeader[4] = digest[0] ^ digest[1] ^ digest[2] ^ digest[3];
return m_nHeader[4];
}
// 1: pass, 0: fail, -1: bypass
int CPacket::chkMAC(const unsigned char* key, const int len)
{
md5_state_t state;
uint32_t digest[4];
uint32_t expect;
/*printf("pkt.type %d,chkMAC [0]-0x%x [4]-0x%x:",
getType(), m_nHeader[0], m_nHeader[4]);
for (int i=0; i<len; i++) {
printf("%02x ", key[i]);
}
printf("\n");
*/
// check security flag
if (!(m_nHeader[0] & 0x40000000)) {
// bypass ACK,ACK-2 packet check for connection in early setup stage
if (getType() != 2 && getType() != 6)
return 0; // fail
else
return -1; // bypass
}
// save then clear MAC
expect = m_nHeader[4];
m_nHeader[4] = 0x0;
// round 1
md5_init_key(&state, key, len);
md5_append(&state, (const md5_byte_t *)m_PacketVector[0].iov_base, m_PacketVector[0].iov_len);
if (m_PacketVector[1].iov_base && m_PacketVector[1].iov_len) {
md5_append(&state, (const md5_byte_t *)m_PacketVector[1].iov_base, m_PacketVector[1].iov_len);
}
md5_finish(&state, (md5_byte_t *)digest);
// round 2
md5_init_key(&state, key, len);
md5_append(&state, (const md5_byte_t *)digest, sizeof(digest));
md5_finish(&state, (md5_byte_t *)digest);
return (expect == (digest[0] ^ digest[1] ^ digest[2] ^ digest[3])) ? 1 : 0;
}
int CPacket::getExtendedType() const
{
// read bit 16~31
return m_nHeader[0] & 0x0000FFFF;
}
int32_t CPacket::getAckSeqNo() const
{
// read additional information field
return m_nHeader[1];
}
int CPacket::getMsgBoundary() const
{
// read [1] bit 0~1
return m_nHeader[1] >> 30;
}
bool CPacket::getMsgOrderFlag() const
{
// read [1] bit 2
return (1 == ((m_nHeader[1] >> 29) & 1));
}
int32_t CPacket::getMsgSeq() const
{
// read [1] bit 3~31
return m_nHeader[1] & 0x1FFFFFFF;
}
CPacket* CPacket::clone() const
{
CPacket* pkt = new CPacket;
memcpy(pkt->m_nHeader, m_nHeader, m_iPktHdrSize);
pkt->m_pcData = new char[m_PacketVector[1].iov_len];
memcpy(pkt->m_pcData, m_pcData, m_PacketVector[1].iov_len);
pkt->m_PacketVector[1].iov_len = m_PacketVector[1].iov_len;
return pkt;
}
CHandShake::CHandShake():
m_iVersion(0),
m_iType(0),
m_iISN(0),
m_iMSS(0),
m_iFlightFlagSize(0),
m_iReqType(0),
m_iID(0),
m_iCookie(0)
{
for (int i = 0; i < 4; ++ i)
m_piPeerIP[i] = 0;
}
int CHandShake::serialize(char* buf, int& size)
{
if (size < m_iContentSize)
return -1;
int32_t* p = (int32_t*)buf;
*p++ = m_iVersion;
*p++ = m_iType;
*p++ = m_iISN;
*p++ = m_iMSS;
*p++ = m_iFlightFlagSize;
*p++ = m_iReqType;
*p++ = m_iID;
*p++ = m_iCookie;
for (int i = 0; i < 4; ++ i)
*p++ = m_piPeerIP[i];
size = m_iContentSize;
return 0;
}
int CHandShake::deserialize(const char* buf, int size)
{
if (size < m_iContentSize)
return -1;
int32_t* p = (int32_t*)buf;
m_iVersion = *p++;
m_iType = *p++;
m_iISN = *p++;
m_iMSS = *p++;
m_iFlightFlagSize = *p++;
m_iReqType = *p++;
m_iID = *p++;
m_iCookie = *p++;
for (int i = 0; i < 4; ++ i)
m_piPeerIP[i] = *p++;
return 0;
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
MaterialGraphNode.cpp
=============================================================================*/
#include "UnrealEd.h"
#include "Materials/MaterialExpressionComponentMask.h"
#include "Materials/MaterialExpressionConstant.h"
#include "Materials/MaterialExpressionConstant2Vector.h"
#include "Materials/MaterialExpressionConstant3Vector.h"
#include "Materials/MaterialExpressionConstant4Vector.h"
#include "Materials/MaterialExpressionFontSample.h"
#include "Materials/MaterialExpressionFontSampleParameter.h"
#include "Materials/MaterialExpressionFunctionInput.h"
#include "Materials/MaterialExpressionFunctionOutput.h"
#include "Materials/MaterialExpressionMaterialFunctionCall.h"
#include "Materials/MaterialExpressionParameter.h"
#include "Materials/MaterialExpressionScalarParameter.h"
#include "Materials/MaterialExpressionStaticBool.h"
#include "Materials/MaterialExpressionStaticBoolParameter.h"
#include "Materials/MaterialExpressionTextureBase.h"
#include "Materials/MaterialExpressionTextureCoordinate.h"
#include "Materials/MaterialExpressionTextureSample.h"
#include "Materials/MaterialExpressionTextureSampleParameter.h"
#include "Materials/MaterialExpressionTextureObject.h"
#include "Materials/MaterialExpressionVectorParameter.h"
#include "Materials/MaterialFunction.h"
#include "MaterialEditorUtilities.h"
#include "MaterialEditorActions.h"
#include "GraphEditorActions.h"
#include "GraphEditorSettings.h"
#include "EditorClassUtils.h"
#include "GenericCommands.h"
#include "ScopedTransaction.h"
#define LOCTEXT_NAMESPACE "MaterialGraphNode"
/////////////////////////////////////////////////////
// UMaterialGraphNode
UMaterialGraphNode::UMaterialGraphNode(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, bPreviewNeedsUpdate(false)
, bIsErrorExpression(false)
, bIsPreviewExpression(false)
{
}
void UMaterialGraphNode::PostCopyNode()
{
// Make sure the MaterialExpression goes back to being owned by the Material after copying.
ResetMaterialExpressionOwner();
}
FMaterialRenderProxy* UMaterialGraphNode::GetExpressionPreview()
{
return FMaterialEditorUtilities::GetExpressionPreview(GetGraph(), MaterialExpression);
}
void UMaterialGraphNode::RecreateAndLinkNode()
{
// Throw away the original pins
for (int32 PinIndex = 0; PinIndex < Pins.Num(); ++PinIndex)
{
UEdGraphPin* Pin = Pins[PinIndex];
Pin->Modify();
Pin->BreakAllPinLinks();
#if 0
UEdGraphNode::ReturnPinToPool(Pin);
#else
Pin->Rename(NULL, GetTransientPackage(), REN_None);
Pin->RemoveFromRoot();
Pin->MarkPendingKill();
#endif
}
Pins.Empty();
AllocateDefaultPins();
CastChecked<UMaterialGraph>(GetGraph())->LinkGraphNodesFromMaterial();
}
void UMaterialGraphNode::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.Property)
{
const FName PropertyName = PropertyChangedEvent.Property->GetFName();
if (PropertyName == FName(TEXT("NodeComment")))
{
if (MaterialExpression)
{
MaterialExpression->Modify();
MaterialExpression->Desc = NodeComment;
}
}
}
}
void UMaterialGraphNode::PostEditImport()
{
// Make sure this MaterialExpression is owned by the Material it's being pasted into.
ResetMaterialExpressionOwner();
}
void UMaterialGraphNode::PostDuplicate(bool bDuplicateForPIE)
{
Super::PostDuplicate(bDuplicateForPIE);
if (!bDuplicateForPIE)
{
CreateNewGuid();
}
}
bool UMaterialGraphNode::CanPasteHere(const UEdGraph* TargetGraph) const
{
if (Super::CanPasteHere(TargetGraph))
{
const UMaterialGraph* MaterialGraph = Cast<const UMaterialGraph>(TargetGraph);
if (MaterialGraph)
{
// Check whether we're trying to paste a material function into a function that depends on it
UMaterialExpressionMaterialFunctionCall* FunctionExpression = Cast<UMaterialExpressionMaterialFunctionCall>(MaterialExpression);
bool bIsValidFunctionExpression = true;
if (MaterialGraph->MaterialFunction
&& FunctionExpression
&& FunctionExpression->MaterialFunction
&& FunctionExpression->MaterialFunction->IsDependent(MaterialGraph->MaterialFunction))
{
bIsValidFunctionExpression = false;
}
if (bIsValidFunctionExpression && MaterialExpression && IsAllowedExpressionType(MaterialExpression->GetClass(), MaterialGraph->MaterialFunction != NULL))
{
return true;
}
}
}
return false;
}
FText UMaterialGraphNode::GetNodeTitle(ENodeTitleType::Type TitleType) const
{
TArray<FString> Captions;
MaterialExpression->GetCaption(Captions);
if (TitleType == ENodeTitleType::EditableTitle)
{
return FText::FromString(GetParameterName());
}
else if (TitleType == ENodeTitleType::ListView || TitleType == ENodeTitleType::MenuTitle)
{
return FText::FromString(MaterialExpression->GetClass()->GetDescription());
}
else
{
// More useful to display multi line parameter captions in reverse order
// TODO: May have to choose order based on expression type if others need correct order
int32 CaptionIndex = Captions.Num() -1;
FTextBuilder NodeTitle;
NodeTitle.AppendLine(Captions[CaptionIndex]);
for (; CaptionIndex > 0; )
{
CaptionIndex--;
NodeTitle.AppendLine(Captions[CaptionIndex]);
}
if ( MaterialExpression->bShaderInputData && (MaterialExpression->bHidePreviewWindow || MaterialExpression->bCollapsed))
{
NodeTitle.AppendLine(LOCTEXT("InputData", "Input Data"));
}
if (bIsPreviewExpression)
{
NodeTitle.AppendLine();
NodeTitle.AppendLine(LOCTEXT("PreviewExpression", "Previewing"));
}
return NodeTitle.ToText();
}
}
FLinearColor UMaterialGraphNode::GetNodeTitleColor() const
{
UMaterial* Material = CastChecked<UMaterialGraph>(GetGraph())->Material;
if (bIsPreviewExpression)
{
// If we are currently previewing a node, its border should be the preview color.
return FColor( 70, 100, 200 );
}
const UGraphEditorSettings* Settings = GetDefault<UGraphEditorSettings>();
if (UsesBoolColour(MaterialExpression))
{
return Settings->BooleanPinTypeColor;
}
else if (UsesFloatColour(MaterialExpression))
{
return Settings->FloatPinTypeColor;
}
else if (UsesVectorColour(MaterialExpression))
{
return Settings->VectorPinTypeColor;
}
else if (UsesObjectColour(MaterialExpression))
{
return Settings->ObjectPinTypeColor;
}
else if (UsesEventColour(MaterialExpression))
{
return Settings->EventNodeTitleColor;
}
else if (MaterialExpression->IsA(UMaterialExpressionMaterialFunctionCall::StaticClass()))
{
// Previously FColor(0, 116, 255);
return Settings->FunctionCallNodeTitleColor;
}
else if (MaterialExpression->IsA(UMaterialExpressionFunctionOutput::StaticClass()))
{
// Previously FColor(255, 155, 0);
return Settings->ResultNodeTitleColor;
}
else if (UMaterial::IsParameter(MaterialExpression))
{
if (Material->HasDuplicateParameters(MaterialExpression))
{
return FColor( 0, 255, 255 );
}
else
{
return FColor( 0, 128, 128 );
}
}
else if (UMaterial::IsDynamicParameter(MaterialExpression))
{
if (Material->HasDuplicateDynamicParameters(MaterialExpression))
{
return FColor( 0, 255, 255 );
}
else
{
return FColor( 0, 128, 128 );
}
}
// Assume that most material expressions act like pure functions and don't affect anything else
return Settings->PureFunctionCallNodeTitleColor;
}
FText UMaterialGraphNode::GetTooltipText() const
{
if (MaterialExpression)
{
TArray<FString> ToolTips;
MaterialExpression->GetExpressionToolTip(ToolTips);
if (ToolTips.Num() > 0)
{
FString ToolTip = ToolTips[0];
for (int32 Index = 1; Index < ToolTips.Num(); ++Index)
{
ToolTip += TEXT("\n");
ToolTip += ToolTips[Index];
}
return FText::FromString(ToolTip);
}
}
return FText::GetEmpty();
}
void UMaterialGraphNode::PrepareForCopying()
{
if (MaterialExpression)
{
// Temporarily take ownership of the MaterialExpression, so that it is not deleted when cutting
MaterialExpression->Rename(NULL, this, REN_DontCreateRedirectors);
}
}
void UMaterialGraphNode::GetContextMenuActions(const FGraphNodeContextMenuBuilder& Context) const
{
UMaterialGraph* MaterialGraph = CastChecked<UMaterialGraph>(GetGraph());
if (Context.Node)
{
if (MaterialExpression)
{
if (MaterialExpression->IsA(UMaterialExpressionTextureBase::StaticClass()))
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().UseCurrentTexture);
// Add a 'Convert To Texture' option for convertible types
Context.MenuBuilder->BeginSection("MaterialEditorMenu0");
{
if ( MaterialExpression->IsA(UMaterialExpressionTextureSample::StaticClass()))
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().ConvertToTextureObjects);
}
else if ( MaterialExpression->IsA(UMaterialExpressionTextureObject::StaticClass()))
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().ConvertToTextureSamples);
}
}
Context.MenuBuilder->EndSection();
}
// Add a 'Convert To Parameter' option for convertible types
if (MaterialExpression->IsA(UMaterialExpressionConstant::StaticClass())
|| MaterialExpression->IsA(UMaterialExpressionConstant2Vector::StaticClass())
|| MaterialExpression->IsA(UMaterialExpressionConstant3Vector::StaticClass())
|| MaterialExpression->IsA(UMaterialExpressionConstant4Vector::StaticClass())
|| MaterialExpression->IsA(UMaterialExpressionTextureSample::StaticClass())
|| MaterialExpression->IsA(UMaterialExpressionComponentMask::StaticClass()))
{
Context.MenuBuilder->BeginSection("MaterialEditorMenu1");
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().ConvertObjects);
}
Context.MenuBuilder->EndSection();
}
// Add a 'Convert To Constant' option for convertible types
if (MaterialExpression->IsA(UMaterialExpressionScalarParameter::StaticClass())
|| MaterialExpression->IsA(UMaterialExpressionVectorParameter::StaticClass()))
{
Context.MenuBuilder->BeginSection("MaterialEditorMenu1");
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().ConvertToConstant);
}
Context.MenuBuilder->EndSection();
}
Context.MenuBuilder->BeginSection("MaterialEditorMenu2");
{
// Don't show preview option for bools
if (!MaterialExpression->IsA(UMaterialExpressionStaticBool::StaticClass())
&& !MaterialExpression->IsA(UMaterialExpressionStaticBoolParameter::StaticClass()))
{
// Add a preview node option if only one node is selected
if (bIsPreviewExpression)
{
// If we are already previewing the selected node, the menu option should tell the user that this will stop previewing
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().StopPreviewNode);
}
else
{
// The menu option should tell the user this node will be previewed.
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().StartPreviewNode);
}
}
if (MaterialExpression->bRealtimePreview)
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().DisableRealtimePreviewNode);
}
else
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().EnableRealtimePreviewNode);
}
}
Context.MenuBuilder->EndSection();
}
// Break all links
Context.MenuBuilder->AddMenuEntry(FGraphEditorCommands::Get().BreakNodeLinks);
// Separate the above frequently used options from the below less frequently used common options
Context.MenuBuilder->BeginSection("MaterialEditorMenu3");
{
Context.MenuBuilder->AddMenuEntry( FGenericCommands::Get().Delete );
Context.MenuBuilder->AddMenuEntry( FGenericCommands::Get().Cut );
Context.MenuBuilder->AddMenuEntry( FGenericCommands::Get().Copy );
Context.MenuBuilder->AddMenuEntry( FGenericCommands::Get().Duplicate );
// Select upstream and downstream nodes
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().SelectDownstreamNodes);
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().SelectUpstreamNodes);
}
Context.MenuBuilder->EndSection();
Context.MenuBuilder->BeginSection("MaterialEditorMenuDocumentation");
{
Context.MenuBuilder->AddMenuEntry(FGraphEditorCommands::Get().GoToDocumentation);
}
Context.MenuBuilder->EndSection();
// Handle the favorites options
if (MaterialExpression)
{
Context.MenuBuilder->BeginSection("MaterialEditorMenuFavorites");
{
if (FMaterialEditorUtilities::IsMaterialExpressionInFavorites(MaterialExpression))
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().RemoveFromFavorites);
}
else
{
Context.MenuBuilder->AddMenuEntry(FMaterialEditorCommands::Get().AddToFavorites);
}
}
Context.MenuBuilder->EndSection();
}
}
}
void UMaterialGraphNode::CreateInputPins()
{
const TArray<FExpressionInput*> ExpressionInputs = MaterialExpression->GetInputs();
for (int32 Index = 0; Index < ExpressionInputs.Num() ; ++Index)
{
FExpressionInput* Input = ExpressionInputs[Index];
FString InputName = MaterialExpression->GetInputName(Index);
// Shorten long expression input names.
if ( !FCString::Stricmp( *InputName, TEXT("Coordinates") ) )
{
InputName = TEXT("UVs");
}
else if ( !FCString::Stricmp( *InputName, TEXT("TextureObject") ) )
{
InputName = TEXT("Tex");
}
else if ( !FCString::Stricmp( *InputName, TEXT("Input") ) )
{
InputName = TEXT("");
}
else if ( !FCString::Stricmp( *InputName, TEXT("Exponent") ) )
{
InputName = TEXT("Exp");
}
else if ( !FCString::Stricmp( *InputName, TEXT("AGreaterThanB") ) )
{
InputName = TEXT("A>=B");
}
else if ( !FCString::Stricmp( *InputName, TEXT("AEqualsB") ) )
{
InputName = TEXT("A==B");
}
else if ( !FCString::Stricmp( *InputName, TEXT("ALessThanB") ) )
{
InputName = TEXT("A<B");
}
else if ( !FCString::Stricmp( *InputName, TEXT("MipLevel") ) )
{
InputName = TEXT("Level");
}
else if ( !FCString::Stricmp( *InputName, TEXT("MipBias") ) )
{
InputName = TEXT("Bias");
}
const UMaterialGraphSchema* Schema = CastChecked<UMaterialGraphSchema>(GetSchema());
FString PinCategory = MaterialExpression->IsInputConnectionRequired(Index) ? Schema->PC_Required : Schema->PC_Optional;
FString PinSubCategory = TEXT("");
UEdGraphPin* NewPin = CreatePin(EGPD_Input, PinCategory, PinSubCategory, NULL, /*bIsArray=*/ false, /*bIsReference=*/ false, InputName);
if (NewPin->PinName.IsEmpty())
{
// Makes sure pin has a name for lookup purposes but user will never see it
NewPin->PinName = CreateUniquePinName(TEXT("Input"));
NewPin->PinFriendlyName = FText::FromString(TEXT(" "));
}
}
}
void UMaterialGraphNode::CreateOutputPins()
{
TArray<FExpressionOutput>& Outputs = MaterialExpression->GetOutputs();
for( int32 Index = 0 ; Index < Outputs.Num() ; ++Index )
{
const FExpressionOutput& ExpressionOutput = Outputs[Index];
FString PinCategory = TEXT("");
FString PinSubCategory = TEXT("");
FString OutputName = TEXT("");
const UMaterialGraphSchema* Schema = CastChecked<UMaterialGraphSchema>(GetSchema());
if( ExpressionOutput.Mask )
{
PinCategory = Schema->PC_Mask;
if ( ExpressionOutput.MaskR && !ExpressionOutput.MaskG && !ExpressionOutput.MaskB && !ExpressionOutput.MaskA)
{
PinSubCategory = Schema->PSC_Red;
}
else if (!ExpressionOutput.MaskR && ExpressionOutput.MaskG && !ExpressionOutput.MaskB && !ExpressionOutput.MaskA)
{
PinSubCategory = Schema->PSC_Green;
}
else if (!ExpressionOutput.MaskR && !ExpressionOutput.MaskG && ExpressionOutput.MaskB && !ExpressionOutput.MaskA)
{
PinSubCategory = Schema->PSC_Blue;
}
else if (!ExpressionOutput.MaskR && !ExpressionOutput.MaskG && !ExpressionOutput.MaskB && ExpressionOutput.MaskA)
{
PinSubCategory = Schema->PSC_Alpha;
}
}
if (MaterialExpression->bShowOutputNameOnPin)
{
OutputName = ExpressionOutput.OutputName;
}
UEdGraphPin* NewPin = CreatePin(EGPD_Output, PinCategory, PinSubCategory, NULL, /*bIsArray=*/ false, /*bIsReference=*/ false, OutputName);
if (NewPin->PinName.IsEmpty())
{
// Makes sure pin has a name for lookup purposes but user will never see it
NewPin->PinName = CreateUniquePinName(TEXT("Output"));
NewPin->PinFriendlyName = FText::FromString(TEXT(" "));
}
}
}
int32 UMaterialGraphNode::GetOutputIndex(const UEdGraphPin* OutputPin)
{
TArray<UEdGraphPin*> OutputPins;
GetOutputPins(OutputPins);
for (int32 Index = 0; Index < OutputPins.Num(); ++Index)
{
if (OutputPin == OutputPins[Index])
{
return Index;
}
}
return -1;
}
uint32 UMaterialGraphNode::GetOutputType(const UEdGraphPin* OutputPin)
{
return MaterialExpression->GetOutputType(GetOutputIndex(OutputPin));
}
int32 UMaterialGraphNode::GetInputIndex(const UEdGraphPin* InputPin) const
{
TArray<UEdGraphPin*> InputPins;
GetInputPins(InputPins);
for (int32 Index = 0; Index < InputPins.Num(); ++Index)
{
if (InputPin == InputPins[Index])
{
return Index;
}
}
return -1;
}
uint32 UMaterialGraphNode::GetInputType(const UEdGraphPin* InputPin) const
{
return MaterialExpression->GetInputType(GetInputIndex(InputPin));
}
void UMaterialGraphNode::ResetMaterialExpressionOwner()
{
if (MaterialExpression)
{
// Ensures MaterialExpression is owned by the Material or Function
UMaterialGraph* MaterialGraph = CastChecked<UMaterialGraph>(GetGraph());
UObject* ExpressionOuter = MaterialGraph->Material;
if (MaterialGraph->MaterialFunction)
{
ExpressionOuter = MaterialGraph->MaterialFunction;
}
MaterialExpression->Rename(NULL, ExpressionOuter, REN_DontCreateRedirectors);
// Set up the back pointer for newly created material nodes
MaterialExpression->GraphNode = this;
}
}
void UMaterialGraphNode::PostPlacedNewNode()
{
if (MaterialExpression)
{
NodeComment = MaterialExpression->Desc;
bCommentBubbleVisible = MaterialExpression->bCommentBubbleVisible;
NodePosX = MaterialExpression->MaterialExpressionEditorX;
NodePosY = MaterialExpression->MaterialExpressionEditorY;
bCanRenameNode = MaterialExpression->CanRenameNode();
}
}
void UMaterialGraphNode::NodeConnectionListChanged()
{
Super::NodeConnectionListChanged();
const UEdGraphSchema* Schema = GetSchema();
if (Schema != nullptr)
{
Schema->ForceVisualizationCacheClear();
}
}
void UMaterialGraphNode::OnRenameNode(const FString& NewName)
{
MaterialExpression->Modify();
SetParameterName(NewName);
MaterialExpression->MarkPackageDirty();
MaterialDirtyDelegate.ExecuteIfBound();
}
void UMaterialGraphNode::OnUpdateCommentText( const FString& NewComment )
{
const FScopedTransaction Transaction( LOCTEXT( "CommentCommitted", "Comment Changed" ) );
// Update the Node comment
Modify();
NodeComment = NewComment;
// Update the Material Expresssion desc to match the comment
if( MaterialExpression )
{
MaterialExpression->Modify();
MaterialExpression->Desc = NewComment;
MaterialDirtyDelegate.ExecuteIfBound();
}
}
void UMaterialGraphNode::OnCommentBubbleToggled( bool bInCommentBubbleVisible )
{
if ( MaterialExpression )
{
MaterialExpression->Modify();
MaterialExpression->bCommentBubbleVisible = bInCommentBubbleVisible;
MaterialDirtyDelegate.ExecuteIfBound();
}
}
void UMaterialGraphNode::GetPinHoverText(const UEdGraphPin& Pin, FString& HoverTextOut) const
{
Super::GetPinHoverText(Pin, HoverTextOut);
if (HoverTextOut.IsEmpty())
{
TArray<FString> ToolTips;
int32 DirIndex = -1;
int32 PinIndex = INDEX_NONE;
for (int32 Index = 0; Index < Pins.Num(); ++Index)
{
if (Pin.Direction == Pins[Index]->Direction)
{
++DirIndex;
if (Pins[Index] == &Pin)
{
PinIndex = DirIndex;
break;
}
}
}
if (Pin.Direction == EEdGraphPinDirection::EGPD_Input)
{
MaterialExpression->GetConnectorToolTip(PinIndex, INDEX_NONE, ToolTips);
}
else
{
MaterialExpression->GetConnectorToolTip(INDEX_NONE, PinIndex, ToolTips);
}
if (ToolTips.Num() > 0)
{
HoverTextOut = ToolTips[0];
for (int32 Index = 1; Index < ToolTips.Num(); ++Index)
{
HoverTextOut += TEXT("\n");
HoverTextOut += ToolTips[Index];
}
}
}
}
FString UMaterialGraphNode::GetParameterName() const
{
return MaterialExpression->GetEditableName();
}
void UMaterialGraphNode::SetParameterName(const FString& NewName)
{
MaterialExpression->SetEditableName(NewName);
//@TODO: Push into the SetEditableName interface
CastChecked<UMaterialGraph>(GetGraph())->Material->UpdateExpressionParameterName(MaterialExpression);
}
bool UMaterialGraphNode::UsesBoolColour(UMaterialExpression* Expression)
{
if (Expression->IsA<UMaterialExpressionStaticBool>())
{
return true;
}
// Explicitly check for bool param as switch params inherit from it
else if (Expression->GetClass() == UMaterialExpressionStaticBoolParameter::StaticClass())
{
return true;
}
return false;
}
bool UMaterialGraphNode::UsesFloatColour(UMaterialExpression* Expression)
{
if (Expression->IsA<UMaterialExpressionConstant>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionScalarParameter>())
{
return true;
}
return false;
}
bool UMaterialGraphNode::UsesVectorColour(UMaterialExpression* Expression)
{
if (Expression->IsA<UMaterialExpressionConstant2Vector>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionConstant3Vector>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionConstant4Vector>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionVectorParameter>())
{
return true;
}
return false;
}
bool UMaterialGraphNode::UsesObjectColour(UMaterialExpression* Expression)
{
if (Expression->IsA<UMaterialExpressionTextureBase>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionFontSample>())
{
return true;
}
return false;
}
bool UMaterialGraphNode::UsesEventColour(UMaterialExpression* Expression)
{
if (Expression->bShaderInputData && !Expression->IsA<UMaterialExpressionStaticBool>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionFunctionInput>())
{
return true;
}
else if (Expression->IsA<UMaterialExpressionTextureCoordinate>())
{
return true;
}
return false;
}
FString UMaterialGraphNode::GetDocumentationExcerptName() const
{
// Default the node to searching for an excerpt named for the C++ node class name, including the U prefix.
// This is done so that the excerpt name in the doc file can be found by find-in-files when searching for the full class name.
UClass* MyClass = (MaterialExpression != NULL) ? MaterialExpression->GetClass() : this->GetClass();
return FString::Printf(TEXT("%s%s"), MyClass->GetPrefixCPP(), *MyClass->GetName());
}
#undef LOCTEXT_NAMESPACE
|
/*
-------------------------------------------------------------------------------
Copyright (c) Charles Carley.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-------------------------------------------------------------------------------
*/
#include "skJsonScanner.h"
#include <memory.h>
#include <cstdio>
#include "Utils/skFileStream.h"
#include "Utils/skMemoryUtils.h"
skJsonScanner::skJsonScanner() :
m_data(nullptr),
m_len(SK_NPOS),
m_pos(SK_NPOS)
{
}
skJsonScanner::~skJsonScanner()
{
delete[] m_data;
m_data = nullptr;
}
void skJsonScanner::open(const skString& path)
{
const skFileStream fs = skFileStream(path.c_str(), skStream::READ);
if (fs.isOpen())
{
const SKsize len = fs.size();
if (len > 0 && len < SK_NPOS16)
{
m_len = len;
m_pos = 0;
delete[] m_data;
m_data = nullptr;
m_data = new SKint8[m_len + 1];
fs.read(m_data, m_len);
m_data[m_len] = 0;
}
}
}
void skJsonScanner::open(const char* mem, const SKsize len)
{
if (mem && len > 0 && len < SK_NPOS16)
{
m_len = len;
m_pos = 0;
delete[] m_data;
m_data = nullptr;
m_data = new SKint8[m_len + 1];
skMemcpy(m_data, mem, len);
m_data[m_len] = 0;
}
}
void skJsonScanner::scan(skJsonToken& tok)
{
tok.setType(skJsonTokenType::JT_NULL);
tok.clear();
if (!m_data)
return;
while (m_pos < m_len)
{
char ch = m_data[m_pos];
++m_pos;
switch (ch)
{
case '/':
{
ch = m_data[m_pos];
if (ch == '/')
{
while (ch != '\n' && ch != '\r' && ch != 0)
{
++m_pos;
ch = m_data[m_pos];
}
if (ch == 0)
{
m_pos = SK_NPOS;
return;
}
}
else
{
m_pos = SK_NPOS;
return;
}
break;
}
case '[':
tok.setType(skJsonTokenType::JT_L_BRACE);
return;
case ']':
tok.setType(skJsonTokenType::JT_R_BRACE);
return;
case ',':
tok.setType(skJsonTokenType::JT_COMMA);
return;
case ':':
tok.setType(skJsonTokenType::JT_COLON);
return;
case '{':
tok.setType(skJsonTokenType::JT_L_BRACKET);
return;
case '}':
tok.setType(skJsonTokenType::JT_R_BRACKET);
return;
case '\"':
{
while (m_data[m_pos] != '\"' && m_data[m_pos] != 0)
tok.push(m_data[m_pos++]);
if (m_data[m_pos] == '\"')
{
++m_pos;
tok.setType(skJsonTokenType::JT_STRING);
return;
}
m_pos = SK_NPOS;
return;
}
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
bool hasDot = false;
tok.push(ch);
for (; m_pos < m_len; ++m_pos)
{
ch = m_data[m_pos];
if (ch == '.')
hasDot = true;
if (isDigitSet(ch) && ch != 0)
tok.push(ch);
else
break;
}
if (ch != 0)
{
tok.setType(hasDot ? skJsonTokenType::JT_NUMBER
: skJsonTokenType::JT_INTEGER);
return;
}
m_pos = SK_NPOS;
return;
}
case 't':
case 'f':
case 'n':
{
if (skChar::equalsn((const char*)&m_data[m_pos - 1], "true", 4) == 0)
{
m_pos += 3;
tok.setType(skJsonTokenType::JT_BOOL);
tok.push("true");
return;
}
if (skChar::equalsn((const char*)&m_data[m_pos - 1], "false", 5) == 0)
{
m_pos += 4;
tok.setType(skJsonTokenType::JT_BOOL);
tok.push("false");
return;
}
if (skChar::equalsn((const char*)&m_data[m_pos - 1], "null", 4) == 0)
{
m_pos += 3;
tok.setType(skJsonTokenType::JT_NULL);
tok.push("null");
return;
}
m_pos = SK_NPOS;
return;
}
case ' ':
case '\t':
case '\n':
case '\r':
break;
default:
m_pos = SK_NPOS;
return;
}
}
}
bool skJsonScanner::isDigitSet(const char ch)
{
return ch >= '0' && ch <= '9' || ch == '-' || ch == '.';
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "libzerocoin/Params.h"
#include "chainparams.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace std;
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
/**
* Main network
*/
//! Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress>& vSeedsOut, const SeedSpec6* data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7 * 24 * 60 * 60;
for (unsigned int i = 0; i < count; i++) {
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static Checkpoints::MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(0, uint256("00000f0cc92e464a99fa51cee574c22c084761fa7d01b3f0b431c0dc55679447"));
static const Checkpoints::CCheckpointData data = {
&mapCheckpoints,
1590390920, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
0 // * estimated number of transactions per day after checkpoint
};
static Checkpoints::MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
(0, uint256("0x001"));
static const Checkpoints::CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1590390920,
0,
0};
static Checkpoints::MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of(0, uint256("0x001"));
static const Checkpoints::CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
1590390920,
0,
0};
libzerocoin::ZerocoinParams* CChainParams::Zerocoin_Params(bool useModulusV1) const
{
assert(this);
static CBigNum bnHexModulus = 0;
if (!bnHexModulus)
bnHexModulus.SetHex(zerocoinModulus);
static libzerocoin::ZerocoinParams ZCParamsHex = libzerocoin::ZerocoinParams(bnHexModulus);
static CBigNum bnDecModulus = 0;
if (!bnDecModulus)
bnDecModulus.SetDec(zerocoinModulus);
static libzerocoin::ZerocoinParams ZCParamsDec = libzerocoin::ZerocoinParams(bnDecModulus);
if (useModulusV1)
return &ZCParamsHex;
return &ZCParamsDec;
}
class CMainParams : public CChainParams
{
public:
CMainParams()
{
networkID = CBaseChainParams::MAIN;
strNetworkID = "main";
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0x15;
pchMessageStart[1] = 0x1b;
pchMessageStart[2] = 0xfb;
pchMessageStart[3] = 0xc5;
vAlertPubKey = ParseHex("0428971fb9ec8fdd097acc0633a4653121d30622735c0abc7d32979ac3398eebeeefe697633df6020117f808d99f45548441a6d902e368405eac15e5b7386e262d");
nDefaultPort = 19532;
bnProofOfWorkLimit = ~uint256(0) >> 20; // Akikcoin starting difficulty is 1 / 2^12
nSubsidyHalvingInterval = 210000;
nMaxReorganizationDepth = 100;
nEnforceBlockUpgradeMajority = 4050; // 75%
nRejectBlockOutdatedMajority = 5130; // 95%
nToCheckBlockUpgradeMajority = 5400; // Approximate expected amount of blocks in 7 days (720*7.5)
nMinerThreads = 0;
nTargetTimespan = 2 * 60;
nTargetSpacing = 2 * 60;
nMaturity = 50;
nMasternodeCountDrift = 20;
nMaxMoneyOut = 70000000 * COIN;
/** Height or Time Based Activations **/
nLastPOWBlock = 1000;
nModifierUpdateBlock = 0;
nZerocoinStartHeight = 0;
nZerocoinStartTime = 1590390920;
nBlockEnforceSerialRange = 1; //Enforce serial range starting this block
nBlockRecalculateAccumulators = 999999999; //Trigger a recalculation of accumulators
nBlockFirstFraudulent = 999999999; //First block that bad serials emerged
nBlockLastGoodCheckpoint = 999999999; //Last valid accumulator checkpoint
nBlockEnforceInvalidUTXO = 999999999; //Start enforcing the invalid UTXO's
nInvalidAmountFiltered = 0; //Amount of invalid coins filtered through exchanges, that should be considered valid
nBlockZerocoinV2 = 999999999;
nBlockDoubleAccumulated = 999999999;
nEnforceNewSporkKey = 1590390920;
nRejectOldSporkKey = 1527811200;
// Public coin spend enforcement
nPublicZCSpends = 1;
// Fake Serial Attack
nFakeSerialBlockheightEnd = 0;
nSupplyBeforeFakeSerial = 0; // zerocoin supply at block nFakeSerialBlockheightEnd
/**
* Build the genesis block. Note that the output of the genesis coinbase cannot
* be spent as it did not originally exist in the database.
*
* CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
* CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04fff00000f0cc92e464a99fa51cee574c22c084761fa7d01b3f0b431c0dc55679447d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
* CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
* vMerkleTree: e0028e
*/
const char* pszTimestamp = "Covid19 forcing businesses to adapt and rethink how they make money";
CMutableTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 200 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("0455c893b9667543c3f62ed0a05f63e256e6066f302ab8b08f0b0de0f86820b919023964caac879fab915e1e07463baeeaf68445d17d650c4f3e4cd213a60a1e0b") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1590390920;
genesis.nBits = 0x1e0ffff0;
genesis.nNonce = 20820661;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000f0cc92e464a99fa51cee574c22c084761fa7d01b3f0b431c0dc55679447"));
assert(genesis.hashMerkleRoot == uint256("0xc9b96afc18c7e772b2117f19c853f796e2f5729077d97e8de18660fdaf32fdcc"));
vSeeds.push_back(CDNSSeedData("akikcoin.com", "node1.akikcoin.com"));
vSeeds.push_back(CDNSSeedData("n2.akikcoin.com", "node2.akikcoin.com"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 23);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 24);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 151);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x02)(0x2D)(0x25)(0x33).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x02)(0x21)(0x31)(0x2B).convert_to_container<std::vector<unsigned char> >();
// BIP44 coin type is from https://github.com/satoshilabs/slips/blob/master/slip-0044.md
base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x77).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
fMiningRequiresPeers = true;
fAllowMinDifficultyBlocks = false;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
fSkipProofOfWorkCheck = false;
fTestnetToBeDeprecatedFieldRPC = false;
fHeadersFirstSyncingActive = false;
nPoolMaxTransactions = 3;
nBudgetCycleBlocks = 21600;
strSporkKey = "04bad9c9568ed13a637dca6a897a4a51d774c9e3fa27c791742e996653c0fe499130a0bc1defbef7c18c058c263f9c65a5ddbeaf61d7dff0dd03063af252e4e23b";
strSporkKeyOld = "04B433E6598390C992F4F022F20D3B4CBBE691652EE7C48243B81701CBDB7CC7D7BF0EE09E154E6FCBF2043D65AF4E9E97B89B5DBAF830D83B9B7F469A6C45A717";
strObfuscationPoolDummyAddress = "ALdPzxpjNFGeU2g4fexGDYYnNvwQrbNxZq";
nStartMasternodePayments = 1590390920;
/** Zerocoin */
zerocoinModulus = "25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784"
"4069182906412495150821892985591491761845028084891200728449926873928072877767359714183472702618963750149718246911"
"6507761337985909570009733045974880842840179742910064245869181719511874612151517265463228221686998754918242243363"
"7259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133"
"8441436038339044149526344321901146575444541784240209246165157233507787077498171257724679629263863563732899121548"
"31438167899885040445364023527381951378636564391212010397122822120720357";
nMaxZerocoinSpendsPerTransaction = 7; // Assume about 20kb each
nMaxZerocoinPublicSpendsPerTransaction = 637; // Assume about 220 bytes each input
nMinZerocoinMintFee = 1 * CENT; //high fee required for zerocoin mints
nMintRequiredConfirmations = 20; //the maximum amount of confirmations until accumulated in 19
nRequiredAccumulation = 1;
nDefaultSecurityLevel = 100; //full security level for accumulators
nZerocoinHeaderVersion = 4; //Block headers must be this version once zerocoin is active
nZerocoinRequiredStakeDepth = 200; //The required confirmations for a zakc to be stakable
nBudget_Fee_Confirmations = 6; // Number of confirmations for the finalization fee
nProposalEstablishmentTime = 60 * 60 * 24; // Proposals must be at least a day old to make it into a budget
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return data;
}
};
static CMainParams mainParams;
/**
* Testnet (v3)
*/
class CTestNetParams : public CMainParams
{
public:
CTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
strNetworkID = "test";
pchMessageStart[0] = 0x40;
pchMessageStart[1] = 0xdd;
pchMessageStart[2] = 0x22;
pchMessageStart[3] = 0x41;
vAlertPubKey = ParseHex("04515b06cdd770981945416af7d4f9da046297c68993ed87fd0bc7218d27e13e341304e7c6a6cb41d68ffc8b7363526f5c50dfbce8daddb652efa68e00d6e969c6");
nDefaultPort = 29532;
nEnforceBlockUpgradeMajority = 2430; // 75%
nRejectBlockOutdatedMajority = 3078; // 95%
nToCheckBlockUpgradeMajority = 3240; // 4 days
nMinerThreads = 0;
nTargetTimespan = 2 * 60;
nTargetSpacing = 2 * 60;
nLastPOWBlock = 200;
nMaturity = 15;
nMasternodeCountDrift = 4;
nModifierUpdateBlock = 0;
nMaxMoneyOut = 43199500 * COIN;
nZerocoinStartHeight = 0;
nZerocoinStartTime = 1590390920;
nBlockEnforceSerialRange = 1; //Enforce serial range starting this block
nBlockRecalculateAccumulators = 999999999; //Trigger a recalculation of accumulators
nBlockFirstFraudulent = 999999999; //First block that bad serials emerged
nBlockLastGoodCheckpoint = 999999999; //Last valid accumulator checkpoint
nBlockEnforceInvalidUTXO = 999999999; //Start enforcing the invalid UTXO's
nInvalidAmountFiltered = 0; //Amount of invalid coins filtered through exchanges, that should be considered valid
nBlockZerocoinV2 = 999999999; //!> The block that zerocoin v2 becomes active
nEnforceNewSporkKey = 1590390920;
nRejectOldSporkKey = 1522454400;
// Public coin spend enforcement
nPublicZCSpends = 1;
// Fake Serial Attack
nFakeSerialBlockheightEnd = -1;
nSupplyBeforeFakeSerial = 0;
//! Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1590390920;
genesis.nNonce = 20820661;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000f0cc92e464a99fa51cee574c22c084761fa7d01b3f0b431c0dc55679447"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 45);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 46);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 173);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container<std::vector<unsigned char> >();
// Testnet akikcoin BIP44 coin type is '1' (All coin's testnet default)
base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
fMiningRequiresPeers = true;
fAllowMinDifficultyBlocks = true;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
fTestnetToBeDeprecatedFieldRPC = true;
nPoolMaxTransactions = 2;
nBudgetCycleBlocks = 144; //!< Ten cycles per day on testnet
strSporkKey = "04d02d4971e47837e187ee7fbd2976a8658b9bc6f73cd2437c9d9b872ef42876dc1f33fa43ea14e1511cee8beafee88210dea43a709be28febd06f07e875974c69";
strSporkKeyOld = "04348C2F50F90267E64FACC65BFDC9D0EB147D090872FB97ABAE92E9A36E6CA60983E28E741F8E7277B11A7479B626AC115BA31463AC48178A5075C5A9319D4A38";
strObfuscationPoolDummyAddress = "KBRL52HNWWSkBLDHgxp1RiPRewWTofxiZe";
nStartMasternodePayments = 1590390920;
nBudget_Fee_Confirmations = 3; // Number of confirmations for the finalization fee. We have to make this very short
// here because we only have a 8 block finalization window on testnet
nProposalEstablishmentTime = 60 * 5; // Proposals must be at least 5 mns old to make it into a test budget
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataTestnet;
}
};
static CTestNetParams testNetParams;
/**
* Regression test
*/
class CRegTestParams : public CTestNetParams
{
public:
CRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strNetworkID = "regtest";
pchMessageStart[0] = 0x37;
pchMessageStart[1] = 0x7a;
pchMessageStart[2] = 0xa6;
pchMessageStart[3] = 0x51;
nDefaultPort = 51476;
nSubsidyHalvingInterval = 150;
nEnforceBlockUpgradeMajority = 750;
nRejectBlockOutdatedMajority = 950;
nToCheckBlockUpgradeMajority = 1000;
nMinerThreads = 1;
nTargetTimespan = 24 * 60 * 60; // Akikcoin: 1 day
nTargetSpacing = 1 * 60; // Akikcoin: 1 minutes
bnProofOfWorkLimit = ~uint256(0) >> 1;
nLastPOWBlock = 250;
nMaturity = 50;
nMasternodeCountDrift = 4;
nModifierUpdateBlock = 0; //approx Mon, 17 Apr 2017 04:00:00 GMT
nMaxMoneyOut = 43199500 * COIN;
nZerocoinStartHeight = 300;
nBlockZerocoinV2 = 300;
nZerocoinStartTime = 1590390920;
nBlockEnforceSerialRange = 1; //Enforce serial range starting this block
nBlockRecalculateAccumulators = 999999999; //Trigger a recalculation of accumulators
nBlockFirstFraudulent = 999999999; //First block that bad serials emerged
nBlockLastGoodCheckpoint = 999999999; //Last valid accumulator checkpoint
// Public coin spend enforcement
nPublicZCSpends = 350;
// Fake Serial Attack
nFakeSerialBlockheightEnd = -1;
//! Modify the regtest genesis block so the timestamp is valid for a later start.
genesis.nTime = 1590390920;
genesis.nNonce = 20820661;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x00000f0cc92e464a99fa51cee574c22c084761fa7d01b3f0b431c0dc55679447"));
//assert(hashGenesisBlock == uint256("0x47a2609ce886e33d25133fbce5c9d6b7dd705df2d8e76a94576254e733ef7b75"));
vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds.
vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds.
fMiningRequiresPeers = false;
fAllowMinDifficultyBlocks = true;
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
fSkipProofOfWorkCheck = true;
fTestnetToBeDeprecatedFieldRPC = false;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataRegtest;
}
};
static CRegTestParams regTestParams;
/**
* Unit test
*/
class CUnitTestParams : public CMainParams, public CModifiableParams
{
public:
CUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strNetworkID = "unittest";
nDefaultPort = 51478;
vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds.
vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds.
fMiningRequiresPeers = false;
fDefaultConsistencyChecks = true;
fAllowMinDifficultyBlocks = false;
fMineBlocksOnDemand = true;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
// UnitTest share the same checkpoints as MAIN
return data;
}
//! Published setters to allow changing values in unit test cases
virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval = anSubsidyHalvingInterval; }
virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority = anEnforceBlockUpgradeMajority; }
virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority = anRejectBlockOutdatedMajority; }
virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority = anToCheckBlockUpgradeMajority; }
virtual void setDefaultConsistencyChecks(bool afDefaultConsistencyChecks) { fDefaultConsistencyChecks = afDefaultConsistencyChecks; }
virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks = afAllowMinDifficultyBlocks; }
virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; }
};
static CUnitTestParams unitTestParams;
static CChainParams* pCurrentParams = 0;
CModifiableParams* ModifiableParams()
{
assert(pCurrentParams);
assert(pCurrentParams == &unitTestParams);
return (CModifiableParams*)&unitTestParams;
}
const CChainParams& Params()
{
assert(pCurrentParams);
return *pCurrentParams;
}
CChainParams& Params(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
return mainParams;
case CBaseChainParams::TESTNET:
return testNetParams;
case CBaseChainParams::REGTEST:
return regTestParams;
case CBaseChainParams::UNITTEST:
return unitTestParams;
default:
assert(false && "Unimplemented network");
return mainParams;
}
}
void SelectParams(CBaseChainParams::Network network)
{
SelectBaseParams(network);
pCurrentParams = &Params(network);
}
bool SelectParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectParams(network);
return true;
}
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2010 Adrian Sai-wah Tam
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com>
*/
#define NS_LOG_APPEND_CONTEXT \
if (m_node) { std::clog << Simulator::Now ().GetSeconds () << " [node " << m_node->GetId () << "] "; }
#include "tcp-reno.h"
#include "ns3/log.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/simulator.h"
#include "ns3/abort.h"
#include "ns3/node.h"
NS_LOG_COMPONENT_DEFINE ("TcpReno");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (TcpReno);
TypeId
TcpReno::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::TcpReno")
.SetParent<TcpSocketBase> ()
.AddConstructor<TcpReno> ()
.AddTraceSource ("CongestionWindow",
"The TCP connection's congestion window",
MakeTraceSourceAccessor (&TcpReno::m_cWnd))
;
return tid;
}
TcpReno::TcpReno (void) : m_inFastRec (false)
{
NS_LOG_FUNCTION (this);
}
TcpReno::TcpReno (const TcpReno& sock)
: TcpSocketBase (sock),
m_cWnd (sock.m_cWnd),
m_ssThresh (sock.m_ssThresh),
m_initialCWnd (sock.m_initialCWnd),
m_inFastRec (false)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC ("Invoked the copy constructor");
}
TcpReno::~TcpReno (void)
{
}
/** We initialize m_cWnd from this function, after attributes initialized */
int
TcpReno::Listen (void)
{
NS_LOG_FUNCTION (this);
InitializeCwnd ();
return TcpSocketBase::Listen ();
}
/** We initialize m_cWnd from this function, after attributes initialized */
int
TcpReno::Connect (const Address & address)
{
NS_LOG_FUNCTION (this << address);
InitializeCwnd ();
return TcpSocketBase::Connect (address);
}
/** Limit the size of in-flight data by cwnd and receiver's rxwin */
uint32_t
TcpReno::Window (void)
{
NS_LOG_FUNCTION (this);
return std::min (m_rWnd.Get (), m_cWnd.Get ());
}
Ptr<TcpSocketBase>
TcpReno::Fork (void)
{
return CopyObject<TcpReno> (this);
}
/** New ACK (up to seqnum seq) received. Increase cwnd and call TcpSocketBase::NewAck() */
void
TcpReno::NewAck (const SequenceNumber32& seq)
{
NS_LOG_FUNCTION (this << seq);
NS_LOG_LOGIC ("TcpReno receieved ACK for seq " << seq <<
" cwnd " << m_cWnd <<
" ssthresh " << m_ssThresh);
// Check for exit condition of fast recovery
if (m_inFastRec)
{ // RFC2001, sec.4; RFC2581, sec.3.2
// First new ACK after fast recovery: reset cwnd
m_cWnd = m_ssThresh;
m_inFastRec = false;
NS_LOG_INFO ("Reset cwnd to " << m_cWnd);
};
// Increase of cwnd based on current phase (slow start or congestion avoidance)
if (m_cWnd < m_ssThresh)
{ // Slow start mode, add one segSize to cWnd. Default m_ssThresh is 65535. (RFC2001, sec.1)
m_cWnd += m_segmentSize;
NS_LOG_INFO ("In SlowStart, updated to cwnd " << m_cWnd << " ssthresh " << m_ssThresh);
}
else
{ // Congestion avoidance mode, increase by (segSize*segSize)/cwnd. (RFC2581, sec.3.1)
// To increase cwnd for one segSize per RTT, it should be (ackBytes*segSize)/cwnd
double adder = static_cast<double> (m_segmentSize * m_segmentSize) / m_cWnd.Get ();
adder = std::max (1.0, adder);
m_cWnd += static_cast<uint32_t> (adder);
NS_LOG_INFO ("In CongAvoid, updated to cwnd " << m_cWnd << " ssthresh " << m_ssThresh);
}
// Complete newAck processing
TcpSocketBase::NewAck (seq);
}
// Fast recovery and fast retransmit
void
TcpReno::DupAck (const TcpHeader& t, uint32_t count)
{
NS_LOG_FUNCTION (this << "t " << count);
if (count == 3 && !m_inFastRec)
{ // triple duplicate ack triggers fast retransmit (RFC2581, sec.3.2)
m_ssThresh = std::max (2 * m_segmentSize, BytesInFlight () / 2);
m_cWnd = m_ssThresh + 3 * m_segmentSize;
m_inFastRec = true;
NS_LOG_INFO ("Triple dupack. Reset cwnd to " << m_cWnd << ", ssthresh to " << m_ssThresh);
DoRetransmit ();
}
else if (m_inFastRec)
{ // In fast recovery, inc cwnd for every additional dupack (RFC2581, sec.3.2)
m_cWnd += m_segmentSize;
NS_LOG_INFO ("Increased cwnd to " << m_cWnd);
SendPendingData (m_connected);
};
}
// Retransmit timeout
void TcpReno::Retransmit (void)
{
NS_LOG_FUNCTION (this);
NS_LOG_LOGIC (this << " ReTxTimeout Expired at time " << Simulator::Now ().GetSeconds ());
m_inFastRec = false;
// If erroneous timeout in closed/timed-wait state, just return
if (m_state == CLOSED || m_state == TIME_WAIT) return;
// If all data are received, just return
if (m_txBuffer.HeadSequence () >= m_nextTxSequence) return;
// According to RFC2581 sec.3.1, upon RTO, ssthresh is set to half of flight
// size and cwnd is set to 1*MSS, then the lost packet is retransmitted and
// TCP back to slow start
m_ssThresh = std::max (2 * m_segmentSize, BytesInFlight () / 2);
m_cWnd = m_segmentSize;
m_nextTxSequence = m_txBuffer.HeadSequence (); // Restart from highest Ack
NS_LOG_INFO ("RTO. Reset cwnd to " << m_cWnd <<
", ssthresh to " << m_ssThresh << ", restart from seqnum " << m_nextTxSequence);
m_rtt->IncreaseMultiplier (); // Double the next RTO
DoRetransmit (); // Retransmit the packet
}
void
TcpReno::SetSegSize (uint32_t size)
{
NS_ABORT_MSG_UNLESS (m_state == CLOSED, "TcpReno::SetSegSize() cannot change segment size after connection started.");
m_segmentSize = size;
}
void
TcpReno::SetSSThresh (uint32_t threshold)
{
m_ssThresh = threshold;
}
uint32_t
TcpReno::GetSSThresh (void) const
{
return m_ssThresh;
}
void
TcpReno::SetInitialCwnd (uint32_t cwnd)
{
NS_ABORT_MSG_UNLESS (m_state == CLOSED, "TcpReno::SetInitialCwnd() cannot change initial cwnd after connection started.");
m_initialCWnd = cwnd;
}
uint32_t
TcpReno::GetInitialCwnd (void) const
{
return m_initialCWnd;
}
void
TcpReno::InitializeCwnd (void)
{
/*
* Initialize congestion window, default to 1 MSS (RFC2001, sec.1) and must
* not be larger than 2 MSS (RFC2581, sec.3.1). Both m_initiaCWnd and
* m_segmentSize are set by the attribute system in ns3::TcpSocket.
*/
m_cWnd = m_initialCWnd * m_segmentSize;
}
} // namespace ns3
|
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UMGEditorPrivatePCH.h"
#include "Designer/DesignTimeUtils.h"
#define LOCTEXT_NAMESPACE "UMGEditor"
bool FDesignTimeUtils::GetArrangedWidget(TSharedRef<SWidget> Widget, FArrangedWidget& ArrangedWidget)
{
TSharedPtr<SWindow> WidgetWindow = FSlateApplication::Get().FindWidgetWindow(Widget);
if ( !WidgetWindow.IsValid() )
{
return false;
}
TSharedRef<SWindow> CurrentWindowRef = WidgetWindow.ToSharedRef();
FWidgetPath WidgetPath;
if ( FSlateApplication::Get().GeneratePathToWidgetUnchecked(Widget, WidgetPath) )
{
ArrangedWidget = WidgetPath.FindArrangedWidget(Widget).Get(FArrangedWidget::NullWidget);
return true;
}
return false;
}
bool FDesignTimeUtils::GetArrangedWidgetRelativeToWindow(TSharedRef<SWidget> Widget, FArrangedWidget& ArrangedWidget)
{
TSharedPtr<SWindow> WidgetWindow = FSlateApplication::Get().FindWidgetWindow(Widget);
if ( !WidgetWindow.IsValid() )
{
return false;
}
TSharedRef<SWindow> CurrentWindowRef = WidgetWindow.ToSharedRef();
FWidgetPath WidgetPath;
if ( FSlateApplication::Get().GeneratePathToWidgetUnchecked(Widget, WidgetPath) )
{
ArrangedWidget = WidgetPath.FindArrangedWidget(Widget).Get(FArrangedWidget::NullWidget);
ArrangedWidget.Geometry.AppendTransform(FSlateLayoutTransform(Inverse(CurrentWindowRef->GetPositionInScreen())));
return true;
}
return false;
}
bool FDesignTimeUtils::GetArrangedWidgetRelativeToParent(TSharedRef<const SWidget> Widget, TSharedRef<const SWidget> Parent, FArrangedWidget& ArrangedWidget)
{
FWidgetPath WidgetPath;
if ( FSlateApplication::Get().GeneratePathToWidgetUnchecked(Widget, WidgetPath) )
{
GetArrangedWidgetRelativeToParent(WidgetPath, Widget, Parent, ArrangedWidget);
return true;
}
return false;
}
void FDesignTimeUtils::GetArrangedWidgetRelativeToParent(FWidgetPath& WidgetPath, TSharedRef<const SWidget> Widget, TSharedRef<const SWidget> Parent, FArrangedWidget& ArrangedWidget)
{
FArrangedWidget ArrangedDesigner = WidgetPath.FindArrangedWidget(Parent).Get(FArrangedWidget::NullWidget);
ArrangedWidget = WidgetPath.FindArrangedWidget(Widget).Get(FArrangedWidget::NullWidget);
// !!! WRH 2014/08/26 - This code tries to mutate an FGeometry in an unsupported way. This code should be refactored.
ArrangedWidget.Geometry.AppendTransform(FSlateLayoutTransform(Inverse(ArrangedDesigner.Geometry.AbsolutePosition)));
}
#undef LOCTEXT_NAMESPACE
|
/*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2014 by Synge Todo <wistaria@comp-phys.org>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*****************************************************************************/
#include "common.hpp"
void test(int n, double total_sz) {
std::vector<int> list1;
std::vector<std::pair<int, int> > list2;
int idim = sz(n, total_sz, list1, list2);
std::cout << n << ' ' << total_sz << ' ' << idim << std::endl;
int ihf = (n + 1) / 2;
int ihfbit = 1 << ihf;
int irght = ihfbit - 1;
int ilft = ((1 << n) - 1) ^ irght;
for (int i = 0; i < list1.size(); ++i) {
int ia = list1[i] & irght;
int ib = (list1[i] & ilft) / ihfbit;
if (i != list2[ia].first + list2[ib].second) {
std::cerr << "Incorrect table list1 and list2\n";
std::abort();
}
}
}
int main() {
test(16, 0);
test(8, 0);
test(8, 1);
}
|
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "checker/reverse_checker.h"
#include <vector>
#include <limits>
#include <string>
#include "common/op_enum.h"
namespace mindspore {
namespace dpico {
bool ReverseChecker::Check(api::CNodePtr op, int32_t output_num, mindspore::Format format) {
if (!CheckInputW(op, kInputIndex1, format, kMaxInputWOf4Dims)) {
MS_LOG(WARNING) << "input_w is not supported. " << op->fullname_with_scope();
return false;
}
auto primitive = api::GetValueNode<api::PrimitivePtr>(op->input(0));
if (primitive == nullptr) {
MS_LOG(ERROR) << "primitive is nullptr";
return false;
}
if (primitive->GetAttr(ops::kAxis) != nullptr) {
auto axis = api::GetValue<std::vector<int64_t>>(primitive->GetAttr(ops::kAxis));
if (axis.size() != 1) {
MS_LOG(WARNING) << "reverse's axis size only supports 1 by dpico. " << op->fullname_with_scope();
return false;
}
}
return true;
}
OpCheckerRegistrar g_ReverseChecker("ReverseV2", new ReverseChecker());
} // namespace dpico
} // namespace mindspore
|
/*
binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
Note:
The order of output does not matter.
The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
*/
// 语法错误类型:
// Line 5: expected identifier before numeric constant
// 将vector构造放在函数外
// Line 24: invalid types '<unresolved overloaded function type>[int]' for array subscript
// 将参数外的方框写成小括号造成的
// 注意,在类中方法外不能使用vector<int> a(k, x)的形式
// 需要先申明vector<int> a,然后再构造函数中初始化,
// 或者以 vector<int> a = vector<int>(5) 的形式赋值
class Solution {
private:
// hours[i]代表i个1可以表示的小时数
// hours[4]代表大于等于4个1能够表示的小时数,显然为无效
// vector< vector<int> > hours(4, vector<int>(1, 0));
// vector< vector<int> > minites(6, vector<int>(1, 0));
vector< vector<int> > hours = vector< vector<int> >(4, vector<int>());
vector< vector<int> > minites = vector< vector<int> >(6, vector<int>());
public:
int ones(int n) {
// 统计n中1的个数
if(n==0) return 0;
if(n==1) return 1;
if(n%2) return 1+ones(n>>1);
else return ones(n>>1);
}
void initHoursMinites() {
for(int i=0; i<12; i++) {
int tmp = ones(i);
hours[tmp].push_back(i);
}
for(int i=0; i<60; i++) {
int tmp = ones(i);
minites[tmp].push_back(i);
}
}
vector<string> readBinaryWatch(int num) {
vector<string> ans;
unordered_set<string> uset;
if(num < 0 || num>8) return ans; //超过8个1,无合法时间,表示11:59只需要8个1
initHoursMinites();
for(int l=0, r=num; l<=num && i<= 11; l++, r--) {
if(l>3 || r>5) continue;
for(int i=0; i<hours[l].size(); i++) {
for(int j=0; j<minites[r].size(); j++) {
string tmp = to_string(hours[l][i])+":"+ (minites[r][j]<10?"0":"") +to_string(minites[r][j]);
uset.insert(tmp);
}
}
}
for(auto t:uset) ans.push_back(t);
return ans;
}
};
// 上述统计1个数的算法的标准写法为
int bitCount(int n) {
int cnt = 0;
while(n) {
n = n&(n-1);
cnt++;
}
return cnt;:w
}
// Solution 2
// https://discuss.leetcode.com/topic/59585/only-0ms-c-solution-easy-understand
class Solution {
public:
int bitCount(int c)
{
int count=0;
while (c)
{
c=c&(c-1);
count++;
}
return count;
}
vector<string> readBinaryWatch(int num) {
int bottom;
vector<string> result;
for (int i=0;i<=11;++i)
{
bottom=num-bitCount(i);
if (bottom<0) continue;
for (int j=0;j<60;++j)
{
if (bitCount(j)==bottom)
{
string s=to_string(i);
s=s+':';
if (j<10)
{
s=s+'0';
s=s+to_string(j);
}
else s+=to_string(j);
result.push_back(s);
}
}
}
return result;
}
};
|
/*******************************************************************************
NES Sound Driver & Library (NSD.lib) MML Compiler
Copyright (c) 2012 A.Watanabe (S.W.), All rights reserved.
For conditions of distribution and use, see copyright notice in "nsc.cpp".
*******************************************************************************/
#include "StdAfx.h"
#include "VRC7.h"
//==============================================================
// コンストラクタ
//--------------------------------------------------------------
// ●引数
// MMLfile* MML MMLファイルのオブジェクト
// unsigned int _id VRC7音色番号
// const _CHAR _strName[] オブジェクト名
// ●返値
// 無し
//==============================================================
VRC7::VRC7(MMLfile* MML, unsigned int _id, const _CHAR _strName[]):
MusicItem(_id, _strName),
m_id(_id)
{
//----------------------
//Local変数
int i;
bool _mset = false;
unsigned char _mode = 0;
unsigned char _pt = 0;
unsigned char _opll[24];
unsigned char cData;
// 定数定義
enum Command_ID_mml {
VRC7_Normal,
VRC7_Resister,
VRC7_Num,
VRC7_Comma
};
// これらは、MML構文で使えるコマンド。
const static Command_Info Command[] = {
{ "@R", VRC7_Resister },
{ "@", VRC7_Normal },
{ "0", VRC7_Num },
{ "1", VRC7_Num },
{ "2", VRC7_Num },
{ "3", VRC7_Num },
{ "4", VRC7_Num },
{ "5", VRC7_Num },
{ "6", VRC7_Num },
{ "7", VRC7_Num },
{ "8", VRC7_Num },
{ "9", VRC7_Num },
{ "$", VRC7_Num },
{ "%", VRC7_Num },
{ ",", VRC7_Comma }
};
//------------------------------
//クラスの初期設定
iSize = 8;
code.resize(iSize);
//------------------------------
//コンパイル
// { の検索
while(MML->cRead() != '{'){
if(MML->eof()){
MML->Err(_T("ブロックの開始を示す{が見つかりません。"));
}
}
// } が来るまで、記述ブロック内をコンパイルする。
while((cData = MML->GetChar()) != '}'){
// } が来る前に、[EOF]が来たらエラー
if( MML->eof() ){
MML->Err(_T("ブロックの終端を示す`}'がありません。"));
}
//1つ戻る
MML->Back();
//各コマンド毎の処理
switch(MML->GetCommandID(Command, sizeof(Command)/sizeof(Command_Info))){
case(VRC7_Normal):
if(_mset == true){
MML->Err(_T("@, @Rコマンドは1回だけ指定して下さい。"));
}
_mset = true;
_mode = 0;
break;
case(VRC7_Resister):
if(_mset == true){
MML->Err(_T("@, @Rコマンドは1回だけ指定して下さい。"));
}
_mset = true;
_mode = 1;
break;
case(VRC7_Num):
if(_mset == false){
MML->Err(_T("先ずは@, @Rコマンドを記述して下さい。"));
}
MML->Back();
i = MML->GetInt();
if( (i<0) || (i>255) ){
MML->Err(_T("0〜255の範囲で指定して下さい。"));
}
if(_mode == 0){
if(_pt >= 24){
MML->Err(_T("VRC7(パラメータベース)の引数が24個を超えました。"));
}
_opll[_pt] = (unsigned char)i;
} else {
if(_pt >= 8){
MML->Err(_T("VRC7(レジスタベース)の引数が8個を超えました。"));
}
code[_pt] = (unsigned char)i;
}
_pt++;
break;
case(VRC7_Comma):
break;
//unknown command
default:
MML->Err(_T("unknown command"));
break;
}
}
if(_mode == 0){
if(_pt < 24){
MML->Err(_T("VRC7(パラメータベース)の引数が24個に満たないです。"));
}
//TL FB
//0 1
//AR DR SL RR KL MT AM VB EG KR DT
//2 3 4 5 6 7 8 9 10 11 12
//AR DR SL RR KL MT AM VB EG KR DT
//13 14 15 16 17 18 19 20 21 22 23
code[0] = ((_opll[ 8] & 0x01) << 7) | ((_opll[ 9] & 0x01) << 6) | ((_opll[10] & 0x01) << 5) | ((_opll[11] & 0x01) << 4) | (_opll[ 7] & 0x0F);
code[1] = ((_opll[19] & 0x01) << 7) | ((_opll[20] & 0x01) << 6) | ((_opll[21] & 0x01) << 5) | ((_opll[22] & 0x01) << 4) | (_opll[18] & 0x0F);
code[2] = ((_opll[ 6] & 0x03) << 6) | (_opll[ 0] & 0x3F);
code[3] = ((_opll[17] & 0x03) << 6) | ((_opll[23] & 0x01) << 4) | ((_opll[12] & 0x01) << 3) | (_opll[ 1] & 0x07);
code[4] = ((_opll[ 2] & 0x0F) << 4) | (_opll[ 3] & 0x0F);
code[5] = ((_opll[13] & 0x0F) << 4) | (_opll[14] & 0x0F);
code[6] = ((_opll[ 4] & 0x0F) << 4) | (_opll[ 5] & 0x0F);
code[7] = ((_opll[15] & 0x0F) << 4) | (_opll[16] & 0x0F);
} else {
if(_pt < 8){
MML->Err(_T("VRC7(レジスタベース)の引数が8個に満たないです。"));
}
}
}
//==============================================================
// デストラクタ
//--------------------------------------------------------------
// ●引数
// 無し
// ●返値
// 無し
//==============================================================
VRC7::~VRC7(void)
{
}
//==============================================================
// コードの取得
//--------------------------------------------------------------
// ●引数
// MusicFile* MUS コードを出力する曲データファイル・オブジェクト
// ●返値
// 無し
//==============================================================
void VRC7::getAsm(MusicFile* MUS)
{
*MUS << MUS->Header.Label.c_str() << "VRC7" << m_id << ":" << endl;
MusicItem::getAsm(MUS);
}
|
/* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
/*
* $Header: /fuji/lewis/RCS/PixelMapButtonItem.cc,v 1.6 1992/09/08 16:40:43 lewis Exp $
*
* TODO:
*
* Changes:
* $Log: PixelMapButtonItem.cc,v $
* Revision 1.6 1992/09/08 16:40:43 lewis
* Renamed NULL -> Nil.
*
* Revision 1.5 1992/09/01 17:25:44 sterling
* Lots of Foundation changes.
*
* Revision 1.5 1992/02/18 03:50:39 lewis
* Had to change type name of Version to SaveableVersion to avoid name conflict.
*
* Revision 1.3 1992/02/05 06:06:37 lewis
* cleanup, and use PixelMapFromData () instead of direct PixelMap constructor. Create new
* savable version, and dont read/write pixelmap since it doesnt work right under X yet.
*
* Revision 1.2 1992/02/03 19:41:08 sterling
* switched constructor arfs
*
* Revision 1.1 1992/02/03 17:39:17 sterling
* Initial revision
*
*
*/
#include "StreamUtils.hh"
#include "Dialog.hh"
#include "PushButton.hh"
#include "PixelMapButton.hh"
#include "PixelMapButtonItem.hh"
#include "CommandNumbers.hh"
#include "ViewItemInfo.hh"
#include "PixelMapButtonInfo.hh"
/*
********************************************************************************
**************************** PixelMapButtonItemType ****************************
********************************************************************************
*/
PixelMapButtonItemType::PixelMapButtonItemType ():
#if qHP_BadTypedefForStaticProcs
ItemType (eBuildButton, "PixelMapButton", (ItemBuilderProc)&PixelMapButtonItemBuilder)
#else
ItemType (eBuildButton, "PixelMapButton", &PixelMapButtonItemBuilder)
#endif
{
Require (sThis == Nil);
sThis = this;
}
PixelMapButtonItemType& PixelMapButtonItemType::Get ()
{
RequireNotNil (sThis);
return (*sThis);
}
ViewItem* PixelMapButtonItemType::PixelMapButtonItemBuilder ()
{
return (new PixelMapButtonItem (Get ()));
}
PixelMapButtonItemType* PixelMapButtonItemType::sThis = Nil;
static AbstractPixelMapButton* BuildPixelMapButton (CommandNumber gui, const PixelMap& pm)
{
if (gui == eMacUI) {
return (new PixelMapButton_MacUI_Portable (pm, Nil));
}
else if (gui == eMotifUI) {
return (new PixelMapButton_MotifUI_Portable (pm, Nil));
}
else if (gui == eWindowsGUI) {
return (new PixelMapButton_WinUI_Portable (pm, Nil));
}
AssertNotReached (); return (Nil);
}
/*
********************************************************************************
**************************** PixelMapButtonItem ********************************
********************************************************************************
*/
const SaveableVersion kOne = 1; // original version reads/writes old format pixelmaps
const SaveableVersion kTwo = 2; // dont write pixelmaps cuz doesnt work under X yet (Feb 4, 1992)
const SaveableVersion kThree = 3; // allow pixelmaps read/write again
PixelMapButtonItem::PixelMapButtonItem (ItemType& type):
ButtonItem (type),
fPixelMapButton (Nil)
{
static UInt8 kPIXELMAPBUTTON_Data [] = {
0xFF, 0xFF,
0x55, 0xD5,
0xFF, 0xBF,
0x5, 0xE0,
0xF7, 0xAF,
0x55, 0xED,
0xF7, 0xAB,
0x55, 0xEE,
0x77, 0xAA,
0xD5, 0xEF,
0xB7, 0xAA,
0xF5, 0xEF,
0x7, 0xA0,
0xFD, 0xFF,
0xAB, 0xAA,
0xFF, 0xFF,
};
const PixelMap kPIXELMAPBUTTON = PixelMapFromData (Point (16, 16), kPIXELMAPBUTTON_Data, sizeof (kPIXELMAPBUTTON_Data));
SetButton (fPixelMapButton = BuildPixelMapButton (EmilyWindow::GetGUI (), kPIXELMAPBUTTON));
SetMaxVersion (kThree);
}
void PixelMapButtonItem::GUIChanged (CommandNumber /*oldGUI*/, CommandNumber newGUI)
{
SetButton (fPixelMapButton = BuildPixelMapButton (newGUI, fPixelMapButton->GetPixelMap ()));
ApplyCurrentParams ();
}
String PixelMapButtonItem::GetHeaderFileName ()
{
static const String kHeaderFileName = "PixelMapButton.hh";
return (kHeaderFileName);
}
AbstractPixelMapButton& PixelMapButtonItem::GetPixelMapButton () const
{
RequireNotNil (fPixelMapButton);
return (*fPixelMapButton);
}
void PixelMapButtonItem::DoRead_ (class istream& from)
{
ButtonItem::DoRead_ (from);
if (GetVersion () != kTwo) {
PixelMap pm = PixelMap (kZeroRect);
from >> pm;
fPixelMapButton->SetPixelMap (pm);
}
}
void PixelMapButtonItem::DoWrite_ (class ostream& to, int tabCount) const
{
ButtonItem::DoWrite_ (to, tabCount);
to << tab (tabCount) << fPixelMapButton->GetPixelMap () << ' ' << newline;
}
void PixelMapButtonItem::WriteBuilder (class ostream& to, int tabCount)
{
ViewItem::WriteBuilder (to, tabCount);
to << ViewItem::kEmptyInitializer << newline;
}
void PixelMapButtonItem::WriteParameters (class ostream& to, int tabCount, CommandNumber language, CommandNumber gui)
{
ButtonItem::WriteParameters (to, tabCount, language, gui);
to << tab (tabCount) << GetFieldName () << ".SetController (this);" << newline;
}
void PixelMapButtonItem::SetItemInfo ()
{
PixelMapButtonInfo info = PixelMapButtonInfo (*this);
Dialog d = Dialog (&info, &info, AbstractPushButton::kOKLabel, AbstractPushButton::kCancelLabel);
d.SetDefaultButton (d.GetOKButton ());
if (d.Pose ()) {
PostCommand (new SetPixelMapButtonInfoCommand (*this, info));
DirtyDocument ();
}
}
SetPixelMapButtonInfoCommand::SetPixelMapButtonInfoCommand (PixelMapButtonItem& item, class PixelMapButtonInfo& info) :
Command (eSetItemInfo, kUndoable),
fItem (item),
fItemInfoCommand (Nil),
fNewPixelMap (info.GetPixelMap ()),
fOldPixelMap (item.GetPixelMapButton ().GetPixelMap ())
{
fItemInfoCommand = new SetItemInfoCommand (item, info.GetViewItemInfo ());
}
void SetPixelMapButtonInfoCommand::DoIt ()
{
fItemInfoCommand->DoIt ();
fItem.GetPixelMapButton ().SetPixelMap (fNewPixelMap);
Command::DoIt ();
}
void SetPixelMapButtonInfoCommand::UnDoIt ()
{
fItemInfoCommand->UnDoIt ();
fItem.GetPixelMapButton ().SetPixelMap (fOldPixelMap);
Command::UnDoIt ();
}
// For gnuemacs:
// Local Variables: ***
// mode:C ***
// tab-width:4 ***
// End: ***
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_CEPHES_FUNCTION_SIMD_SSE_SSE4_2_ACOSH_HPP_INCLUDED
#define NT2_TOOLBOX_CEPHES_FUNCTION_SIMD_SSE_SSE4_2_ACOSH_HPP_INCLUDED
#include <nt2/toolbox/cephes/function/simd/sse/sse4_1/acosh.hpp>
#endif
|
/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "logging/rtc_event_log/encoder/rtc_event_log_encoder_legacy.h"
#include <string.h>
#include <vector>
#include "absl/types/optional.h"
#include "api/array_view.h"
#include "api/network_state_predictor.h"
#include "api/rtp_headers.h"
#include "api/rtp_parameters.h"
#include "api/transport/network_types.h"
#include "logging/rtc_event_log/events/rtc_event_alr_state.h"
#include "logging/rtc_event_log/events/rtc_event_audio_network_adaptation.h"
#include "logging/rtc_event_log/events/rtc_event_audio_playout.h"
#include "logging/rtc_event_log/events/rtc_event_audio_receive_stream_config.h"
#include "logging/rtc_event_log/events/rtc_event_audio_send_stream_config.h"
#include "logging/rtc_event_log/events/rtc_event_bwe_update_delay_based.h"
#include "logging/rtc_event_log/events/rtc_event_bwe_update_loss_based.h"
#include "logging/rtc_event_log/events/rtc_event_ice_candidate_pair.h"
#include "logging/rtc_event_log/events/rtc_event_ice_candidate_pair_config.h"
#include "logging/rtc_event_log/events/rtc_event_probe_cluster_created.h"
#include "logging/rtc_event_log/events/rtc_event_probe_result_failure.h"
#include "logging/rtc_event_log/events/rtc_event_probe_result_success.h"
#include "logging/rtc_event_log/events/rtc_event_rtcp_packet_incoming.h"
#include "logging/rtc_event_log/events/rtc_event_rtcp_packet_outgoing.h"
#include "logging/rtc_event_log/events/rtc_event_rtp_packet_incoming.h"
#include "logging/rtc_event_log/events/rtc_event_rtp_packet_outgoing.h"
#include "logging/rtc_event_log/events/rtc_event_video_receive_stream_config.h"
#include "logging/rtc_event_log/events/rtc_event_video_send_stream_config.h"
#include "logging/rtc_event_log/rtc_stream_config.h"
#include "modules/audio_coding/audio_network_adaptor/include/audio_network_adaptor_config.h"
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "modules/rtp_rtcp/source/rtcp_packet/app.h"
#include "modules/rtp_rtcp/source/rtcp_packet/bye.h"
#include "modules/rtp_rtcp/source/rtcp_packet/common_header.h"
#include "modules/rtp_rtcp/source/rtcp_packet/extended_jitter_report.h"
#include "modules/rtp_rtcp/source/rtcp_packet/extended_reports.h"
#include "modules/rtp_rtcp/source/rtcp_packet/psfb.h"
#include "modules/rtp_rtcp/source/rtcp_packet/receiver_report.h"
#include "modules/rtp_rtcp/source/rtcp_packet/rtpfb.h"
#include "modules/rtp_rtcp/source/rtcp_packet/sdes.h"
#include "modules/rtp_rtcp/source/rtcp_packet/sender_report.h"
#include "modules/rtp_rtcp/source/rtp_packet.h"
#include "rtc_base/checks.h"
#include "rtc_base/ignore_wundef.h"
#include "rtc_base/logging.h"
// *.pb.h files are generated at build-time by the protobuf compiler.
RTC_PUSH_IGNORING_WUNDEF()
#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
#include "external/webrtc/webrtc/logging/rtc_event_log/rtc_event_log.pb.h"
#else
#include "logging/rtc_event_log/rtc_event_log.pb.h"
#endif
RTC_POP_IGNORING_WUNDEF()
namespace webrtc {
namespace {
rtclog::DelayBasedBweUpdate::DetectorState ConvertDetectorState(
BandwidthUsage state) {
switch (state) {
case BandwidthUsage::kBwNormal:
return rtclog::DelayBasedBweUpdate::BWE_NORMAL;
case BandwidthUsage::kBwUnderusing:
return rtclog::DelayBasedBweUpdate::BWE_UNDERUSING;
case BandwidthUsage::kBwOverusing:
return rtclog::DelayBasedBweUpdate::BWE_OVERUSING;
case BandwidthUsage::kLast:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::DelayBasedBweUpdate::BWE_NORMAL;
}
rtclog::BweProbeResult::ResultType ConvertProbeResultType(
ProbeFailureReason failure_reason) {
switch (failure_reason) {
case ProbeFailureReason::kInvalidSendReceiveInterval:
return rtclog::BweProbeResult::INVALID_SEND_RECEIVE_INTERVAL;
case ProbeFailureReason::kInvalidSendReceiveRatio:
return rtclog::BweProbeResult::INVALID_SEND_RECEIVE_RATIO;
case ProbeFailureReason::kTimeout:
return rtclog::BweProbeResult::TIMEOUT;
case ProbeFailureReason::kLast:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::BweProbeResult::SUCCESS;
}
rtclog::VideoReceiveConfig_RtcpMode ConvertRtcpMode(RtcpMode rtcp_mode) {
switch (rtcp_mode) {
case RtcpMode::kCompound:
return rtclog::VideoReceiveConfig::RTCP_COMPOUND;
case RtcpMode::kReducedSize:
return rtclog::VideoReceiveConfig::RTCP_REDUCEDSIZE;
case RtcpMode::kOff:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::VideoReceiveConfig::RTCP_COMPOUND;
}
rtclog::IceCandidatePairConfig::IceCandidatePairConfigType
ConvertIceCandidatePairConfigType(IceCandidatePairConfigType type) {
switch (type) {
case IceCandidatePairConfigType::kAdded:
return rtclog::IceCandidatePairConfig::ADDED;
case IceCandidatePairConfigType::kUpdated:
return rtclog::IceCandidatePairConfig::UPDATED;
case IceCandidatePairConfigType::kDestroyed:
return rtclog::IceCandidatePairConfig::DESTROYED;
case IceCandidatePairConfigType::kSelected:
return rtclog::IceCandidatePairConfig::SELECTED;
case IceCandidatePairConfigType::kNumValues:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::IceCandidatePairConfig::ADDED;
}
rtclog::IceCandidatePairConfig::IceCandidateType ConvertIceCandidateType(
IceCandidateType type) {
switch (type) {
case IceCandidateType::kUnknown:
return rtclog::IceCandidatePairConfig::UNKNOWN_CANDIDATE_TYPE;
case IceCandidateType::kLocal:
return rtclog::IceCandidatePairConfig::LOCAL;
case IceCandidateType::kStun:
return rtclog::IceCandidatePairConfig::STUN;
case IceCandidateType::kPrflx:
return rtclog::IceCandidatePairConfig::PRFLX;
case IceCandidateType::kRelay:
return rtclog::IceCandidatePairConfig::RELAY;
case IceCandidateType::kNumValues:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::IceCandidatePairConfig::UNKNOWN_CANDIDATE_TYPE;
}
rtclog::IceCandidatePairConfig::Protocol ConvertIceCandidatePairProtocol(
IceCandidatePairProtocol protocol) {
switch (protocol) {
case IceCandidatePairProtocol::kUnknown:
return rtclog::IceCandidatePairConfig::UNKNOWN_PROTOCOL;
case IceCandidatePairProtocol::kUdp:
return rtclog::IceCandidatePairConfig::UDP;
case IceCandidatePairProtocol::kTcp:
return rtclog::IceCandidatePairConfig::TCP;
case IceCandidatePairProtocol::kSsltcp:
return rtclog::IceCandidatePairConfig::SSLTCP;
case IceCandidatePairProtocol::kTls:
return rtclog::IceCandidatePairConfig::TLS;
case IceCandidatePairProtocol::kNumValues:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::IceCandidatePairConfig::UNKNOWN_PROTOCOL;
}
rtclog::IceCandidatePairConfig::AddressFamily
ConvertIceCandidatePairAddressFamily(
IceCandidatePairAddressFamily address_family) {
switch (address_family) {
case IceCandidatePairAddressFamily::kUnknown:
return rtclog::IceCandidatePairConfig::UNKNOWN_ADDRESS_FAMILY;
case IceCandidatePairAddressFamily::kIpv4:
return rtclog::IceCandidatePairConfig::IPV4;
case IceCandidatePairAddressFamily::kIpv6:
return rtclog::IceCandidatePairConfig::IPV6;
case IceCandidatePairAddressFamily::kNumValues:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::IceCandidatePairConfig::UNKNOWN_ADDRESS_FAMILY;
}
rtclog::IceCandidatePairConfig::NetworkType ConvertIceCandidateNetworkType(
IceCandidateNetworkType network_type) {
switch (network_type) {
case IceCandidateNetworkType::kUnknown:
return rtclog::IceCandidatePairConfig::UNKNOWN_NETWORK_TYPE;
case IceCandidateNetworkType::kEthernet:
return rtclog::IceCandidatePairConfig::ETHERNET;
case IceCandidateNetworkType::kLoopback:
return rtclog::IceCandidatePairConfig::LOOPBACK;
case IceCandidateNetworkType::kWifi:
return rtclog::IceCandidatePairConfig::WIFI;
case IceCandidateNetworkType::kVpn:
return rtclog::IceCandidatePairConfig::VPN;
case IceCandidateNetworkType::kCellular:
return rtclog::IceCandidatePairConfig::CELLULAR;
case IceCandidateNetworkType::kNumValues:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::IceCandidatePairConfig::UNKNOWN_NETWORK_TYPE;
}
rtclog::IceCandidatePairEvent::IceCandidatePairEventType
ConvertIceCandidatePairEventType(IceCandidatePairEventType type) {
switch (type) {
case IceCandidatePairEventType::kCheckSent:
return rtclog::IceCandidatePairEvent::CHECK_SENT;
case IceCandidatePairEventType::kCheckReceived:
return rtclog::IceCandidatePairEvent::CHECK_RECEIVED;
case IceCandidatePairEventType::kCheckResponseSent:
return rtclog::IceCandidatePairEvent::CHECK_RESPONSE_SENT;
case IceCandidatePairEventType::kCheckResponseReceived:
return rtclog::IceCandidatePairEvent::CHECK_RESPONSE_RECEIVED;
case IceCandidatePairEventType::kNumValues:
RTC_DCHECK_NOTREACHED();
}
RTC_DCHECK_NOTREACHED();
return rtclog::IceCandidatePairEvent::CHECK_SENT;
}
} // namespace
std::string RtcEventLogEncoderLegacy::EncodeLogStart(int64_t timestamp_us,
int64_t utc_time_us) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(timestamp_us);
rtclog_event.set_type(rtclog::Event::LOG_START);
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeLogEnd(int64_t timestamp_us) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(timestamp_us);
rtclog_event.set_type(rtclog::Event::LOG_END);
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeBatch(
std::deque<std::unique_ptr<RtcEvent>>::const_iterator begin,
std::deque<std::unique_ptr<RtcEvent>>::const_iterator end) {
std::string encoded_output;
for (auto it = begin; it != end; ++it) {
// TODO(terelius): Can we avoid the slight inefficiency of reallocating the
// string?
RTC_CHECK(it->get() != nullptr);
encoded_output += Encode(**it);
}
return encoded_output;
}
std::string RtcEventLogEncoderLegacy::Encode(const RtcEvent& event) {
switch (event.GetType()) {
case RtcEvent::Type::AudioNetworkAdaptation: {
auto& rtc_event =
static_cast<const RtcEventAudioNetworkAdaptation&>(event);
return EncodeAudioNetworkAdaptation(rtc_event);
}
case RtcEvent::Type::AlrStateEvent: {
auto& rtc_event = static_cast<const RtcEventAlrState&>(event);
return EncodeAlrState(rtc_event);
}
case RtcEvent::Type::AudioPlayout: {
auto& rtc_event = static_cast<const RtcEventAudioPlayout&>(event);
return EncodeAudioPlayout(rtc_event);
}
case RtcEvent::Type::AudioReceiveStreamConfig: {
auto& rtc_event =
static_cast<const RtcEventAudioReceiveStreamConfig&>(event);
return EncodeAudioReceiveStreamConfig(rtc_event);
}
case RtcEvent::Type::AudioSendStreamConfig: {
auto& rtc_event =
static_cast<const RtcEventAudioSendStreamConfig&>(event);
return EncodeAudioSendStreamConfig(rtc_event);
}
case RtcEvent::Type::BweUpdateDelayBased: {
auto& rtc_event = static_cast<const RtcEventBweUpdateDelayBased&>(event);
return EncodeBweUpdateDelayBased(rtc_event);
}
case RtcEvent::Type::BweUpdateLossBased: {
auto& rtc_event = static_cast<const RtcEventBweUpdateLossBased&>(event);
return EncodeBweUpdateLossBased(rtc_event);
}
case RtcEvent::Type::DtlsTransportState: {
return "";
}
case RtcEvent::Type::DtlsWritableState: {
return "";
}
case RtcEvent::Type::IceCandidatePairConfig: {
auto& rtc_event =
static_cast<const RtcEventIceCandidatePairConfig&>(event);
return EncodeIceCandidatePairConfig(rtc_event);
}
case RtcEvent::Type::IceCandidatePairEvent: {
auto& rtc_event = static_cast<const RtcEventIceCandidatePair&>(event);
return EncodeIceCandidatePairEvent(rtc_event);
}
case RtcEvent::Type::ProbeClusterCreated: {
auto& rtc_event = static_cast<const RtcEventProbeClusterCreated&>(event);
return EncodeProbeClusterCreated(rtc_event);
}
case RtcEvent::Type::ProbeResultFailure: {
auto& rtc_event = static_cast<const RtcEventProbeResultFailure&>(event);
return EncodeProbeResultFailure(rtc_event);
}
case RtcEvent::Type::ProbeResultSuccess: {
auto& rtc_event = static_cast<const RtcEventProbeResultSuccess&>(event);
return EncodeProbeResultSuccess(rtc_event);
}
case RtcEvent::Type::RtcpPacketIncoming: {
auto& rtc_event = static_cast<const RtcEventRtcpPacketIncoming&>(event);
return EncodeRtcpPacketIncoming(rtc_event);
}
case RtcEvent::Type::RtcpPacketOutgoing: {
auto& rtc_event = static_cast<const RtcEventRtcpPacketOutgoing&>(event);
return EncodeRtcpPacketOutgoing(rtc_event);
}
case RtcEvent::Type::RtpPacketIncoming: {
auto& rtc_event = static_cast<const RtcEventRtpPacketIncoming&>(event);
return EncodeRtpPacketIncoming(rtc_event);
}
case RtcEvent::Type::RtpPacketOutgoing: {
auto& rtc_event = static_cast<const RtcEventRtpPacketOutgoing&>(event);
return EncodeRtpPacketOutgoing(rtc_event);
}
case RtcEvent::Type::VideoReceiveStreamConfig: {
auto& rtc_event =
static_cast<const RtcEventVideoReceiveStreamConfig&>(event);
return EncodeVideoReceiveStreamConfig(rtc_event);
}
case RtcEvent::Type::VideoSendStreamConfig: {
auto& rtc_event =
static_cast<const RtcEventVideoSendStreamConfig&>(event);
return EncodeVideoSendStreamConfig(rtc_event);
}
case RtcEvent::Type::RouteChangeEvent:
case RtcEvent::Type::RemoteEstimateEvent:
case RtcEvent::Type::GenericPacketReceived:
case RtcEvent::Type::GenericPacketSent:
case RtcEvent::Type::GenericAckReceived:
case RtcEvent::Type::FrameDecoded:
// These are unsupported in the old format, but shouldn't crash.
return "";
}
int event_type = static_cast<int>(event.GetType());
RTC_DCHECK_NOTREACHED() << "Unknown event type (" << event_type << ")";
return "";
}
std::string RtcEventLogEncoderLegacy::EncodeAlrState(
const RtcEventAlrState& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::ALR_STATE_EVENT);
auto* alr_state = rtclog_event.mutable_alr_state();
alr_state->set_in_alr(event.in_alr());
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeAudioNetworkAdaptation(
const RtcEventAudioNetworkAdaptation& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::AUDIO_NETWORK_ADAPTATION_EVENT);
auto* audio_network_adaptation =
rtclog_event.mutable_audio_network_adaptation();
if (event.config().bitrate_bps)
audio_network_adaptation->set_bitrate_bps(*event.config().bitrate_bps);
if (event.config().frame_length_ms)
audio_network_adaptation->set_frame_length_ms(
*event.config().frame_length_ms);
if (event.config().uplink_packet_loss_fraction) {
audio_network_adaptation->set_uplink_packet_loss_fraction(
*event.config().uplink_packet_loss_fraction);
}
if (event.config().enable_fec)
audio_network_adaptation->set_enable_fec(*event.config().enable_fec);
if (event.config().enable_dtx)
audio_network_adaptation->set_enable_dtx(*event.config().enable_dtx);
if (event.config().num_channels)
audio_network_adaptation->set_num_channels(*event.config().num_channels);
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeAudioPlayout(
const RtcEventAudioPlayout& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::AUDIO_PLAYOUT_EVENT);
auto* playout_event = rtclog_event.mutable_audio_playout_event();
playout_event->set_local_ssrc(event.ssrc());
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeAudioReceiveStreamConfig(
const RtcEventAudioReceiveStreamConfig& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::AUDIO_RECEIVER_CONFIG_EVENT);
rtclog::AudioReceiveConfig* receiver_config =
rtclog_event.mutable_audio_receiver_config();
receiver_config->set_remote_ssrc(event.config().remote_ssrc);
receiver_config->set_local_ssrc(event.config().local_ssrc);
for (const auto& e : event.config().rtp_extensions) {
rtclog::RtpHeaderExtension* extension =
receiver_config->add_header_extensions();
extension->set_name(e.uri);
extension->set_id(e.id);
}
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeAudioSendStreamConfig(
const RtcEventAudioSendStreamConfig& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::AUDIO_SENDER_CONFIG_EVENT);
rtclog::AudioSendConfig* sender_config =
rtclog_event.mutable_audio_sender_config();
sender_config->set_ssrc(event.config().local_ssrc);
for (const auto& e : event.config().rtp_extensions) {
rtclog::RtpHeaderExtension* extension =
sender_config->add_header_extensions();
extension->set_name(e.uri);
extension->set_id(e.id);
}
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeBweUpdateDelayBased(
const RtcEventBweUpdateDelayBased& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::DELAY_BASED_BWE_UPDATE);
auto* bwe_event = rtclog_event.mutable_delay_based_bwe_update();
bwe_event->set_bitrate_bps(event.bitrate_bps());
bwe_event->set_detector_state(ConvertDetectorState(event.detector_state()));
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeBweUpdateLossBased(
const RtcEventBweUpdateLossBased& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::LOSS_BASED_BWE_UPDATE);
auto* bwe_event = rtclog_event.mutable_loss_based_bwe_update();
bwe_event->set_bitrate_bps(event.bitrate_bps());
bwe_event->set_fraction_loss(event.fraction_loss());
bwe_event->set_total_packets(event.total_packets());
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeIceCandidatePairConfig(
const RtcEventIceCandidatePairConfig& event) {
rtclog::Event encoded_rtc_event;
encoded_rtc_event.set_timestamp_us(event.timestamp_us());
encoded_rtc_event.set_type(rtclog::Event::ICE_CANDIDATE_PAIR_CONFIG);
auto* encoded_ice_event =
encoded_rtc_event.mutable_ice_candidate_pair_config();
encoded_ice_event->set_config_type(
ConvertIceCandidatePairConfigType(event.type()));
encoded_ice_event->set_candidate_pair_id(event.candidate_pair_id());
const auto& desc = event.candidate_pair_desc();
encoded_ice_event->set_local_candidate_type(
ConvertIceCandidateType(desc.local_candidate_type));
encoded_ice_event->set_local_relay_protocol(
ConvertIceCandidatePairProtocol(desc.local_relay_protocol));
encoded_ice_event->set_local_network_type(
ConvertIceCandidateNetworkType(desc.local_network_type));
encoded_ice_event->set_local_address_family(
ConvertIceCandidatePairAddressFamily(desc.local_address_family));
encoded_ice_event->set_remote_candidate_type(
ConvertIceCandidateType(desc.remote_candidate_type));
encoded_ice_event->set_remote_address_family(
ConvertIceCandidatePairAddressFamily(desc.remote_address_family));
encoded_ice_event->set_candidate_pair_protocol(
ConvertIceCandidatePairProtocol(desc.candidate_pair_protocol));
return Serialize(&encoded_rtc_event);
}
std::string RtcEventLogEncoderLegacy::EncodeIceCandidatePairEvent(
const RtcEventIceCandidatePair& event) {
rtclog::Event encoded_rtc_event;
encoded_rtc_event.set_timestamp_us(event.timestamp_us());
encoded_rtc_event.set_type(rtclog::Event::ICE_CANDIDATE_PAIR_EVENT);
auto* encoded_ice_event =
encoded_rtc_event.mutable_ice_candidate_pair_event();
encoded_ice_event->set_event_type(
ConvertIceCandidatePairEventType(event.type()));
encoded_ice_event->set_candidate_pair_id(event.candidate_pair_id());
return Serialize(&encoded_rtc_event);
}
std::string RtcEventLogEncoderLegacy::EncodeProbeClusterCreated(
const RtcEventProbeClusterCreated& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::BWE_PROBE_CLUSTER_CREATED_EVENT);
auto* probe_cluster = rtclog_event.mutable_probe_cluster();
probe_cluster->set_id(event.id());
probe_cluster->set_bitrate_bps(event.bitrate_bps());
probe_cluster->set_min_packets(event.min_probes());
probe_cluster->set_min_bytes(event.min_bytes());
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeProbeResultFailure(
const RtcEventProbeResultFailure& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::BWE_PROBE_RESULT_EVENT);
auto* probe_result = rtclog_event.mutable_probe_result();
probe_result->set_id(event.id());
probe_result->set_result(ConvertProbeResultType(event.failure_reason()));
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeProbeResultSuccess(
const RtcEventProbeResultSuccess& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::BWE_PROBE_RESULT_EVENT);
auto* probe_result = rtclog_event.mutable_probe_result();
probe_result->set_id(event.id());
probe_result->set_result(rtclog::BweProbeResult::SUCCESS);
probe_result->set_bitrate_bps(event.bitrate_bps());
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeRtcpPacketIncoming(
const RtcEventRtcpPacketIncoming& event) {
return EncodeRtcpPacket(event.timestamp_us(), event.packet(), true);
}
std::string RtcEventLogEncoderLegacy::EncodeRtcpPacketOutgoing(
const RtcEventRtcpPacketOutgoing& event) {
return EncodeRtcpPacket(event.timestamp_us(), event.packet(), false);
}
std::string RtcEventLogEncoderLegacy::EncodeRtpPacketIncoming(
const RtcEventRtpPacketIncoming& event) {
return EncodeRtpPacket(event.timestamp_us(), event.RawHeader(),
event.packet_length(), PacedPacketInfo::kNotAProbe,
true);
}
std::string RtcEventLogEncoderLegacy::EncodeRtpPacketOutgoing(
const RtcEventRtpPacketOutgoing& event) {
return EncodeRtpPacket(event.timestamp_us(), event.RawHeader(),
event.packet_length(), event.probe_cluster_id(),
false);
}
std::string RtcEventLogEncoderLegacy::EncodeVideoReceiveStreamConfig(
const RtcEventVideoReceiveStreamConfig& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::VIDEO_RECEIVER_CONFIG_EVENT);
rtclog::VideoReceiveConfig* receiver_config =
rtclog_event.mutable_video_receiver_config();
receiver_config->set_remote_ssrc(event.config().remote_ssrc);
receiver_config->set_local_ssrc(event.config().local_ssrc);
// TODO(perkj): Add field for rsid.
receiver_config->set_rtcp_mode(ConvertRtcpMode(event.config().rtcp_mode));
receiver_config->set_remb(event.config().remb);
for (const auto& e : event.config().rtp_extensions) {
rtclog::RtpHeaderExtension* extension =
receiver_config->add_header_extensions();
extension->set_name(e.uri);
extension->set_id(e.id);
}
for (const auto& d : event.config().codecs) {
rtclog::DecoderConfig* decoder = receiver_config->add_decoders();
decoder->set_name(d.payload_name);
decoder->set_payload_type(d.payload_type);
if (d.rtx_payload_type != 0) {
rtclog::RtxMap* rtx = receiver_config->add_rtx_map();
rtx->set_payload_type(d.payload_type);
rtx->mutable_config()->set_rtx_ssrc(event.config().rtx_ssrc);
rtx->mutable_config()->set_rtx_payload_type(d.rtx_payload_type);
}
}
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeVideoSendStreamConfig(
const RtcEventVideoSendStreamConfig& event) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(event.timestamp_us());
rtclog_event.set_type(rtclog::Event::VIDEO_SENDER_CONFIG_EVENT);
rtclog::VideoSendConfig* sender_config =
rtclog_event.mutable_video_sender_config();
// TODO(perkj): rtclog::VideoSendConfig should only contain one SSRC.
sender_config->add_ssrcs(event.config().local_ssrc);
if (event.config().rtx_ssrc != 0) {
sender_config->add_rtx_ssrcs(event.config().rtx_ssrc);
}
for (const auto& e : event.config().rtp_extensions) {
rtclog::RtpHeaderExtension* extension =
sender_config->add_header_extensions();
extension->set_name(e.uri);
extension->set_id(e.id);
}
// TODO(perkj): rtclog::VideoSendConfig should contain many possible codec
// configurations.
for (const auto& codec : event.config().codecs) {
sender_config->set_rtx_payload_type(codec.rtx_payload_type);
rtclog::EncoderConfig* encoder = sender_config->mutable_encoder();
encoder->set_name(codec.payload_name);
encoder->set_payload_type(codec.payload_type);
if (event.config().codecs.size() > 1) {
RTC_LOG(LS_WARNING)
<< "LogVideoSendStreamConfig currently only supports one "
"codec. Logging codec :"
<< codec.payload_name;
break;
}
}
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeRtcpPacket(
int64_t timestamp_us,
const rtc::Buffer& packet,
bool is_incoming) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(timestamp_us);
rtclog_event.set_type(rtclog::Event::RTCP_EVENT);
rtclog_event.mutable_rtcp_packet()->set_incoming(is_incoming);
rtcp::CommonHeader header;
const uint8_t* block_begin = packet.data();
const uint8_t* packet_end = packet.data() + packet.size();
std::vector<uint8_t> buffer(packet.size());
uint32_t buffer_length = 0;
while (block_begin < packet_end) {
if (!header.Parse(block_begin, packet_end - block_begin)) {
break; // Incorrect message header.
}
const uint8_t* next_block = header.NextPacket();
uint32_t block_size = next_block - block_begin;
switch (header.type()) {
case rtcp::Bye::kPacketType:
case rtcp::ExtendedJitterReport::kPacketType:
case rtcp::ExtendedReports::kPacketType:
case rtcp::Psfb::kPacketType:
case rtcp::ReceiverReport::kPacketType:
case rtcp::Rtpfb::kPacketType:
case rtcp::SenderReport::kPacketType:
// We log sender reports, receiver reports, bye messages
// inter-arrival jitter, third-party loss reports, payload-specific
// feedback and extended reports.
memcpy(buffer.data() + buffer_length, block_begin, block_size);
buffer_length += block_size;
break;
case rtcp::App::kPacketType:
case rtcp::Sdes::kPacketType:
default:
// We don't log sender descriptions, application defined messages
// or message blocks of unknown type.
break;
}
block_begin += block_size;
}
rtclog_event.mutable_rtcp_packet()->set_packet_data(buffer.data(),
buffer_length);
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::EncodeRtpPacket(
int64_t timestamp_us,
rtc::ArrayView<const uint8_t> header,
size_t packet_length,
int probe_cluster_id,
bool is_incoming) {
rtclog::Event rtclog_event;
rtclog_event.set_timestamp_us(timestamp_us);
rtclog_event.set_type(rtclog::Event::RTP_EVENT);
rtclog_event.mutable_rtp_packet()->set_incoming(is_incoming);
rtclog_event.mutable_rtp_packet()->set_packet_length(packet_length);
rtclog_event.mutable_rtp_packet()->set_header(header.data(), header.size());
if (probe_cluster_id != PacedPacketInfo::kNotAProbe) {
RTC_DCHECK(!is_incoming);
rtclog_event.mutable_rtp_packet()->set_probe_cluster_id(probe_cluster_id);
}
return Serialize(&rtclog_event);
}
std::string RtcEventLogEncoderLegacy::Serialize(rtclog::Event* event) {
// Even though we're only serializing a single event during this call, what
// we intend to get is a list of events, with a tag and length preceding
// each actual event. To produce that, we serialize a list of a single event.
// If we later concatenate several results from this function, the result will
// be a proper concatenation of all those events.
rtclog::EventStream event_stream;
event_stream.add_stream();
// As a tweak, we swap the new event into the event-stream, write that to
// file, then swap back. This saves on some copying, while making sure that
// the caller wouldn't be surprised by Serialize() modifying the object.
rtclog::Event* output_event = event_stream.mutable_stream(0);
output_event->Swap(event);
std::string output_string = event_stream.SerializeAsString();
RTC_DCHECK(!output_string.empty());
// When the function returns, the original Event will be unchanged.
output_event->Swap(event);
return output_string;
}
} // namespace webrtc
|
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include"shooter.h"
/*
Test that shooter returns a Roll and verify that the roll result has one
of the following values:
Natural
Craps
Point
*/
TEST_CASE("Test case for roll result")
{
Die d1;
Die d2;
Shooter shootObject;
for (int i = 0; i < 20; i++)
{
Roll rollObject = shootObject.shoot(d1, d2);
bool check = false;
std::string result = rollObject.result();
if (result == "Craps: " || result == "Natural: " || result == "Points: ")
{
check = true;
}
REQUIRE(check == true);
}
}
|
class Solution {
public:
std::vector<std::string> generateParenthesis(int n) {
std::vector<std::pair<int, std::string>> vct_rst;
vct_rst.push_back(std::make_pair(-1, "("));
//一共有2*n个字符,已经确定第一个是‘(’
for (int i = 0; i < n * 2 - 1; ++i) {
std::vector<std::pair<int, std::string>> vct_temp;
for (int j = 0; j < vct_rst.size(); ++j) {
auto pair_tmp = vct_rst[j];
//即使剩下的字符个数填‘)',可以凑成合法的括号
if (n * 2 - i - 1 + pair_tmp.first > 0) {
vct_temp.push_back(std::pair<int, std::string>(pair_tmp.first - 1, pair_tmp.second + "("));
}
// 前面还有未匹配的‘(’
if (pair_tmp.first < 0) {
vct_temp.push_back(std::pair<int, std::string>(pair_tmp.first + 1, pair_tmp.second + ")"));
}
}
vct_rst = vct_temp;
}
std::vector<std::string> rst;
for (int i = 0; i < vct_rst.size(); ++i) {
auto pair_tmp = vct_rst[i];
rst.push_back(pair_tmp.second);
}
return rst;
}
};
|
#pragma once
#include <vector>
#include "Movie.hpp"
class Movies {
public:
Movies();
~Movies();
bool add_movie(std::string name, std::string rating, unsigned int watched);
bool increment_watched(std::string name);
void display() const;
private:
std::vector<Movie> mMovies;
};
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, All Rights Reserved
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// 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 EMC Corporation
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#include "sort.hpp"
#include "shared.hpp"
#include "analysis/token_attributes.hpp"
#include "index/index_reader.hpp"
#include "utils/memory_pool.hpp"
NS_ROOT
// ----------------------------------------------------------------------------
// --SECTION-- sort
// ----------------------------------------------------------------------------
sort::sort(const type_id& type) noexcept
: type_(&type) {
}
// ----------------------------------------------------------------------------
// --SECTION-- order
// ----------------------------------------------------------------------------
const order& order::unordered() {
static order ord;
return ord;
}
void order::remove(const type_id& type) {
order_.erase(
std::remove_if(
order_.begin(), order_.end(),
[type] (const entry& e) { return type == e.sort().type(); }
));
}
const order::prepared& order::prepared::unordered() {
static order::prepared ord;
return ord;
}
order::prepared::prepared(order::prepared&& rhs) noexcept
: order_(std::move(rhs.order_)),
features_(std::move(rhs.features_)),
score_size_(rhs.score_size_),
stats_size_(rhs.stats_size_) {
rhs.score_size_ = 0;
rhs.stats_size_ = 0;
}
order::prepared& order::prepared::operator=(order::prepared&& rhs) noexcept {
if (this != &rhs) {
order_ = std::move(rhs.order_);
features_ = std::move(rhs.features_);
score_size_ = rhs.score_size_;
rhs.score_size_ = 0;
stats_size_ = rhs.stats_size_;
rhs.stats_size_ = 0;
}
return *this;
}
bool order::operator==(const order& other) const {
if (order_.size() != other.order_.size()) {
return false;
}
for (size_t i = 0, count = order_.size(); i < count; ++i) {
auto& entry = order_[i];
auto& other_entry = other.order_[i];
auto& sort = entry.sort_;
auto& other_sort = other_entry.sort_;
// FIXME TODO operator==(...) should be specialized for every sort child class based on init config
if (!sort != !other_sort
|| (sort
&& (sort->type() != other_sort->type()
|| entry.reverse_ != other_entry.reverse_))) {
return false;
}
}
return true;
}
order& order::add(bool reverse, const sort::ptr& sort) {
assert(sort);
order_.emplace_back(sort, reverse);
return *this;
}
order::prepared order::prepare() const {
order::prepared pord;
pord.order_.reserve(order_.size());
size_t stats_align = 0;
size_t score_align = 0;
for (auto& entry : order_) {
auto prepared = entry.sort().prepare();
if (!prepared) {
// skip empty sorts
continue;
}
const auto score_size = prepared->score_size();
assert(score_size.second <= alignof(MAX_ALIGN_T));
assert(math::is_power2(score_size.second)); // math::is_power2(0) returns true
const auto stats_size = prepared->stats_size();
assert(stats_size.second <= alignof(MAX_ALIGN_T));
assert(math::is_power2(stats_size.second)); // math::is_power2(0) returns true
stats_align = std::max(stats_align, stats_size.second);
score_align = std::max(score_align, score_size.second);
pord.score_size_ = memory::align_up(pord.score_size_, score_size.second);
pord.stats_size_ = memory::align_up(pord.stats_size_, stats_size.second);
pord.features_ |= prepared->features();
pord.order_.emplace_back(
std::move(prepared),
pord.score_size_,
pord.stats_size_,
entry.reverse()
);
pord.score_size_ += memory::align_up(score_size.first, score_size.second);
pord.stats_size_ += memory::align_up(stats_size.first, stats_size.second);
}
pord.stats_size_ = memory::align_up(pord.stats_size_, stats_align);
pord.score_size_ = memory::align_up(pord.score_size_, score_align);
return pord;
}
// -----------------------------------------------------------------------------
// --SECTION-- collectors
// -----------------------------------------------------------------------------
order::prepared::collectors::collectors(
const order::prepared& buckets,
size_t terms_count)
: buckets_(buckets.order_) {
field_collectors_.reserve(buckets_.size());
term_collectors_.reserve(buckets_.size() * terms_count);
// add field collectors from each bucket
for (auto& entry: buckets_) {
assert(entry.bucket); // ensured by order::prepare
field_collectors_.emplace_back(entry.bucket->prepare_field_collector());
}
// add term collectors from each bucket
// layout order [t0.b0, t0.b1, ... t0.bN, t1.b0, t1.b1 ... tM.BN]
for (size_t i = 0; i < terms_count; ++i) {
for (auto& entry: buckets_) {
assert(entry.bucket); // ensured by order::prepare
term_collectors_.emplace_back(entry.bucket->prepare_term_collector());
}
}
}
order::prepared::collectors::collectors(collectors&& other) noexcept
: buckets_(other.buckets_),
field_collectors_(std::move(other.field_collectors_)),
term_collectors_(std::move(other.term_collectors_)) {
}
void order::prepared::collectors::collect(
const sub_reader& segment,
const term_reader& field) const {
for (auto& entry: field_collectors_) {
if (entry) { // may be null if prepare_field_collector() returned nullptr
entry->collect(segment, field);
}
}
}
void order::prepared::collectors::collect(
const sub_reader& segment,
const term_reader& field,
size_t term_offset,
const attribute_view& term_attrs) const {
for (size_t i = 0, count = buckets_.size(); i < count; ++i) {
const auto idx = term_offset * buckets_.size() + i;
assert(idx < term_collectors_.size()); // enforced by allocation in the constructor
auto& entry = term_collectors_[idx];
if (entry) { // may be null if prepare_term_collector() returned nullptr
entry->collect(segment, field, term_attrs);
}
}
}
void order::prepared::collectors::finish(
byte_type* stats_buf,
const index_reader& index) const {
// special case where term statistics collection is not applicable
// e.g. by_column_existence filter
if (term_collectors_.empty()) {
assert(field_collectors_.size() == buckets_.size()); // enforced by allocation in the constructor
for (size_t i = 0, count = field_collectors_.size(); i < count; ++i) {
auto& sort = buckets_[i];
assert(sort.bucket); // ensured by order::prepare
sort.bucket->collect(
stats_buf + sort.stats_offset, // where stats for bucket start
index,
field_collectors_[i].get(),
nullptr
);
}
} else {
auto bucket_count = buckets_.size();
assert(term_collectors_.size() % bucket_count == 0); // enforced by allocation in the constructor
for (size_t i = 0, count = term_collectors_.size(); i < count; ++i) {
auto bucket_offset = i % bucket_count;
auto& sort = buckets_[bucket_offset];
assert(sort.bucket); // ensured by order::prepare
assert(i % bucket_count < field_collectors_.size()); // enforced by allocation in the constructor
sort.bucket->collect(
stats_buf + sort.stats_offset, // where stats for bucket start
index,
field_collectors_[bucket_offset].get(),
term_collectors_[i].get()
);
}
}
}
size_t order::prepared::collectors::push_back() {
auto term_offset = term_collectors_.size() / buckets_.size();
term_collectors_.reserve(term_collectors_.size() + buckets_.size());
for (auto& entry: buckets_) {
assert(entry.bucket); // ensured by order::prepare
term_collectors_.emplace_back(entry.bucket->prepare_term_collector());
}
return term_offset;
}
// ----------------------------------------------------------------------------
// --SECTION-- scorers
// ----------------------------------------------------------------------------
order::prepared::scorers::scorers(
const prepared_order_t& buckets,
const sub_reader& segment,
const term_reader& field,
const byte_type* stats_buf,
const attribute_view& doc,
boost_t boost
) {
scorers_.reserve(buckets.size());
for (auto& entry: buckets) {
assert(stats_buf);
assert(entry.bucket); // ensured by order::prepared
const auto& bucket = *entry.bucket;
auto scorer = bucket.prepare_scorer(
segment, field, stats_buf + entry.stats_offset, doc, boost
);
if (scorer.second) {
// skip empty scorers
scorers_.emplace_back(std::move(scorer.first), scorer.second, entry.score_offset);
}
}
}
order::prepared::scorers::scorers(order::prepared::scorers&& other) noexcept
: scorers_(std::move(other.scorers_)) {
}
order::prepared::scorers& order::prepared::scorers::operator=(
order::prepared::scorers&& other
) noexcept {
if (this != &other) {
scorers_ = std::move(other.scorers_);
}
return *this;
}
void order::prepared::scorers::score(byte_type* scr) const {
for (auto& scorer : scorers_) {
assert(scorer.func);
(*scorer.func)(scorer.ctx.get(), scr + scorer.offset);
}
}
void order::prepared::prepare_collectors(
byte_type* stats_buf,
const index_reader& index
) const {
for (auto& entry: order_) {
assert(entry.bucket); // ensured by order::prepared
entry.bucket->collect(stats_buf + entry.stats_offset, index, nullptr, nullptr);
}
}
void order::prepared::prepare_score(byte_type* score) const {
for (auto& sort : order_) {
assert(sort.bucket);
sort.bucket->prepare_score(score + sort.score_offset);
}
}
void order::prepared::prepare_stats(byte_type* stats) const {
for (auto& sort : order_) {
assert(sort.bucket);
sort.bucket->prepare_stats(stats + sort.stats_offset);
}
}
bool order::prepared::less(const byte_type* lhs, const byte_type* rhs) const {
if (!lhs) {
return rhs != nullptr; // lhs(nullptr) == rhs(nullptr)
}
if (!rhs) {
return true; // nullptr last
}
for (const auto& sort: order_) {
assert(sort.bucket); // ensured by order::prepared
const auto& bucket = *sort.bucket;
const auto* lhs_begin = lhs + sort.score_offset;
const auto* rhs_begin = rhs + sort.score_offset;
if (bucket.less(lhs_begin, rhs_begin)) {
return !sort.reverse;
}
if (bucket.less(rhs_begin, lhs_begin)) {
return sort.reverse;
}
}
return false;
}
void order::prepared::add(byte_type* lhs, const byte_type* rhs) const {
for_each([lhs, rhs] (const prepared_sort& sort) {
assert(sort.bucket);
sort.bucket->add(lhs + sort.score_offset, rhs + sort.score_offset);
});
}
NS_END
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/cfile/block_cache.h"
#include <cstddef>
#include <cstdint>
#include <ostream>
#include <string>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "kudu/gutil/gscoped_ptr.h"
#include "kudu/gutil/macros.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/util/cache.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/flag_validators.h"
#include "kudu/util/process_memory.h"
#include "kudu/util/slice.h"
#include "kudu/util/string_case.h"
DEFINE_int64(block_cache_capacity_mb, 512, "block cache capacity in MB");
TAG_FLAG(block_cache_capacity_mb, stable);
// Yes, it's strange: the default value is 'true' but that's intentional.
// The idea is to avoid the corresponding group flag validator striking
// while running anything but master and tserver. As for the master and tserver,
// those have the default value for this flag set to 'false'.
DEFINE_bool(force_block_cache_capacity, true,
"Force Kudu to accept the block cache size, even if it is unsafe.");
TAG_FLAG(force_block_cache_capacity, unsafe);
TAG_FLAG(force_block_cache_capacity, hidden);
DEFINE_string(block_cache_type, "DRAM",
"Which type of block cache to use for caching data. "
"Valid choices are 'DRAM' or 'NVM'. DRAM, the default, "
"caches data in regular memory. 'NVM' caches data "
"in a memory-mapped file using the NVML library.");
TAG_FLAG(block_cache_type, experimental);
using strings::Substitute;
template <class T> class scoped_refptr;
namespace kudu {
class MetricEntity;
namespace cfile {
namespace {
Cache* CreateCache(int64_t capacity) {
CacheType t = BlockCache::GetConfiguredCacheTypeOrDie();
return NewLRUCache(t, capacity, "block_cache");
}
// Validates the block cache capacity won't permit the cache to grow large enough
// to cause pernicious flushing behavior. See KUDU-2318.
bool ValidateBlockCacheCapacity() {
if (FLAGS_force_block_cache_capacity) {
return true;
}
int64_t capacity = FLAGS_block_cache_capacity_mb * 1024 * 1024;
int64_t mpt = process_memory::MemoryPressureThreshold();
if (capacity > mpt) {
LOG(ERROR) << Substitute("Block cache capacity exceeds the memory pressure "
"threshold ($0 bytes vs. $1 bytes). This will "
"cause instability and harmful flushing behavior. "
"Lower --block_cache_capacity_mb or raise "
"--memory_limit_hard_bytes.",
capacity, mpt);
return false;
}
if (capacity > mpt / 2) {
LOG(WARNING) << Substitute("Block cache capacity exceeds 50% of the memory "
"pressure threshold ($0 bytes vs. 50% of $1 bytes). "
"This may cause performance problems. Consider "
"lowering --block_cache_capacity_mb or raising "
"--memory_limit_hard_bytes.",
capacity, mpt);
}
return true;
}
} // anonymous namespace
GROUP_FLAG_VALIDATOR(block_cache_capacity_mb, ValidateBlockCacheCapacity);
CacheType BlockCache::GetConfiguredCacheTypeOrDie() {
ToUpperCase(FLAGS_block_cache_type, &FLAGS_block_cache_type);
if (FLAGS_block_cache_type == "NVM") {
return NVM_CACHE;
}
if (FLAGS_block_cache_type == "DRAM") {
return DRAM_CACHE;
}
LOG(FATAL) << "Unknown block cache type: '" << FLAGS_block_cache_type
<< "' (expected 'DRAM' or 'NVM')";
__builtin_unreachable();
}
BlockCache::BlockCache()
: BlockCache(FLAGS_block_cache_capacity_mb * 1024 * 1024) {
}
BlockCache::BlockCache(size_t capacity)
: cache_(CreateCache(capacity)) {
}
BlockCache::PendingEntry BlockCache::Allocate(const CacheKey& key, size_t block_size) {
Slice key_slice(reinterpret_cast<const uint8_t*>(&key), sizeof(key));
return PendingEntry(cache_.get(), cache_->Allocate(key_slice, block_size));
}
bool BlockCache::Lookup(const CacheKey& key, Cache::CacheBehavior behavior,
BlockCacheHandle *handle) {
Cache::Handle *h = cache_->Lookup(Slice(reinterpret_cast<const uint8_t*>(&key),
sizeof(key)), behavior);
if (h != nullptr) {
handle->SetHandle(cache_.get(), h);
}
return h != nullptr;
}
void BlockCache::Insert(BlockCache::PendingEntry* entry, BlockCacheHandle* inserted) {
Cache::Handle *h = cache_->Insert(entry->handle_, /* eviction_callback= */ nullptr);
entry->handle_ = nullptr;
inserted->SetHandle(cache_.get(), h);
}
void BlockCache::StartInstrumentation(const scoped_refptr<MetricEntity>& metric_entity) {
cache_->SetMetrics(metric_entity);
}
} // namespace cfile
} // namespace kudu
|
//
// Bachelor of Software Engineering
// Media Design School
// Auckland
// New Zealand
//
// (c) 2018 Media Design School.
//
// File Name : spaceship.cpp
// Description : controls bonus spaceship
// Author : Henry Oliver
// Mail : henry.oliver@mediadesign.school.nz
//
// Library Includes
// Local Includes
#include "resource.h"
#include "utils.h"
#include "spaceship.h"
// This Include
// Static Variables
// Static Function Prototypes
// Implementation
CSpaceShip::CSpaceShip()
: m_bHit(false)
{
}
CSpaceShip::~CSpaceShip()
{
}
bool
CSpaceShip::Initialise(float m_x)
{
VALIDATE(CEntity::Initialise(IDB_BITMAP9, IDB_BITMAP10));
m_fX = m_x;
m_fY = 15;
return (true);
}
void
CSpaceShip::Draw()
{
if (!m_bHit)
{
CEntity::Draw();
}
}
void
CSpaceShip::Process(float _fDeltaTick)
{
if (m_fX < 600) {
m_fX += 0.3f;
}
if (!m_bHit)
{
CEntity::Process(_fDeltaTick);
}
}
void
CSpaceShip::SetHit(bool _b)
{
m_bHit = _b;
}
bool
CSpaceShip::IsHit() const
{
return (m_bHit);
}
void CSpaceShip::SpawnMe(int m_x) {
m_fX = (0.0f - m_x);
m_fY = 15;
m_bHit = false;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcorn-config.h"
#endif
#include "net.h"
#include "addrman.h"
#include "chainparams.h"
#include "clientversion.h"
#include "miner.h"
#include "obfuscation.h"
#include "primitives/transaction.h"
#include "scheduler.h"
#include "guiinterface.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
#ifndef PROTECTION_LEVEL_UNRESTRICTED
#define PROTECTION_LEVEL_UNRESTRICTED 10
#endif
#ifndef IPV6_PROTECTION_LEVEL
#define IPV6_PROTECTION_LEVEL 23
#endif
#endif
namespace
{
const int MAX_OUTBOUND_CONNECTIONS = 16;
struct ListenSocket {
SOCKET socket;
bool whitelisted;
ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
};
}
//
// Global state variables
//
bool fDiscover = true;
bool fListen = true;
uint64_t nLocalServices = NODE_NETWORK;
CCriticalSection cs_mapLocalHost;
std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64_t nLocalHostNonce = 0;
static std::vector<ListenSocket> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
bool fAddressesInitialized = false;
std::string strSubVersion;
std::vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
std::map<CInv, CDataStream> mapRelay;
std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
static std::deque<std::string> vOneShots;
CCriticalSection cs_vOneShots;
std::set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
std::vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
NodeId nLastNodeId = 0;
CCriticalSection cs_nLastNodeId;
static CSemaphore* semOutbound = NULL;
boost::condition_variable messageHandlerCondition;
// Signals for message handling
static CNodeSignals g_signals;
CNodeSignals& GetNodeSignals() { return g_signals; }
void AddOneShot(std::string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr* paddrPeer)
{
if (!fListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) {
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
// Otherwise, return the unroutable 0.0.0.0 but filled in with
// the normal parameters, since the IP may be changed to a useful
// one by discovery.
CAddress GetLocalAddress(const CNetAddr* paddrPeer)
{
CAddress ret(CService("0.0.0.0", GetListenPort()), 0);
CService addr;
if (GetLocal(addr, paddrPeer)) {
ret = CAddress(addr);
}
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
return ret;
}
bool RecvLine(SOCKET hSocket, std::string& strLine)
{
strLine = "";
while (true) {
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0) {
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
} else if (nBytes <= 0) {
boost::this_thread::interruption_point();
if (nBytes < 0) {
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) {
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0) {
// socket closed
LogPrint("net", "socket closed\n");
return false;
} else {
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
}
}
int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == LOCAL_NONE)
return 0;
return mapLocalHost[addr].nScore;
}
// Is our peer's addrLocal potentially useful as an external IP source?
bool IsPeerAddrLocalGood(CNode* pnode)
{
return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
!IsLimited(pnode->addrLocal.GetNetwork());
}
// pushes our own address to a peer
void AdvertiseLocal(CNode* pnode)
{
if (fListen && pnode->fSuccessfullyConnected) {
CAddress addrLocal = GetLocalAddress(&pnode->addr);
// If discovery is enabled, sometimes give our peer the address it
// tells us that it sees us as in case it has a better idea of our
// address than we do.
if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) {
addrLocal.SetIP(pnode->addrLocal);
}
if (addrLocal.IsRoutable()) {
LogPrintf("%s: advertising address %s\n", __func__, addrLocal.ToString());
FastRandomContext insecure_rand;
pnode->PushAddress(addrLocal, insecure_rand);
}
}
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo& info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
}
return true;
}
bool AddLocal(const CNetAddr& addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
bool RemoveLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
LogPrintf("RemoveLocal(%s)\n", addr.ToString());
mapLocalHost.erase(addr);
return true;
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr& addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given network is one we can probably connect to */
bool IsReachable(enum Network net)
{
LOCK(cs_mapLocalHost);
return !vfLimited[net];
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
enum Network net = addr.GetNetwork();
return IsReachable(net);
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(const CSubNet& subNet)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (subNet.Match((CNetAddr)pnode->addr))
return (pnode);
return NULL;
}
CNode* FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
//if using regtest, just check the IP
if ((CNetAddr)pnode->addr == (CNetAddr)addr)
return (pnode);
} else {
if (pnode->addr == addr)
return (pnode);
}
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster)
{
if (pszDest == NULL) {
// we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections()
// so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus()
if (IsLocal(addrConnect) && !obfuScationMaster)
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode) {
pnode->fObfuScationMaster = obfuScationMaster;
pnode->AddRef();
return pnode;
}
}
/// debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
// Connect
SOCKET hSocket = INVALID_SOCKET;;
bool proxyConnectionFailed = false;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) {
if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket);
return NULL;
}
addrman.Attempt(addrConnect);
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
if (obfuScationMaster) pnode->fObfuScationMaster = true;
return pnode;
} else if (!proxyConnectionFailed) {
// If connecting to the node failed, and failure is not caused by a problem connecting to
// the proxy, mark this as an attempt.
addrman.Attempt(addrConnect);
}
return NULL;
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET) {
LogPrint("net", "disconnecting peer=%d\n", id);
CloseSocket(hSocket);
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
bool CNode::DisconnectOldProtocol(int nVersionRequired, std::string strLastCommand)
{
fDisconnect = false;
if (nVersion < nVersionRequired) {
LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion);
PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol()));
fDisconnect = true;
}
return fDisconnect;
}
void CNode::PushVersion()
{
int nBestHeight = g_signals.GetHeight().get_value_or(0);
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0)));
CAddress addrMe = GetLocalAddress(&addr);
GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
if (fLogIPs)
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
else
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, strSubVersion, nBestHeight, true);
}
banmap_t CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
bool CNode::setBannedIsDirty;
void CNode::ClearBanned()
{
{
LOCK(cs_setBanned);
setBanned.clear();
setBannedIsDirty = true;
}
DumpBanlist(); // store banlist to Disk
uiInterface.BannedListChanged();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++)
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil)
fResult = true;
}
}
return fResult;
}
bool CNode::IsBanned(CSubNet subnet)
{
bool fResult = false;
{
LOCK(cs_setBanned);
banmap_t::iterator i = setBanned.find(subnet);
if (i != setBanned.end()) {
CBanEntry banEntry = (*i).second;
if (GetTime() < banEntry.nBanUntil)
fResult = true;
}
}
return fResult;
}
void CNode::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
{
CSubNet subNet(addr);
Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
}
void CNode::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
{
CBanEntry banEntry(GetTime());
banEntry.banReason = banReason;
if (bantimeoffset <= 0)
{
bantimeoffset = GetArg("-bantime", 60*60*24); // Default 24-hour ban
sinceUnixEpoch = false;
}
banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
{
LOCK(cs_setBanned);
if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
setBanned[subNet] = banEntry;
setBannedIsDirty = true;
}
else
return;
}
uiInterface.BannedListChanged();
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (subNet.Match((CNetAddr)pnode->addr))
pnode->fDisconnect = true;
}
}
if(banReason == BanReasonManuallyAdded)
DumpBanlist(); //store banlist to disk immediately if user requested ban
}
bool CNode::Unban(const CNetAddr &addr)
{
CSubNet subNet(addr);
return Unban(subNet);
}
bool CNode::Unban(const CSubNet &subNet)
{
{
LOCK(cs_setBanned);
if (!setBanned.erase(subNet))
return false;
setBannedIsDirty = true;
}
uiInterface.BannedListChanged();
DumpBanlist(); //store banlist to disk immediately
return true;
}
void CNode::GetBanned(banmap_t &banMap)
{
LOCK(cs_setBanned);
banMap = setBanned; //create a thread safe copy
}
void CNode::SetBanned(const banmap_t &banMap)
{
LOCK(cs_setBanned);
setBanned = banMap;
setBannedIsDirty = true;
}
void CNode::SweepBanned()
{
int64_t now = GetTime();
bool notifyUI = false;
{
LOCK(cs_setBanned);
banmap_t::iterator it = setBanned.begin();
while(it != setBanned.end())
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(now > banEntry.nBanUntil)
{
setBanned.erase(it++);
setBannedIsDirty = true;
notifyUI = true;
LogPrint("net", "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
}
else
++it;
}
}
// update UI
if(notifyUI) {
uiInterface.BannedListChanged();
}
}
bool CNode::BannedSetIsDirty()
{
LOCK(cs_setBanned);
return setBannedIsDirty;
}
void CNode::SetBannedSetDirty(bool dirty)
{
LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
setBannedIsDirty = dirty;
}
std::vector<CSubNet> CNode::vWhitelistedRange;
CCriticalSection CNode::cs_vWhitelistedRange;
bool CNode::IsWhitelistedRange(const CNetAddr& addr)
{
LOCK(cs_vWhitelistedRange);
for (const CSubNet& subnet : vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
return false;
}
void CNode::AddWhitelistedRange(const CSubNet& subnet)
{
LOCK(cs_vWhitelistedRange);
vWhitelistedRange.push_back(subnet);
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats& stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(nTimeOffset);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
X(fWhitelisted);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (BitCorn users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId());
return false;
}
pch += handled;
nBytes -= handled;
if (msg.complete()) {
msg.nTime = GetTimeMicros();
messageHandlerCondition.notify_one();
}
}
return true;
}
int CNetMessage::readHeader(const char* pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
} catch (const std::exception&) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char* pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode* pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData& data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
pnode->RecordBytesSent(nBytes);
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static std::list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (true) {
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
std::vector<CNode*> vNodesCopy = vNodes;
for (CNode* pnode : vNodesCopy) {
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) {
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
for (CNode* pnode : vNodesDisconnectedCopy) {
// wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete) {
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
size_t vNodesSize;
{
LOCK(cs_vNodes);
vNodesSize = vNodes.size();
}
if(vNodesSize != nPrevNodeCount) {
nPrevNodeCount = vNodesSize;
uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
for (const ListenSocket& hListenSocket : vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = std::max(hSocketMax, hListenSocket.socket);
have_fds = true;
}
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = std::max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR) {
if (have_fds) {
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec / 1000);
}
//
// Accept new connections
//
for (const ListenSocket& hListenSocket : vhListenSocket) {
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) {
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
LogPrintf("Warning: Unknown socket family\n");
bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET) {
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
} else if (!IsSelectableSocket(hSocket)) {
LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
CloseSocket(hSocket);
} else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) {
LogPrint("net", "connection from %s dropped (full)\n", addr.ToString());
CloseSocket(hSocket);
} else if (CNode::IsBanned(addr) && !whitelisted) {
LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
CloseSocket(hSocket);
} else {
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
pnode->fWhitelisted = whitelisted;
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
}
//
// Service each socket
//
std::vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
for (CNode* pnode : vNodesCopy)
pnode->AddRef();
}
for (CNode* pnode : vNodesCopy) {
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0) {
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
pnode->RecordBytesRecv(nBytes);
} else if (nBytes == 0) {
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "socket closed\n");
pnode->CloseSocketDisconnect();
} else if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend)) {
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
int64_t nTime = GetTime();
if (nTime - pnode->nTimeConnected > 60) {
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) {
LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
} else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) {
LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodesCopy)
pnode->Release();
}
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char* multicastif = 0;
const char* minissdpdpath = 0;
struct UPNPDev* devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
/* miniupnpc 1.9.20150730 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else {
if (externalIPAddress[0]) {
LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
} else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
std::string strDesc = "BITCORN " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");
;
MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes
}
} catch (const boost::thread_interrupted&) {
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist);
devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP) {
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
} else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);
LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const std::vector<CDNSSeedData>& vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
for (const CDNSSeedData& seed : vSeeds) {
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
std::vector<CNetAddr> vIPs;
std::vector<CAddress> vAdd;
if (LookupHost(seed.host.c_str(), vIPs)) {
for (CNetAddr& ip : vIPs) {
int nOneDay = 24 * 3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void DumpData()
{
DumpAddresses();
DumpBanlist();
}
void static ProcessOneShot()
{
std::string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
for (int64_t nLoop = 0;; nLoop++) {
ProcessOneShot();
for (std::string strAddr : mapMultiArgs["-connect"]) {
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++) {
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true) {
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
std::set<std::vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true) {
CAddrInfo addr = addrman.Select();
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while (true) {
std::list<std::string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
for (std::string& strAddNode : vAddedNodes)
lAddresses.push_back(strAddNode);
}
for (std::string& strAddNode : lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++) {
std::list<std::string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
for (std::string& strAddNode : vAddedNodes)
lAddresses.push_back(strAddNode);
}
std::list<std::vector<CService> > lservAddressesToAdd(0);
for (std::string& strAddNode : lAddresses) {
std::vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) {
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
for (CService& serv : vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
for (std::list<std::vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
for (CService& addrNode : *(it))
if (pnode->addr == addrNode) {
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
for (std::vector<CService>& vserv : lservAddressesToAdd) {
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!pszDest) {
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort()))
return false;
} else if (FindNode(pszDest))
return false;
CNode* pnode = ConnectNode(addrConnect, pszDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler()
{
boost::mutex condition_mutex;
boost::unique_lock<boost::mutex> lock(condition_mutex);
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true) {
std::vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
for (CNode* pnode : vNodesCopy) {
pnode->AddRef();
}
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
for (CNode* pnode : vNodesCopy) {
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
if (!g_signals.ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize()) {
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) {
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodesCopy)
pnode->Release();
}
if (fSleep)
messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
}
}
bool BindListenPort(const CService& addrBind, std::string& strError, bool fWhitelisted)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET) {
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
if (!IsSelectableSocket(hListenSocket)) {
strError = "Error: Couldn't create a listenable socket for incoming connections";
LogPrintf("%s\n", strError);
return false;
}
#ifndef WIN32
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows!
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
// Set to non-blocking, incoming connections will also inherit this
if (!SetSocketNonBlocking(hListenSocket, true)) {
strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. BITCORN Core is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[256] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
std::vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr)) {
for (const CNetAddr& addr : vaddr) {
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0) {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
}
void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
{
uiInterface.InitMessage(_("Loading addresses..."));
// Load addresses for peers.dat
int64_t nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
LogPrintf("Invalid or missing peers.dat; recreating\n");
}
//try to read stored banlist
CBanDB bandb;
banmap_t banmap;
if (!bandb.Read(banmap))
LogPrintf("Invalid or missing banlist.dat; recreating\n");
CNode::SetBanned(banmap); //thread save setter
CNode::SetBannedSetDirty(false); //no need to write down just read or nonexistent data
CNode::SweepBanned(); //sweap out unused entries
// Initialize random numbers. Even when rand() is only usable for trivial use-cases most nodes should have a different
// seed after all the file-IO done at this point. Should be good enough even when nodes are started via scripts.
srand(time(NULL));
LogPrintf("Loaded %i addresses from peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
fAddressesInitialized = true;
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover(threadGroup);
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
scheduler.scheduleEvery(&DumpData, DUMP_ADDRESSES_INTERVAL);
}
bool StopNode()
{
LogPrintf("StopNode()\n");
MapPort(false);
if (semOutbound)
for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
if (fAddressesInitialized) {
DumpData();
fAddressesInitialized = false;
}
return true;
}
class CNetCleanup
{
public:
CNetCleanup() {}
~CNetCleanup()
{
// Close sockets
for (CNode* pnode : vNodes)
if (pnode->hSocket != INVALID_SOCKET)
CloseSocket(pnode->hSocket);
for (ListenSocket& hListenSocket : vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
for (CNode* pnode : vNodes)
delete pnode;
for (CNode* pnode : vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
} instance_of_cnetcleanup;
void CExplicitNetCleanup::callCleanup()
{
// Explicit call to destructor of CNetCleanup because it's not implicitly called
// when the wallet is restarted from within the wallet itself.
CNetCleanup* tmp = new CNetCleanup();
delete tmp; // Stroustrup's gonna kill me for that
}
void RelayTransaction(const CTransaction& tx)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, ss);
}
void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
{
CInv inv(MSG_TX, tx.GetHash());
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) {
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter) {
if (pnode->pfilter->IsRelevantAndUpdate(tx))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll)
{
CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
//broadcast the new lock
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (!relayToAll && !pnode->fRelayTxes)
continue;
pnode->PushMessage("ix", tx);
}
}
void RelayInv(CInv& inv)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes){
if((pnode->nServices == NODE_BLOOM_WITHOUT_MN || pnode->nServices == NODE_BLOOM_LIGHT_ZC) && inv.IsMasterNodeType())continue;
if (pnode->nVersion >= ActiveProtocol())
pnode->PushInventory(inv);
}
}
void CNode::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int nChance)
{
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
switch (GetRand(3)) {
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (unsigned char)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin() + pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin() + pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
//
// CAddrDB
//
CAddrDB::CAddrDB()
{
pathAddr = GetDataDir() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("peers.dat.%04x", randv);
// serialize addresses, checksum data up to that point, then append csum
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
ssPeers << FLATDATA(Params().MessageStart());
ssPeers << addr;
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
ssPeers << hash;
// open output file, and associate with CAutoFile
boost::filesystem::path pathAddr = GetDataDir() / "peers.dat";
FILE* file = fopen(pathAddr.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// Write and commit header, data
try {
fileout << ssPeers;
} catch (const std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
return true;
}
bool CAddrDB::Read(CAddrMan& addr)
{
// open input file, and associate with CAutoFile
FILE* file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// use file size to size memory buffer
uint64_t fileSize = boost::filesystem::file_size(pathAddr);
uint64_t dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (fileSize >= sizeof(uint256))
dataSize = fileSize - sizeof(uint256);
std::vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (const std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("%s : Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssPeers >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s : Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssPeers >> addr;
} catch (const std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); }
unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); }
CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000)
{
nServices = 0;
hSocket = hSocketIn;
nRecvVersion = INIT_PROTO_VERSION;
nLastSend = 0;
nLastRecv = 0;
nSendBytes = 0;
nRecvBytes = 0;
nTimeConnected = GetTime();
nTimeOffset = 0;
addr = addrIn;
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
nVersion = 0;
strSubVer = "";
fWhitelisted = false;
fOneShot = false;
fClient = false; // set by version message
fInbound = fInboundIn;
fNetworkNode = false;
fSuccessfullyConnected = false;
fDisconnect = false;
nRefCount = 0;
nSendSize = 0;
nSendOffset = 0;
hashContinue = 0;
nStartingHeight = -1;
fGetAddr = false;
fRelayTxes = false;
setInventoryKnown.max_size(SendBufferSize() / 1000);
pfilter = new CBloomFilter();
nPingNonceSent = 0;
nPingUsecStart = 0;
nPingUsecTime = 0;
fPingQueued = false;
fObfuScationMaster = false;
{
LOCK(cs_nLastNodeId);
id = nLastNodeId++;
}
if (fLogIPs)
LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
else
LogPrint("net", "Added connection peer=%d\n", id);
// Be shy and don't send version until we hear
if (hSocket != INVALID_SOCKET && !fInbound)
PushVersion();
GetNodeSignals().InitializeNode(GetId(), this);
}
CNode::~CNode()
{
CloseSocket(hSocket);
if (pfilter)
delete pfilter;
GetNodeSignals().FinalizeNode(GetId());
}
void CNode::AskFor(const CInv& inv)
{
if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
return;
// We're using mapAskFor as a priority queue,
// the key is the earliest time the request can be sent
int64_t nRequestTime;
limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
if (it != mapAlreadyAskedFor.end())
nRequestTime = it->second;
else
nRequestTime = 0;
LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
static int64_t nLastTime;
++nLastTime;
nNow = std::max(nNow, nLastTime);
nLastTime = nNow;
// Each retry is 2 minutes after the last
nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
if (it != mapAlreadyAskedFor.end())
mapAlreadyAskedFor.update(it, nRequestTime);
else
mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
mapAskFor.insert(std::make_pair(nRequestTime, inv));
}
void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
{
ENTER_CRITICAL_SECTION(cs_vSend);
assert(ssSend.size() == 0);
ssSend << CMessageHeader(pszCommand, 0);
LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
}
void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
{
ssSend.clear();
LEAVE_CRITICAL_SECTION(cs_vSend);
LogPrint("net", "(aborted)\n");
}
void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
{
// The -*messagestest options are intentionally not documented in the help message,
// since they are only used during development to debug the networking code and are
// not intended for end-users.
if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) {
LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
AbortMessage();
return;
}
if (mapArgs.count("-fuzzmessagestest"))
Fuzz(GetArg("-fuzzmessagestest", 10));
if (ssSend.size() == 0) {
LEAVE_CRITICAL_SECTION(cs_vSend);
return;
}
// Set the size
unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
// Set the checksum
uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
ssSend.GetAndClear(*it);
nSendSize += (*it).size();
// If write queue empty, attempt "optimistic write"
if (it == vSendMsg.begin())
SocketSendData(this);
LEAVE_CRITICAL_SECTION(cs_vSend);
}
//
// CBanDB
//
CBanDB::CBanDB()
{
pathBanlist = GetDataDir() / "banlist.dat";
}
bool CBanDB::Write(const banmap_t& banSet)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("banlist.dat.%04x", randv);
// serialize banlist, checksum data up to that point, then append csum
CDataStream ssBanlist(SER_DISK, CLIENT_VERSION);
ssBanlist << FLATDATA(Params().MessageStart());
ssBanlist << banSet;
uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end());
ssBanlist << hash;
// open temp output file, and associate with CAutoFile
boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
FILE *file = fopen(pathTmp.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, pathTmp.string());
// Write and commit header, data
try {
fileout << ssBanlist;
}
catch (const std::exception& e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
// replace existing banlist.dat, if any, with new banlist.dat.XXXX
if (!RenameOver(pathTmp, pathBanlist))
return error("%s: Rename-into-place failed", __func__);
return true;
}
bool CBanDB::Read(banmap_t& banSet)
{
// open input file, and associate with CAutoFile
FILE *file = fopen(pathBanlist.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s: Failed to open file %s", __func__, pathBanlist.string());
// use file size to size memory buffer
uint64_t fileSize = boost::filesystem::file_size(pathBanlist);
uint64_t dataSize = 0;
// Don't try to resize to a negative number if file is small
if (fileSize >= sizeof(uint256))
dataSize = fileSize - sizeof(uint256);
std::vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end());
if (hashIn != hashTmp)
return error("%s: Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssBanlist >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssBanlist >> banSet;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
void DumpBanlist()
{
CNode::SweepBanned(); // clean unused entries (if bantime has expired)
if (!CNode::BannedSetIsDirty())
return;
int64_t nStart = GetTimeMillis();
CBanDB bandb;
banmap_t banmap;
CNode::GetBanned(banmap);
if (bandb.Write(banmap)) {
CNode::SetBannedSetDirty(false);
}
LogPrint("net", "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
banmap.size(), GetTimeMillis() - nStart);
}
|
// JSON condenser example
// This example parses JSON from stdin with validation,
// and re-output the JSON content to stdout with all string capitalized, and without whitespace.
#include "rapidjson/reader.h"
#include "rapidjson/writer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/error/en.h"
#include <vector>
#include <cctype>
using namespace rapidjson;
template<typename OutputHandler>
struct CapitalizeFilter {
CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
bool Null() { return out_.Null(); }
bool Bool(bool b) { return out_.Bool(b); }
bool Int(int i) { return out_.Int(i); }
bool Uint(unsigned u) { return out_.Uint(u); }
bool Int64(int64_t i) { return out_.Int64(i); }
bool Uint64(uint64_t u) { return out_.Uint64(u); }
bool Double(double d) { return out_.Double(d); }
bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); }
bool String(const char* str, SizeType length, bool) {
buffer_.clear();
for (SizeType i = 0; i < length; i++)
buffer_.push_back(static_cast<char>(std::toupper(str[i])));
return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
}
bool StartObject() { return out_.StartObject(); }
bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
bool StartArray() { return out_.StartArray(); }
bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
OutputHandler& out_;
std::vector<char> buffer_;
private:
CapitalizeFilter(const CapitalizeFilter&);
CapitalizeFilter& operator=(const CapitalizeFilter&);
};
#if defined(BUILD_MONOLITHIC)
#define main(c, a) Rjson_example_capitalize_main(c, a)
#endif
int main(int argc, const char** argv)
{
// Prepare JSON reader and input stream.
Reader reader;
char readBuffer[65536];
FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
// Prepare JSON writer and output stream.
char writeBuffer[65536];
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
// JSON reader parse from the input stream and let writer generate the output.
CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
if (!reader.Parse(is, filter)) {
fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
return 0;
}
|
/*!
* Copyright 2018-2021 by Contributors
*/
#include <gtest/gtest.h>
#include "../../helpers.h"
#include "../../../../src/tree/hist/histogram.h"
#include "../../../../src/tree/updater_quantile_hist.h"
namespace xgboost {
namespace tree {
namespace {
void InitRowPartitionForTest(RowSetCollection *row_set, size_t n_samples,
size_t base_rowid = 0) {
auto &row_indices = *row_set->Data();
row_indices.resize(n_samples);
std::iota(row_indices.begin(), row_indices.end(), base_rowid);
row_set->Init();
}
} // anonymous namespace
template <typename GradientSumT>
void TestAddHistRows(bool is_distributed) {
std::vector<CPUExpandEntry> nodes_for_explicit_hist_build_;
std::vector<CPUExpandEntry> nodes_for_subtraction_trick_;
int starting_index = std::numeric_limits<int>::max();
int sync_count = 0;
size_t constexpr kNRows = 8, kNCols = 16;
int32_t constexpr kMaxBins = 4;
auto p_fmat =
RandomDataGenerator(kNRows, kNCols, 0.8).Seed(3).GenerateDMatrix();
auto const &gmat = *(p_fmat
->GetBatches<GHistIndexMatrix>(
BatchParam{GenericParameter::kCpuId, kMaxBins})
.begin());
RegTree tree;
tree.ExpandNode(0, 0, 0, false, 0, 0, 0, 0, 0, 0, 0);
tree.ExpandNode(tree[0].LeftChild(), 0, 0, false, 0, 0, 0, 0, 0, 0, 0);
tree.ExpandNode(tree[0].RightChild(), 0, 0, false, 0, 0, 0, 0, 0, 0, 0);
nodes_for_explicit_hist_build_.emplace_back(3, tree.GetDepth(3), 0.0f);
nodes_for_explicit_hist_build_.emplace_back(4, tree.GetDepth(4), 0.0f);
nodes_for_subtraction_trick_.emplace_back(5, tree.GetDepth(5), 0.0f);
nodes_for_subtraction_trick_.emplace_back(6, tree.GetDepth(6), 0.0f);
HistogramBuilder<GradientSumT, CPUExpandEntry> histogram_builder;
histogram_builder.Reset(gmat.cut.TotalBins(),
{GenericParameter::kCpuId, kMaxBins},
omp_get_max_threads(), 1, is_distributed);
histogram_builder.AddHistRows(&starting_index, &sync_count,
nodes_for_explicit_hist_build_,
nodes_for_subtraction_trick_, &tree);
ASSERT_EQ(sync_count, 2);
ASSERT_EQ(starting_index, 3);
for (const CPUExpandEntry &node : nodes_for_explicit_hist_build_) {
ASSERT_EQ(histogram_builder.Histogram().RowExists(node.nid), true);
}
for (const CPUExpandEntry &node : nodes_for_subtraction_trick_) {
ASSERT_EQ(histogram_builder.Histogram().RowExists(node.nid), true);
}
}
TEST(CPUHistogram, AddRows) {
TestAddHistRows<float>(true);
TestAddHistRows<double>(true);
TestAddHistRows<float>(false);
TestAddHistRows<double>(false);
}
template <typename GradientSumT>
void TestSyncHist(bool is_distributed) {
size_t constexpr kNRows = 8, kNCols = 16;
int32_t constexpr kMaxBins = 4;
std::vector<CPUExpandEntry> nodes_for_explicit_hist_build_;
std::vector<CPUExpandEntry> nodes_for_subtraction_trick_;
int starting_index = std::numeric_limits<int>::max();
int sync_count = 0;
RegTree tree;
auto p_fmat =
RandomDataGenerator(kNRows, kNCols, 0.8).Seed(3).GenerateDMatrix();
auto const &gmat = *(p_fmat
->GetBatches<GHistIndexMatrix>(
BatchParam{GenericParameter::kCpuId, kMaxBins})
.begin());
HistogramBuilder<GradientSumT, CPUExpandEntry> histogram;
uint32_t total_bins = gmat.cut.Ptrs().back();
histogram.Reset(total_bins, {GenericParameter::kCpuId, kMaxBins},
omp_get_max_threads(), 1, is_distributed);
RowSetCollection row_set_collection_;
{
row_set_collection_.Clear();
std::vector<size_t> &row_indices = *row_set_collection_.Data();
row_indices.resize(kNRows);
std::iota(row_indices.begin(), row_indices.end(), 0);
row_set_collection_.Init();
}
// level 0
nodes_for_explicit_hist_build_.emplace_back(0, tree.GetDepth(0), 0.0f);
histogram.AddHistRows(&starting_index, &sync_count,
nodes_for_explicit_hist_build_,
nodes_for_subtraction_trick_, &tree);
tree.ExpandNode(0, 0, 0, false, 0, 0, 0, 0, 0, 0, 0);
nodes_for_explicit_hist_build_.clear();
nodes_for_subtraction_trick_.clear();
// level 1
nodes_for_explicit_hist_build_.emplace_back(tree[0].LeftChild(),
tree.GetDepth(1), 0.0f);
nodes_for_subtraction_trick_.emplace_back(tree[0].RightChild(),
tree.GetDepth(2), 0.0f);
histogram.AddHistRows(&starting_index, &sync_count,
nodes_for_explicit_hist_build_,
nodes_for_subtraction_trick_, &tree);
tree.ExpandNode(tree[0].LeftChild(), 0, 0, false, 0, 0, 0, 0, 0, 0, 0);
tree.ExpandNode(tree[0].RightChild(), 0, 0, false, 0, 0, 0, 0, 0, 0, 0);
nodes_for_explicit_hist_build_.clear();
nodes_for_subtraction_trick_.clear();
// level 2
nodes_for_explicit_hist_build_.emplace_back(3, tree.GetDepth(3), 0.0f);
nodes_for_subtraction_trick_.emplace_back(4, tree.GetDepth(4), 0.0f);
nodes_for_explicit_hist_build_.emplace_back(5, tree.GetDepth(5), 0.0f);
nodes_for_subtraction_trick_.emplace_back(6, tree.GetDepth(6), 0.0f);
histogram.AddHistRows(&starting_index, &sync_count,
nodes_for_explicit_hist_build_,
nodes_for_subtraction_trick_, &tree);
const size_t n_nodes = nodes_for_explicit_hist_build_.size();
ASSERT_EQ(n_nodes, 2ul);
row_set_collection_.AddSplit(0, tree[0].LeftChild(), tree[0].RightChild(), 4,
4);
row_set_collection_.AddSplit(1, tree[1].LeftChild(), tree[1].RightChild(), 2,
2);
row_set_collection_.AddSplit(2, tree[2].LeftChild(), tree[2].RightChild(), 2,
2);
common::BlockedSpace2d space(
n_nodes,
[&](size_t node) {
const int32_t nid = nodes_for_explicit_hist_build_[node].nid;
return row_set_collection_[nid].Size();
},
256);
std::vector<common::GHistRow<GradientSumT>> target_hists(n_nodes);
for (size_t i = 0; i < nodes_for_explicit_hist_build_.size(); ++i) {
const int32_t nid = nodes_for_explicit_hist_build_[i].nid;
target_hists[i] = histogram.Histogram()[nid];
}
// set values to specific nodes hist
std::vector<size_t> n_ids = {1, 2};
for (size_t i : n_ids) {
auto this_hist = histogram.Histogram()[i];
GradientSumT *p_hist = reinterpret_cast<GradientSumT *>(this_hist.data());
for (size_t bin_id = 0; bin_id < 2 * total_bins; ++bin_id) {
p_hist[bin_id] = 2 * bin_id;
}
}
n_ids[0] = 3;
n_ids[1] = 5;
for (size_t i : n_ids) {
auto this_hist = histogram.Histogram()[i];
GradientSumT *p_hist = reinterpret_cast<GradientSumT *>(this_hist.data());
for (size_t bin_id = 0; bin_id < 2 * total_bins; ++bin_id) {
p_hist[bin_id] = bin_id;
}
}
histogram.Buffer().Reset(1, n_nodes, space, target_hists);
// sync hist
if (is_distributed) {
histogram.SyncHistogramDistributed(&tree, nodes_for_explicit_hist_build_,
nodes_for_subtraction_trick_,
starting_index, sync_count);
} else {
histogram.SyncHistogramLocal(&tree, nodes_for_explicit_hist_build_,
nodes_for_subtraction_trick_, starting_index,
sync_count);
}
using GHistRowT = common::GHistRow<GradientSumT>;
auto check_hist = [](const GHistRowT parent, const GHistRowT left,
const GHistRowT right, size_t begin, size_t end) {
const GradientSumT *p_parent =
reinterpret_cast<const GradientSumT *>(parent.data());
const GradientSumT *p_left =
reinterpret_cast<const GradientSumT *>(left.data());
const GradientSumT *p_right =
reinterpret_cast<const GradientSumT *>(right.data());
for (size_t i = 2 * begin; i < 2 * end; ++i) {
ASSERT_EQ(p_parent[i], p_left[i] + p_right[i]);
}
};
size_t node_id = 0;
for (const CPUExpandEntry &node : nodes_for_explicit_hist_build_) {
auto this_hist = histogram.Histogram()[node.nid];
const size_t parent_id = tree[node.nid].Parent();
const size_t subtraction_node_id =
nodes_for_subtraction_trick_[node_id].nid;
auto parent_hist = histogram.Histogram()[parent_id];
auto sibling_hist = histogram.Histogram()[subtraction_node_id];
check_hist(parent_hist, this_hist, sibling_hist, 0, total_bins);
++node_id;
}
node_id = 0;
for (const CPUExpandEntry &node : nodes_for_subtraction_trick_) {
auto this_hist = histogram.Histogram()[node.nid];
const size_t parent_id = tree[node.nid].Parent();
const size_t subtraction_node_id =
nodes_for_explicit_hist_build_[node_id].nid;
auto parent_hist = histogram.Histogram()[parent_id];
auto sibling_hist = histogram.Histogram()[subtraction_node_id];
check_hist(parent_hist, this_hist, sibling_hist, 0, total_bins);
++node_id;
}
}
TEST(CPUHistogram, SyncHist) {
TestSyncHist<float>(true);
TestSyncHist<double>(true);
TestSyncHist<float>(false);
TestSyncHist<double>(false);
}
template <typename GradientSumT>
void TestBuildHistogram(bool is_distributed) {
size_t constexpr kNRows = 8, kNCols = 16;
int32_t constexpr kMaxBins = 4;
auto p_fmat =
RandomDataGenerator(kNRows, kNCols, 0.8).Seed(3).GenerateDMatrix();
auto const &gmat = *(p_fmat
->GetBatches<GHistIndexMatrix>(
BatchParam{GenericParameter::kCpuId, kMaxBins})
.begin());
uint32_t total_bins = gmat.cut.Ptrs().back();
static double constexpr kEps = 1e-6;
std::vector<GradientPair> gpair = {
{0.23f, 0.24f}, {0.24f, 0.25f}, {0.26f, 0.27f}, {0.27f, 0.28f},
{0.27f, 0.29f}, {0.37f, 0.39f}, {0.47f, 0.49f}, {0.57f, 0.59f}};
bst_node_t nid = 0;
HistogramBuilder<GradientSumT, CPUExpandEntry> histogram;
histogram.Reset(total_bins, {GenericParameter::kCpuId, kMaxBins},
omp_get_max_threads(), 1, is_distributed);
RegTree tree;
RowSetCollection row_set_collection;
row_set_collection.Clear();
std::vector<size_t> &row_indices = *row_set_collection.Data();
row_indices.resize(kNRows);
std::iota(row_indices.begin(), row_indices.end(), 0);
row_set_collection.Init();
CPUExpandEntry node(RegTree::kRoot, tree.GetDepth(0), 0.0f);
std::vector<CPUExpandEntry> nodes_for_explicit_hist_build;
nodes_for_explicit_hist_build.push_back(node);
for (auto const &gidx : p_fmat->GetBatches<GHistIndexMatrix>(
{GenericParameter::kCpuId, kMaxBins})) {
histogram.BuildHist(0, gidx, &tree, row_set_collection,
nodes_for_explicit_hist_build, {}, gpair);
}
// Check if number of histogram bins is correct
ASSERT_EQ(histogram.Histogram()[nid].size(), gmat.cut.Ptrs().back());
std::vector<GradientPairPrecise> histogram_expected(histogram.Histogram()[nid].size());
// Compute the correct histogram (histogram_expected)
CHECK_EQ(gpair.size(), kNRows);
for (size_t rid = 0; rid < kNRows; ++rid) {
const size_t ibegin = gmat.row_ptr[rid];
const size_t iend = gmat.row_ptr[rid + 1];
for (size_t i = ibegin; i < iend; ++i) {
const size_t bin_id = gmat.index[i];
histogram_expected[bin_id] += GradientPairPrecise(gpair[rid]);
}
}
// Now validate the computed histogram returned by BuildHist
for (size_t i = 0; i < histogram.Histogram()[nid].size(); ++i) {
GradientPairPrecise sol = histogram_expected[i];
ASSERT_NEAR(sol.GetGrad(), histogram.Histogram()[nid][i].GetGrad(), kEps);
ASSERT_NEAR(sol.GetHess(), histogram.Histogram()[nid][i].GetHess(), kEps);
}
}
TEST(CPUHistogram, BuildHist) {
TestBuildHistogram<float>(true);
TestBuildHistogram<double>(true);
TestBuildHistogram<float>(false);
TestBuildHistogram<double>(false);
}
TEST(CPUHistogram, ExternalMemory) {
size_t constexpr kEntries = 1 << 16;
int32_t constexpr kBins = 32;
auto m = CreateSparsePageDMatrix(kEntries, "cache");
std::vector<size_t> partition_size(1, 0);
size_t total_bins{0};
size_t n_samples{0};
auto gpair = GenerateRandomGradients(m->Info().num_row_, 0.0, 1.0);
auto const &h_gpair = gpair.HostVector();
RegTree tree;
std::vector<CPUExpandEntry> nodes;
nodes.emplace_back(0, tree.GetDepth(0), 0.0f);
GHistRow<double> multi_page;
HistogramBuilder<double, CPUExpandEntry> multi_build;
{
/**
* Multi page
*/
std::vector<RowSetCollection> rows_set;
std::vector<float> hess(m->Info().num_row_, 1.0);
for (auto const &page : m->GetBatches<GHistIndexMatrix>(
{GenericParameter::kCpuId, kBins, hess})) {
CHECK_LT(page.base_rowid, m->Info().num_row_);
auto n_rows_in_node = page.Size();
partition_size[0] = std::max(partition_size[0], n_rows_in_node);
total_bins = page.cut.TotalBins();
n_samples += n_rows_in_node;
rows_set.emplace_back();
InitRowPartitionForTest(&rows_set.back(), n_rows_in_node, page.base_rowid);
}
ASSERT_EQ(n_samples, m->Info().num_row_);
common::BlockedSpace2d space{
1, [&](size_t nidx_in_set) { return partition_size.at(nidx_in_set); },
256};
multi_build.Reset(total_bins, {GenericParameter::kCpuId, kBins},
omp_get_max_threads(), rows_set.size(), false);
size_t page_idx{0};
for (auto const &page : m->GetBatches<GHistIndexMatrix>(
{GenericParameter::kCpuId, kBins, hess})) {
multi_build.BuildHist(page_idx, space, page, &tree,
rows_set.at(page_idx), nodes, {}, h_gpair);
++page_idx;
}
ASSERT_EQ(page_idx, 2);
multi_page = multi_build.Histogram()[0];
}
HistogramBuilder<double, CPUExpandEntry> single_build;
GHistRow<double> single_page;
{
/**
* Single page
*/
RowSetCollection row_set_collection;
InitRowPartitionForTest(&row_set_collection, n_samples);
single_build.Reset(total_bins, {GenericParameter::kCpuId, kBins},
omp_get_max_threads(), 1, false);
size_t n_batches{0};
for (auto const &page :
m->GetBatches<GHistIndexMatrix>({GenericParameter::kCpuId, kBins})) {
single_build.BuildHist(0, page, &tree, row_set_collection, nodes, {},
h_gpair);
n_batches ++;
}
ASSERT_EQ(n_batches, 1);
single_page = single_build.Histogram()[0];
}
for (size_t i = 0; i < single_page.size(); ++i) {
ASSERT_NEAR(single_page[i].GetGrad(), multi_page[i].GetGrad(), kRtEps);
ASSERT_NEAR(single_page[i].GetHess(), multi_page[i].GetHess(), kRtEps);
}
}
} // namespace tree
} // namespace xgboost
|
#include "string.hpp"
int main() {
setBoolName("YES", "NO");
String s(in);
cout << (s.back() == 'T') << endl;
}
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <tack@gecode.org>
*
* Copyright:
* Guido Tack, 2006
*
* Last modified:
* $Date$ by $Author$
* $Revision$
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* 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 "nodestats.hh"
#include "nodewidget.hh"
#include "nodecursor.hh"
#include "nodevisitor.hh"
#include "drawingcursor.hh"
#include "cpprofiler/utils/tree_utils.hh"
using namespace cpprofiler;
NodeStatInspector::NodeStatInspector(QWidget* parent, const NodeTree& nt)
: QWidget(parent), nt(nt) {
setWindowFlags(Qt::Tool);
QGraphicsScene* scene = new QGraphicsScene(parent);
scene->addEllipse(70,10,16,16,QPen(),QBrush(colors::white));
scene->addEllipse(70,60,16,16,QPen(),QBrush(colors::blue));
scene->addRect(32,100,12,12,QPen(),QBrush(colors::red));
QPolygonF poly;
poly << QPointF(78,100) << QPointF(78+8,100+8)
<< QPointF(78,100+16) << QPointF(78-8,100+8);
scene->addPolygon(poly,QPen(),QBrush(colors::green));
scene->addEllipse(110,100,16,16,QPen(),QBrush(colors::white));
QPen pen;
pen.setStyle(Qt::DotLine);
pen.setWidth(0);
scene->addLine(78,26,78,60,pen);
scene->addLine(78,76,38,100,pen);
scene->addLine(78,76,78,100,pen);
scene->addLine(78,76,118,100,pen);
scene->addLine(135,10,145,10);
scene->addLine(145,10,145,110);
scene->addLine(145,60,135,60);
scene->addLine(145,110,135,110);
nodeDepthLabel = scene->addText("0");
nodeDepthLabel->setPos(150,20);
subtreeDepthLabel = scene->addText("0");
subtreeDepthLabel->setPos(150,75);
choicesLabel = scene->addText("0");
choicesLabel->setPos(45,57);
solvedLabel = scene->addText("0");
solvedLabel->setPos(78-solvedLabel->document()->size().width()/2,120);
failedLabel = scene->addText("0");
failedLabel->setPos(30,120);
openLabel = scene->addText("0");
openLabel->setPos(110,120);
QGraphicsView* view = new QGraphicsView(scene);
view->setRenderHints(view->renderHints() | QPainter::Antialiasing);
view->show();
scene->setBackgroundBrush(Qt::white);
boxLayout = new QVBoxLayout();
boxLayout->setContentsMargins(0,0,0,0);
boxLayout->addWidget(view);
setLayout(boxLayout);
setWindowTitle("Gist node statistics");
setAttribute(Qt::WA_QuitOnClose, false);
setAttribute(Qt::WA_DeleteOnClose, false);
}
void
NodeStatInspector::node(VisualNode* n) {
auto& na = nt.getNA();
// if (isVisible()) {
auto depth = utils::calculateDepth(nt, *n);
nodeDepthLabel->setPlainText(QString("%1").arg(depth));;
StatCursor sc(n,na);
PreorderNodeVisitor<StatCursor> pnv(sc);
pnv.run();
subtreeDepthLabel->setPlainText(
QString("%1").arg(pnv.getCursor().depth));
solvedLabel->setPlainText(QString("%1").arg(pnv.getCursor().solved));
solvedLabel->setPos(78-solvedLabel->document()->size().width()/2,120);
failedLabel->setPlainText(QString("%1").arg(pnv.getCursor().failed));
failedLabel->setPos(44-failedLabel->document()->size().width(),120);
choicesLabel->setPlainText(QString("%1").arg(pnv.getCursor().choice));
choicesLabel->setPos(66-choicesLabel->document()->size().width(),57);
openLabel->setPlainText(QString("%1").arg(pnv.getCursor().open));
// }
}
void
NodeStatInspector::showStats(VisualNode* n) {
node(n);
show();
activateWindow();
}
|
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//
#ifndef BOOST_HTTP_PROTO_RFC_IMPL_STATUS_CODE_RULE_PP
#define BOOST_HTTP_PROTO_RFC_IMPL_STATUS_CODE_RULE_PP
#include <boost/http_proto/rfc/status_line_rule.hpp>
#include <boost/http_proto/rfc/crlf_rule.hpp>
#include <boost/http_proto/rfc/version_rule.hpp>
#include <boost/url/grammar/error.hpp>
namespace boost {
namespace http_proto {
/*
status-code = 3DIGIT
*/
void
status_code_rule::
parse(
char const*& it0,
char const* end,
error_code& ec,
status_code_rule& t) noexcept
{
auto const dig =
[](char c) -> int
{
unsigned char uc(c - '0');
if(uc > 9)
return -1;
return uc;
};
auto it = it0;
int v;
if(it == end)
{
ec = grammar::error::incomplete;
return;
}
v = dig(*it);
if(v == -1)
{
ec = grammar::error::syntax;
return;
}
t.v = 100 * v;
++it;
if(it == end)
{
ec = grammar::error::incomplete;
return;
}
v = dig(*it);
if(v == -1)
{
ec = grammar::error::syntax;
return;
}
t.v = t.v + (10 * v);
++it;
if(it == end)
{
ec = grammar::error::incomplete;
return;
}
v = dig(*it);
if(v == -1)
{
ec = error::bad_status_code;
return;
}
t.v = t.v + v;
++it;
t.s = string_view(it0, it - it0);
t.st = int_to_status(t.v);
}
} // http_proto
} // boost
#endif
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Heiko Strathmann
*/
#include <shogun/features/streaming/generators/GaussianBlobsDataGenerator.h>
using namespace shogun;
CGaussianBlobsDataGenerator::CGaussianBlobsDataGenerator() :
CStreamingDenseFeatures<float64_t>()
{
init();
}
CGaussianBlobsDataGenerator::CGaussianBlobsDataGenerator(index_t sqrt_num_blobs,
float64_t distance, float64_t stretch, float64_t angle) :
CStreamingDenseFeatures<float64_t>()
{
init();
set_blobs_model(sqrt_num_blobs, distance, stretch, angle);
}
CGaussianBlobsDataGenerator::~CGaussianBlobsDataGenerator()
{
}
void CGaussianBlobsDataGenerator::set_blobs_model(index_t sqrt_num_blobs,
float64_t distance, float64_t stretch, float64_t angle)
{
m_sqrt_num_blobs=sqrt_num_blobs;
m_distance=distance;
m_stretch=stretch;
m_angle=angle;
/* precompute cholesky decomposition, start with rotation matrix */
SGMatrix<float64_t> R(2, 2);
R(0, 0) = std::cos(angle);
R(0, 1) = -std::sin(angle);
R(1, 0) = std::sin(angle);
R(1, 1) = std::cos(angle);
/* diagonal eigenvalue matrix */
SGMatrix<float64_t> L(2, 2);
L(0, 0) = std::sqrt(stretch);
L(1, 0)=0;
L(0, 1)=0;
L(1, 1)=1;
/* compute and save cholesky for sampling later on */
m_cholesky=SGMatrix<float64_t>::matrix_multiply(R, L);
}
void CGaussianBlobsDataGenerator::init()
{
SG_ADD(&m_sqrt_num_blobs, "sqrt_num_blobs", "Number of Blobs per row");
SG_ADD(&m_distance, "distance", "Distance between blobs");
SG_ADD(&m_stretch, "stretch", "Stretch of blobs");
SG_ADD(&m_angle, "angle", "Angle of Blobs");
SG_ADD(&m_cholesky, "cholesky", "Cholesky factor of covariance matrix");
m_sqrt_num_blobs=1;
m_distance=0;
m_stretch=1;
m_angle=0;
m_cholesky=SGMatrix<float64_t>(2, 2);
m_cholesky(0, 0)=1;
m_cholesky(0, 1)=0;
m_cholesky(1, 0)=0;
m_cholesky(1, 1)=1;
unset_generic();
}
bool CGaussianBlobsDataGenerator::get_next_example()
{
SG_SDEBUG("entering CGaussianBlobsDataGenerator::get_next_example()\n");
/* allocate space */
SGVector<float64_t> result=SGVector<float64_t>(2);
/* sample latent distribution to compute offsets */
index_t x_offset=CMath::random(0, m_sqrt_num_blobs-1)*m_distance;
index_t y_offset=CMath::random(0, m_sqrt_num_blobs-1)*m_distance;
/* sample from std Gaussian */
float64_t x=CMath::randn_double();
float64_t y=CMath::randn_double();
/* transform through cholesky and add offset */
result[0]=m_cholesky(0, 0)*x+m_cholesky(0, 1)*y+x_offset;
result[1]=m_cholesky(1, 0)*x+m_cholesky(1, 1)*y+y_offset;
/* save example back to superclass */
CGaussianBlobsDataGenerator::current_vector=result;
SG_SDEBUG("leaving CGaussianBlobsDataGenerator::get_next_example()\n");
return true;
}
void CGaussianBlobsDataGenerator::release_example()
{
SGVector<float64_t> temp=SGVector<float64_t>();
CGaussianBlobsDataGenerator::current_vector=temp;
}
|
#include "safe_lid.h"
#include "../../game.h"
SafeLid::SafeLid(const char* bodyFilename, const char* modelFilename, const Vector3f& position,
const Vector3f& rotationAxis, float rotationAngle, Prop* pSafe) :
pHingeConstraint_(nullptr),
pSageImageBillboard_(nullptr),
elapsedTime_(0.0f),
timeInterval_(2.0f),
state_(SafeLid::State::LOCKED),
Prop(bodyFilename, modelFilename, false, true, position, rotationAxis, rotationAngle)
{
try
{
pHingeConstraint_ = new HingeConstraint(
pBody_,
pSafe->getBody(),
Vector3f(0.14f, 0.2f, 0.0f),
Vector3f(0.14f, 0.2f, 0.185f),
Vector3f(0.0f, 1.0f, 0.0f),
Vector3f(0.0f, 1.0f, 0.0f)
);
PhysicsEngine::getInstance().addConstraint(pHingeConstraint_);
pHingeConstraint_->setLimit(0.0f, 0.0f);
pSageImageBillboard_ = new Billboard2D("../EscapeRoom/data/textures/safe.png", 1.0f);
}
catch (...)
{
if (pSageImageBillboard_ != nullptr)
{
delete pSageImageBillboard_;
pSageImageBillboard_ = nullptr;
}
if (pHingeConstraint_ != nullptr)
{
PhysicsEngine::getInstance().removeConstraint(pHingeConstraint_);
delete pHingeConstraint_;
pHingeConstraint_ = nullptr;
}
throw;
}
}
SafeLid::~SafeLid()
{
if (pSageImageBillboard_ != nullptr)
{
delete pSageImageBillboard_;
pSageImageBillboard_ = nullptr;
}
if (pHingeConstraint_ != nullptr)
{
PhysicsEngine::getInstance().removeConstraint(pHingeConstraint_);
delete pHingeConstraint_;
pHingeConstraint_ = nullptr;
}
}
bool SafeLid::use(Prop* pOtherProp)
{
switch (state_)
{
case SafeLid::State::LOCKED:
{
Renderer::getInstance().scenes_[SceneId::KEYPAD_SCENE].add(pSageImageBillboard_);
Game::getInstance().useKeypad(
3,
std::bind(
&SafeLid::keypadCallback,
this,
std::placeholders::_1
)
);
return false;
}
case SafeLid::State::UNLOCKED:
{
Game::getInstance().playVideo(
"../EscapeRoom/data/videos/safe_animation.mkv",
std::bind(&SafeLid::videoCallback, this)
);
return false;
}
case SafeLid::State::OPEN:
{
pBody_->applyImpulse(Vector3f(0.0f, 0.0f, -0.4f), Vector3f(0.3f, 0.0f, 0.0f));
return false;
}
default:
return false;
}
}
void SafeLid::update(float deltaTime)
{
pShadedModel3D_->position_ = pBody_->getPosition();
pShadedModel3D_->rotationAxis_ = pBody_->getRotationAxis();
pShadedModel3D_->angle_ = pBody_->getRotationAngle();
}
bool SafeLid::keypadCallback(const int* numbers)
{
if (numbers == nullptr)
{
Renderer::getInstance().scenes_[SceneId::KEYPAD_SCENE].remove(pSageImageBillboard_);
return false;
}
if (numbers[0] == 8
&& numbers[1] == 3
&& numbers[2] == 4)
{
Renderer::getInstance().scenes_[SceneId::KEYPAD_SCENE].remove(pSageImageBillboard_);
state_ = SafeLid::State::UNLOCKED;
return true;
}
return false;
}
void SafeLid::videoCallback()
{
pHingeConstraint_->setLimit(0.0f, 90.0f);
state_ = SafeLid::State::OPEN;
}
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jsnapi_helper-inl.h"
#include <array>
#include <cstdint>
#include "ecmascript/base/builtins_base.h"
#include "ecmascript/base/json_parser.h"
#include "ecmascript/base/json_stringifier.h"
#include "ecmascript/base/string_helper.h"
#include "ecmascript/base/typed_array_helper-inl.h"
#include "ecmascript/ecma_global_storage-inl.h"
#include "ecmascript/ecma_language_context.h"
#include "ecmascript/ecma_module.h"
#include "ecmascript/ecma_string.h"
#include "ecmascript/ecma_vm.h"
#include "ecmascript/global_env.h"
#include "ecmascript/internal_call_params.h"
#include "ecmascript/interpreter/fast_runtime_stub-inl.h"
#include "ecmascript/js_array.h"
#include "ecmascript/js_arraybuffer.h"
#include "ecmascript/js_dataview.h"
#include "ecmascript/js_function.h"
#include "ecmascript/js_map.h"
#include "ecmascript/js_primitive_ref.h"
#include "ecmascript/js_promise.h"
#include "ecmascript/js_regexp.h"
#include "ecmascript/js_serializer.h"
#include "ecmascript/js_set.h"
#include "ecmascript/js_tagged_number.h"
#include "ecmascript/js_thread.h"
#include "ecmascript/js_typed_array.h"
#include "ecmascript/mem/region.h"
#include "ecmascript/object_factory.h"
#include "ecmascript/tagged_array.h"
#include "libpandabase/os/library_loader.h"
#include "utils/pandargs.h"
namespace panda {
using ecmascript::CString;
using ecmascript::ECMAObject;
using ecmascript::EcmaString;
using ecmascript::ErrorType;
using ecmascript::FastRuntimeStub;
using ecmascript::GlobalEnv;
using ecmascript::GlobalEnvConstants;
using ecmascript::InternalCallParams;
using ecmascript::JSArray;
using ecmascript::JSArrayBuffer;
using ecmascript::JSDataView;
using ecmascript::JSDate;
using ecmascript::JSFunction;
using ecmascript::JSFunctionBase;
using ecmascript::JSFunctionExtraInfo;
using ecmascript::JSHClass;
using ecmascript::JSMap;
using ecmascript::JSMethod;
using ecmascript::JSNativeObject;
using ecmascript::JSNativePointer;
using ecmascript::JSObject;
using ecmascript::JSPrimitiveRef;
using ecmascript::JSPromise;
using ecmascript::JSRegExp;
using ecmascript::JSSerializer;
using ecmascript::JSSet;
using ecmascript::JSSymbol;
using ecmascript::JSTaggedNumber;
using ecmascript::JSTaggedType;
using ecmascript::JSTaggedValue;
using ecmascript::JSThread;
using ecmascript::ObjectFactory;
using ecmascript::PromiseCapability;
using ecmascript::PropertyDescriptor;
using ecmascript::OperationResult;
using ecmascript::Region;
using ecmascript::TaggedArray;
using ecmascript::JSTypedArray;
using ecmascript::base::BuiltinsBase;
using ecmascript::base::JsonParser;
using ecmascript::base::JsonStringifier;
using ecmascript::base::StringHelper;
using ecmascript::base::TypedArrayHelper;
template<typename T>
using JSHandle = ecmascript::JSHandle<T>;
namespace {
constexpr uint32_t INTERNAL_POOL_SIZE = 0;
constexpr uint32_t CODE_POOL_SIZE = 0;
constexpr uint32_t COMPILER_POOL_SIZE = 0;
// NOLINTNEXTLINE(fuchsia-statically-constructed-objects)
constexpr std::string_view ENTRY_POINTER = "_GLOBAL::func_main_0";
}
// ------------------------------------ Panda -----------------------------------------------
bool JSNApi::CreateRuntime(const RuntimeOption &option)
{
RuntimeOptions runtimeOptions;
runtimeOptions.SetRuntimeType("ecmascript");
// GC
runtimeOptions.SetGcType(option.GetGcType());
runtimeOptions.SetRunGcInPlace(true);
// Mem
runtimeOptions.SetHeapSizeLimit(option.GetGcPoolSize());
runtimeOptions.SetInternalMemorySizeLimit(INTERNAL_POOL_SIZE);
runtimeOptions.SetCodeCacheSizeLimit(CODE_POOL_SIZE);
runtimeOptions.SetCompilerMemorySizeLimit(COMPILER_POOL_SIZE);
runtimeOptions.SetInternalAllocatorType("malloc");
// Boot
runtimeOptions.SetShouldLoadBootPandaFiles(false);
runtimeOptions.SetShouldInitializeIntrinsics(false);
runtimeOptions.SetBootClassSpaces({"ecmascript"});
// Dfx
runtimeOptions.SetLogLevel(option.GetLogLevel());
arg_list_t logComponents;
logComponents.emplace_back("all");
runtimeOptions.SetLogComponents(logComponents);
if (option.GetLogBufPrint() != nullptr) {
runtimeOptions.SetMobileLog(reinterpret_cast<void *>(option.GetLogBufPrint()));
}
// Debugger
runtimeOptions.SetDebuggerLibraryPath(option.GetDebuggerLibraryPath());
static EcmaLanguageContext lcEcma;
if (!Runtime::Create(runtimeOptions, {&lcEcma})) {
std::cerr << "Error: cannot create runtime" << std::endl;
return false;
}
return true;
}
bool JSNApi::DestoryRuntime()
{
return Runtime::Destroy();
}
EcmaVM *JSNApi::CreateJSVM(const RuntimeOption &option)
{
auto runtime = Runtime::GetCurrent();
if (runtime == nullptr) {
// Art java + Panda js or L2 pure JS app
if (!CreateRuntime(option)) {
return nullptr;
}
runtime = Runtime::GetCurrent();
return EcmaVM::Cast(runtime->GetPandaVM());
}
RuntimeOptions runtimeOptions;
// GC
runtimeOptions.SetGcTriggerType("no-gc-for-start-up"); // A non-production gc strategy. Prohibit stw-gc 10 times.
return EcmaVM::Cast(EcmaVM::Create(runtimeOptions));
}
void JSNApi::DestoryJSVM(EcmaVM *ecmaVm)
{
auto runtime = Runtime::GetCurrent();
if (runtime != nullptr) {
PandaVM *mainVm = runtime->GetPandaVM();
// Art java + Panda js
if (mainVm == ecmaVm) {
DestoryRuntime();
} else {
EcmaVM::Destroy(ecmaVm);
}
}
}
void JSNApi::TriggerGC(const EcmaVM *vm)
{
if (vm->GetJSThread() != nullptr && vm->IsInitialized()) {
vm->CollectGarbage(ecmascript::TriggerGCType::SEMI_GC);
}
}
void JSNApi::ThrowException(const EcmaVM *vm, Local<JSValueRef> error)
{
auto thread = vm->GetJSThread();
thread->SetException(JSNApiHelper::ToJSTaggedValue(*error));
}
bool JSNApi::StartDebugger(const char *library_path, EcmaVM *vm)
{
auto handle = panda::os::library_loader::Load(std::string(library_path));
if (!handle) {
return false;
}
using StartDebugger = bool (*)(const std::string &, EcmaVM *);
auto sym = panda::os::library_loader::ResolveSymbol(handle.Value(), "StartDebug");
if (!sym) {
LOG(ERROR, RUNTIME) << sym.Error().ToString();
return false;
}
bool ret = reinterpret_cast<StartDebugger>(sym.Value())("PandaDebugger", vm);
if (ret) {
auto runtime = Runtime::GetCurrent();
runtime->SetDebugMode(true);
runtime->SetDebuggerLibrary(std::move(handle.Value()));
}
return ret;
}
bool JSNApi::Execute(EcmaVM *vm, Local<StringRef> fileName, Local<StringRef> entry)
{
std::string file = fileName->ToString();
std::string entryPoint = entry->ToString();
std::vector<std::string> argv;
LOG_ECMA(DEBUG) << "start to execute ark file" << file;
if (!vm->ExecuteFromPf(file, entryPoint, argv)) {
LOG_ECMA(ERROR) << "Cannot execute ark file" << file;
std::cerr << "Cannot execute ark file '" << file << "' with entry '" << entryPoint << "'" << std::endl;
return false;
}
return true;
}
bool JSNApi::Execute(EcmaVM *vm, const uint8_t *data, int32_t size, Local<StringRef> entry)
{
std::string entryPoint = entry->ToString();
std::vector<std::string> argv;
if (!vm->ExecuteFromBuffer(data, size, entryPoint, argv)) {
std::cerr << "Cannot execute panda file from memory "
<< "' with entry '" << entryPoint << "'" << std::endl;
return false;
}
return true;
}
Local<ObjectRef> JSNApi::GetUncaughtException(const EcmaVM *vm)
{
return JSNApiHelper::ToLocal<ObjectRef>(vm->GetEcmaUncaughtException());
}
void JSNApi::EnableUserUncaughtErrorHandler(EcmaVM *vm)
{
return vm->EnableUserUncaughtErrorHandler();
}
Local<ObjectRef> JSNApi::GetGlobalObject(const EcmaVM *vm)
{
JSHandle<GlobalEnv> globalEnv = vm->GetGlobalEnv();
JSHandle<JSTaggedValue> global(vm->GetJSThread(), globalEnv->GetGlobalObject());
return JSNApiHelper::ToLocal<ObjectRef>(global);
}
void JSNApi::ExecutePendingJob(const EcmaVM *vm)
{
vm->ExecutePromisePendingJob();
}
uintptr_t JSNApi::GetHandleAddr(const EcmaVM *vm, uintptr_t localAddress)
{
if (localAddress == 0) {
return 0;
}
JSTaggedType value = *(reinterpret_cast<JSTaggedType *>(localAddress));
return ecmascript::EcmaHandleScope::NewHandle(vm->GetJSThread(), value);
}
uintptr_t JSNApi::GetGlobalHandleAddr(const EcmaVM *vm, uintptr_t localAddress)
{
if (localAddress == 0) {
return 0;
}
JSTaggedType value = *(reinterpret_cast<JSTaggedType *>(localAddress));
return vm->GetJSThread()->GetEcmaGlobalStorage()->NewGlobalHandle(value);
}
uintptr_t JSNApi::SetWeak(const EcmaVM *vm, uintptr_t localAddress)
{
if (localAddress == 0) {
return 0;
}
return vm->GetJSThread()->GetEcmaGlobalStorage()->SetWeak(localAddress);
}
bool JSNApi::IsWeak(const EcmaVM *vm, uintptr_t localAddress)
{
if (localAddress == 0) {
return false;
}
return vm->GetJSThread()->GetEcmaGlobalStorage()->IsWeak(localAddress);
}
void JSNApi::DisposeGlobalHandleAddr(const EcmaVM *vm, uintptr_t addr)
{
if (addr == 0) {
return;
}
vm->GetJSThread()->GetEcmaGlobalStorage()->DisposeGlobalHandle(addr);
}
uintptr_t JSNApi::GetGlobalUndefinedAddr(const EcmaVM *vm)
{
return vm->GetJSThread()->GlobalConstants()->GetGlobalConstantAddr(ecmascript::ConstantIndex::UNDEFINED_INDEX);
}
void *JSNApi::SerializeValue(const EcmaVM *vm, Local<JSValueRef> value, Local<JSValueRef> transfer)
{
ecmascript::JSThread *thread = vm->GetJSThread();
ecmascript::Serializer serializer(thread);
JSHandle<JSTaggedValue> arkValue = JSNApiHelper::ToJSHandle(value);
JSHandle<JSTaggedValue> arkTransfer = JSNApiHelper::ToJSHandle(transfer);
std::unique_ptr<ecmascript::SerializationData> data;
if (serializer.WriteValue(thread, arkValue, arkTransfer)) {
data = serializer.Release();
}
return reinterpret_cast<void *>(data.release());
}
Local<JSValueRef> JSNApi::DeserializeValue(const EcmaVM *vm, void *recoder)
{
ecmascript::JSThread *thread = vm->GetJSThread();
std::unique_ptr<ecmascript::SerializationData> data(reinterpret_cast<ecmascript::SerializationData *>(recoder));
ecmascript::Deserializer deserializer(thread, data.release());
JSHandle<JSTaggedValue> result = deserializer.ReadValue();
return JSNApiHelper::ToLocal<ObjectRef>(result);
}
void JSNApi::DeleteSerializationData(void *data)
{
ecmascript::SerializationData *value = reinterpret_cast<ecmascript::SerializationData *>(data);
delete value;
}
bool JSNApi::ExecuteModuleFromBuffer(EcmaVM *vm, const void *data, int32_t size, const std::string &file)
{
auto moduleManager = vm->GetModuleManager();
moduleManager->SetCurrentExportModuleName(file);
// Update Current Module
vm->GetJSThread()->SetIsEcmaInterpreter(true);
std::vector<std::string> argv;
if (!vm->ExecuteFromBuffer(data, size, ENTRY_POINTER, argv)) {
std::cerr << "Cannot execute panda file from memory" << std::endl;
moduleManager->RestoreCurrentExportModuleName();
return false;
}
// Restore Current Module
moduleManager->RestoreCurrentExportModuleName();
return true;
}
Local<ObjectRef> JSNApi::GetExportObject(EcmaVM *vm, const std::string &file, const std::string &itemName)
{
auto moduleManager = vm->GetModuleManager();
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSTaggedValue> moduleName(factory->NewFromStdStringUnCheck(file, true));
JSHandle<JSTaggedValue> moduleObj = moduleManager->GetModule(vm->GetJSThread(), moduleName);
JSHandle<JSTaggedValue> itemString(factory->NewFromStdString(itemName));
JSHandle<JSTaggedValue> exportObj = moduleManager->GetModuleItem(vm->GetJSThread(), moduleObj, itemString);
return JSNApiHelper::ToLocal<ObjectRef>(exportObj);
}
// ----------------------------------- HandleScope -------------------------------------
LocalScope::LocalScope(const EcmaVM *vm) : thread_(vm->GetJSThread())
{
auto thread = reinterpret_cast<JSThread *>(thread_);
prevNext_ = thread->GetHandleScopeStorageNext();
prevEnd_ = thread->GetHandleScopeStorageEnd();
prevHandleStorageIndex_ = thread->GetCurrentHandleStorageIndex();
}
LocalScope::LocalScope(const EcmaVM *vm, JSTaggedType value) : thread_(vm->GetJSThread())
{
auto thread = reinterpret_cast<JSThread *>(thread_);
prevNext_ = thread->GetHandleScopeStorageNext();
prevEnd_ = thread->GetHandleScopeStorageEnd();
prevHandleStorageIndex_ = thread->GetCurrentHandleStorageIndex();
ecmascript::EcmaHandleScope::NewHandle(thread, value);
}
LocalScope::~LocalScope()
{
auto thread = reinterpret_cast<JSThread *>(thread_);
thread->SetHandleScopeStorageNext(static_cast<JSTaggedType *>(prevNext_));
if (thread->GetHandleScopeStorageEnd() != prevEnd_) {
thread->SetHandleScopeStorageEnd(static_cast<JSTaggedType *>(prevEnd_));
thread->ShrinkHandleStorage(prevHandleStorageIndex_);
}
}
// ----------------------------------- EscapeLocalScope ------------------------------
EscapeLocalScope::EscapeLocalScope(const EcmaVM *vm) : LocalScope(vm, 0U)
{
auto thread = vm->GetJSThread();
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
escapeHandle_ = ToUintPtr(thread->GetHandleScopeStorageNext() - 1);
}
// ----------------------------------- NumberRef ---------------------------------------
Local<NumberRef> NumberRef::New(const EcmaVM *vm, double input)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> number(thread, JSTaggedValue(input));
return JSNApiHelper::ToLocal<NumberRef>(number);
}
double NumberRef::Value()
{
return JSTaggedNumber(JSNApiHelper::ToJSTaggedValue(this)).GetNumber();
}
// ----------------------------------- BooleanRef ---------------------------------------
Local<BooleanRef> BooleanRef::New(const EcmaVM *vm, bool input)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> boolean(thread, JSTaggedValue(input));
return JSNApiHelper::ToLocal<BooleanRef>(boolean);
}
bool BooleanRef::Value()
{
return JSNApiHelper::ToJSTaggedValue(this).IsTrue();
}
// ----------------------------------- IntegerRef ---------------------------------------
Local<IntegerRef> IntegerRef::New(const EcmaVM *vm, int input)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> integer(thread, JSTaggedValue(input));
return JSNApiHelper::ToLocal<IntegerRef>(integer);
}
Local<IntegerRef> IntegerRef::NewFromUnsigned(const EcmaVM *vm, unsigned int input)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> integer(thread, JSTaggedValue(input));
return JSNApiHelper::ToLocal<IntegerRef>(integer);
}
int IntegerRef::Value()
{
return JSNApiHelper::ToJSTaggedValue(this).GetInt();
}
// ----------------------------------- StringRef ----------------------------------------
Local<StringRef> StringRef::NewFromUtf8(const EcmaVM *vm, const char *utf8, int length)
{
ObjectFactory *factory = vm->GetFactory();
if (length < 0) {
JSHandle<JSTaggedValue> current(factory->NewFromString(utf8));
return JSNApiHelper::ToLocal<StringRef>(current);
}
JSHandle<JSTaggedValue> current(factory->NewFromUtf8(reinterpret_cast<const uint8_t *>(utf8), length));
return JSNApiHelper::ToLocal<StringRef>(current);
}
std::string StringRef::ToString()
{
return StringHelper::ToStdString(EcmaString::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject()));
}
int32_t StringRef::Length()
{
return EcmaString::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject())->GetLength();
}
int32_t StringRef::Utf8Length()
{
return EcmaString::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject())->GetUtf8Length();
}
int StringRef::WriteUtf8(char *buffer, int length)
{
return EcmaString::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject())
->CopyDataUtf8(reinterpret_cast<uint8_t *>(buffer), length);
}
// ----------------------------------- SymbolRef -----------------------------------------
Local<SymbolRef> SymbolRef::New(const EcmaVM *vm, Local<StringRef> description)
{
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSSymbol> symbol = factory->NewJSSymbol();
JSTaggedValue desc = JSNApiHelper::ToJSTaggedValue(*description);
symbol->SetDescription(vm->GetJSThread(), desc);
return JSNApiHelper::ToLocal<SymbolRef>(JSHandle<JSTaggedValue>(symbol));
}
Local<StringRef> SymbolRef::GetDescription(const EcmaVM *vm)
{
JSTaggedValue description = JSSymbol::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject())->GetDescription();
if (!description.IsString()) {
auto constants = vm->GetJSThread()->GlobalConstants();
return JSNApiHelper::ToLocal<StringRef>(constants->GetHandledEmptyString());
}
JSHandle<JSTaggedValue> descriptionHandle(vm->GetJSThread(), description);
return JSNApiHelper::ToLocal<StringRef>(descriptionHandle);
}
// -------------------------------- NativePointerRef ------------------------------------
Local<NativePointerRef> NativePointerRef::New(const EcmaVM *vm, void *nativePointer)
{
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSNativeObject> obj = factory->NewJSNativeObject(nativePointer);
return JSNApiHelper::ToLocal<NativePointerRef>(JSHandle<JSTaggedValue>(obj));
}
Local<NativePointerRef> NativePointerRef::New(
const EcmaVM *vm, void *nativePointer, NativePointerCallback callBack, void *data)
{
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSNativeObject> obj = factory->NewJSNativeObject(nativePointer, callBack, data);
return JSNApiHelper::ToLocal<NativePointerRef>(JSHandle<JSTaggedValue>(obj));
}
void *NativePointerRef::Value()
{
JSHandle<JSTaggedValue> nativePointer = JSNApiHelper::ToJSHandle(this);
return JSHandle<JSNativeObject>(nativePointer)->GetExternalPointer();
}
// ----------------------------------- ObjectRef ----------------------------------------
Local<ObjectRef> ObjectRef::New(const EcmaVM *vm)
{
ObjectFactory *factory = vm->GetFactory();
JSHandle<GlobalEnv> globalEnv = vm->GetGlobalEnv();
JSHandle<JSTaggedValue> constructor = globalEnv->GetObjectFunction();
JSHandle<JSTaggedValue> object(factory->NewJSObjectByConstructor(JSHandle<JSFunction>(constructor), constructor));
RETURN_VALUE_IF_ABRUPT(vm->GetJSThread(), JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ObjectRef>(object);
}
bool ObjectRef::Set(const EcmaVM *vm, Local<JSValueRef> key, Local<JSValueRef> value)
{
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> keyValue = JSNApiHelper::ToJSHandle(key);
JSHandle<JSTaggedValue> valueValue = JSNApiHelper::ToJSHandle(value);
bool result = JSTaggedValue::SetProperty(vm->GetJSThread(), obj, keyValue, valueValue);
RETURN_VALUE_IF_ABRUPT(vm->GetJSThread(), false);
return result;
}
bool ObjectRef::Set(const EcmaVM *vm, uint32_t key, Local<JSValueRef> value)
{
Local<JSValueRef> keyValue = NumberRef::New(vm, key);
return Set(vm, keyValue, value);
}
bool ObjectRef::SetAccessorProperty(const EcmaVM *vm, Local<JSValueRef> key, Local<FunctionRef> getter,
Local<FunctionRef> setter, PropertyAttribute attribute)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> getterValue = JSNApiHelper::ToJSHandle(getter);
JSHandle<JSTaggedValue> setterValue = JSNApiHelper::ToJSHandle(setter);
PropertyDescriptor desc(thread, attribute.IsWritable(), attribute.IsEnumerable(), attribute.IsConfigurable());
desc.SetValue(JSNApiHelper::ToJSHandle(attribute.GetValue(vm)));
desc.SetSetter(setterValue);
desc.SetGetter(getterValue);
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> keyValue = JSNApiHelper::ToJSHandle(key);
bool result = JSTaggedValue::DefineOwnProperty(thread, obj, keyValue, desc);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
Local<JSValueRef> ObjectRef::Get(const EcmaVM *vm, Local<JSValueRef> key)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> keyValue = JSNApiHelper::ToJSHandle(key);
OperationResult ret = JSTaggedValue::GetProperty(thread, obj, keyValue);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
if (!ret.GetPropertyMetaData().IsFound()) {
return Local<JSValueRef>();
}
return JSNApiHelper::ToLocal<JSValueRef>(ret.GetValue());
}
Local<JSValueRef> ObjectRef::Get(const EcmaVM *vm, int32_t key)
{
Local<JSValueRef> keyValue = IntegerRef::New(vm, key);
return Get(vm, keyValue);
}
bool ObjectRef::GetOwnProperty(const EcmaVM *vm, Local<JSValueRef> key, PropertyAttribute &property)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> keyValue = JSNApiHelper::ToJSHandle(key);
PropertyDescriptor desc(thread);
bool ret = JSObject::GetOwnProperty(thread, JSHandle<JSObject>(obj), keyValue, desc);
if (!ret) {
return false;
}
property.SetValue(JSNApiHelper::ToLocal<JSValueRef>(desc.GetValue()));
if (desc.HasGetter()) {
property.SetGetter(JSNApiHelper::ToLocal<JSValueRef>(desc.GetGetter()));
}
if (desc.HasSetter()) {
property.SetSetter(JSNApiHelper::ToLocal<JSValueRef>(desc.GetSetter()));
}
if (desc.HasWritable()) {
property.SetWritable(desc.IsWritable());
}
if (desc.HasEnumerable()) {
property.SetEnumerable(desc.IsEnumerable());
}
if (desc.HasConfigurable()) {
property.SetConfigurable(desc.IsConfigurable());
}
return true;
}
Local<ArrayRef> ObjectRef::GetOwnPropertyNames(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj(JSNApiHelper::ToJSHandle(this));
JSHandle<TaggedArray> array(JSTaggedValue::GetOwnPropertyKeys(thread, obj));
JSHandle<JSTaggedValue> jsArray(JSArray::CreateArrayFromList(thread, array));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ArrayRef>(jsArray);
}
Local<ArrayRef> ObjectRef::GetOwnEnumerablePropertyNames(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSObject> obj(JSNApiHelper::ToJSHandle(this));
JSHandle<TaggedArray> array(JSObject::EnumerableOwnNames(thread, obj));
JSHandle<JSTaggedValue> jsArray(JSArray::CreateArrayFromList(thread, array));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ArrayRef>(jsArray);
}
Local<JSValueRef> ObjectRef::GetPrototype(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSObject> object(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> prototype(thread, object->GetPrototype(thread));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<JSValueRef>(prototype);
}
bool ObjectRef::DefineProperty(const EcmaVM *vm, Local<JSValueRef> key, PropertyAttribute attribute)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> object(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> keyValue(JSNApiHelper::ToJSHandle(key));
PropertyDescriptor desc(thread, attribute.IsWritable(), attribute.IsEnumerable(), attribute.IsConfigurable());
desc.SetValue(JSNApiHelper::ToJSHandle(attribute.GetValue(vm)));
bool result = object->DefinePropertyOrThrow(thread, object, keyValue, desc);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
bool ObjectRef::Has(const EcmaVM *vm, Local<JSValueRef> key)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> object(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> keyValue(JSNApiHelper::ToJSHandle(key));
bool result = object->HasProperty(thread, object, keyValue);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
bool ObjectRef::Has(const EcmaVM *vm, uint32_t key)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> object(JSNApiHelper::ToJSHandle(this));
bool result = object->HasProperty(thread, object, key);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
bool ObjectRef::Delete(const EcmaVM *vm, Local<JSValueRef> key)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> object(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> keyValue(JSNApiHelper::ToJSHandle(key));
bool result = object->DeleteProperty(thread, object, keyValue);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
bool ObjectRef::Delete(const EcmaVM *vm, uint32_t key)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> object(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> keyHandle(thread, JSTaggedValue(key));
bool result = object->DeleteProperty(thread, object, keyHandle);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
void ObjectRef::SetNativePointerFieldCount(int32_t count)
{
JSHandle<JSObject> object(JSNApiHelper::ToJSHandle(this));
object->SetNativePointerFieldCount(count);
}
int32_t ObjectRef::GetNativePointerFieldCount()
{
JSHandle<JSObject> object(JSNApiHelper::ToJSHandle(this));
return object->GetNativePointerFieldCount();
}
void *ObjectRef::GetNativePointerField(int32_t index)
{
JSHandle<JSObject> object(JSNApiHelper::ToJSHandle(this));
return object->GetNativePointerField(index);
}
void ObjectRef::SetNativePointerField(int32_t index, void *data)
{
JSHandle<JSObject> object(JSNApiHelper::ToJSHandle(this));
object->SetNativePointerField(index, data);
}
// ----------------------------------- FunctionRef --------------------------------------
Local<FunctionRef> FunctionRef::New(EcmaVM *vm, FunctionCallback nativeFunc, void *data)
{
JSThread *thread = vm->GetJSThread();
ObjectFactory *factory = vm->GetFactory();
JSHandle<GlobalEnv> env = vm->GetGlobalEnv();
JSHandle<JSFunction> current(factory->NewJSFunction(env, reinterpret_cast<void *>(Callback::RegisterCallback)));
JSHandle<JSNativePointer> funcCallback = factory->NewJSNativePointer(reinterpret_cast<void *>(nativeFunc));
JSHandle<JSNativePointer> dataCaddress = factory->NewJSNativePointer(data);
JSHandle<JSFunctionExtraInfo> extraInfo(factory->NewFunctionExtraInfo(funcCallback, dataCaddress));
current->SetFunctionExtraInfo(thread, extraInfo.GetTaggedValue());
return JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(current));
}
Local<FunctionRef> FunctionRef::New(EcmaVM *vm, FunctionCallback nativeFunc, Deleter deleter, void *data)
{
JSThread *thread = vm->GetJSThread();
ObjectFactory *factory = vm->GetFactory();
JSHandle<GlobalEnv> env = vm->GetGlobalEnv();
JSHandle<JSFunction> current(factory->NewJSFunction(env, reinterpret_cast<void *>(Callback::RegisterCallback)));
JSHandle<JSNativePointer> funcCallback = factory->NewJSNativePointer(reinterpret_cast<void *>(nativeFunc));
JSHandle<JSNativePointer> dataCaddress = factory->NewJSNativePointer(data, deleter, nullptr);
vm->PushToArrayDataList(*dataCaddress);
JSHandle<JSFunctionExtraInfo> extraInfo(factory->NewFunctionExtraInfo(funcCallback, dataCaddress));
current->SetFunctionExtraInfo(thread, extraInfo.GetTaggedValue());
return JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(current));
}
Local<FunctionRef> FunctionRef::NewClassFunction(EcmaVM *vm, FunctionCallbackWithNewTarget nativeFunc, Deleter deleter,
void *data)
{
JSThread *thread = vm->GetJSThread();
ObjectFactory *factory = vm->GetFactory();
JSHandle<GlobalEnv> env = vm->GetGlobalEnv();
JSHandle<JSHClass> dynclass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithoutName());
JSMethod *method =
vm->GetMethodForNativeFunction(reinterpret_cast<void *>(Callback::RegisterCallbackWithNewTarget));
JSHandle<JSFunction> current =
factory->NewJSFunctionByDynClass(method, dynclass, ecmascript::FunctionKind::CLASS_CONSTRUCTOR);
JSHandle<JSNativePointer> funcCallback = factory->NewJSNativePointer(reinterpret_cast<void *>(nativeFunc));
JSHandle<JSNativePointer> dataCaddress(thread, JSTaggedValue::Undefined());
if (deleter == nullptr) {
dataCaddress = factory->NewJSNativePointer(data);
} else {
dataCaddress = factory->NewJSNativePointer(data, deleter, nullptr);
vm->PushToArrayDataList(*dataCaddress);
}
JSHandle<JSFunctionExtraInfo> extraInfo(factory->NewFunctionExtraInfo(funcCallback, dataCaddress));
current->SetFunctionExtraInfo(thread, extraInfo.GetTaggedValue());
JSHandle<JSObject> clsPrototype =
JSObject::ObjectCreate(thread, JSHandle<JSObject>(env->GetObjectFunctionPrototype()));
current->SetFunctionPrototype(thread, clsPrototype.GetTaggedValue());
return JSNApiHelper::ToLocal<FunctionRef>(JSHandle<JSTaggedValue>(current));
}
Local<JSValueRef> FunctionRef::Call(const EcmaVM *vm, Local<JSValueRef> thisObj,
const Local<JSValueRef> argv[], // NOLINTNEXTLINE(modernize-avoid-c-arrays)
int32_t length)
{
JSThread *thread = vm->GetJSThread();
if (!IsFunction()) {
return JSValueRef::Undefined(vm);
}
JSHandle<JSTaggedValue> func = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> thisValue = JSNApiHelper::ToJSHandle(thisObj);
ObjectFactory *factory = vm->GetFactory();
JSHandle<TaggedArray> arguments = factory->NewTaggedArray(length);
Span<const Local<JSValueRef>> sp(argv, length);
for (int i = 0; i < length; ++i) {
arguments->Set(thread, i, JSNApiHelper::ToJSHandle(sp[i]));
}
InternalCallParams *args = thread->GetInternalCallParams();
args->MakeArgList(*arguments);
JSTaggedValue result = JSFunction::Call(thread, func, thisValue, arguments->GetLength(), args->GetArgv());
RETURN_VALUE_IF_ABRUPT_NOT_CLEAR_EXCEPTION(thread, JSValueRef::Exception(vm));
JSHandle<JSTaggedValue> resultValue(thread, result);
vm->ExecutePromisePendingJob();
RETURN_VALUE_IF_ABRUPT_NOT_CLEAR_EXCEPTION(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<JSValueRef>(resultValue);
}
Local<JSValueRef> FunctionRef::Constructor(const EcmaVM *vm,
const Local<JSValueRef> argv[], // NOLINTNEXTLINE(modernize-avoid-c-arrays)
int32_t length)
{
JSThread *thread = vm->GetJSThread();
if (!IsFunction()) {
return JSValueRef::Undefined(vm);
}
JSHandle<JSTaggedValue> func = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> newTarget = func;
ObjectFactory *factory = vm->GetFactory();
JSHandle<TaggedArray> arguments = factory->NewTaggedArray(length);
Span<const Local<JSValueRef>> sp(argv, length);
for (int i = 0; i < length; ++i) {
arguments->Set(thread, i, JSNApiHelper::ToJSHandle(sp[i]));
}
ecmascript::InternalCallParams *params = thread->GetInternalCallParams();
params->MakeArgList(*arguments);
JSTaggedValue result = JSFunction::Construct(thread, func, length, params->GetArgv(), newTarget);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
JSHandle<JSTaggedValue> resultValue(vm->GetJSThread(), result);
return JSNApiHelper::ToLocal<JSValueRef>(resultValue);
}
Local<JSValueRef> FunctionRef::GetFunctionPrototype(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> func = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> prototype(thread, JSHandle<JSFunction>(func)->GetFunctionPrototype());
return JSNApiHelper::ToLocal<JSValueRef>(prototype);
}
void FunctionRef::SetName(const EcmaVM *vm, Local<StringRef> name)
{
JSThread *thread = vm->GetJSThread();
JSFunction *func = JSFunction::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject());
JSTaggedValue key = JSNApiHelper::ToJSTaggedValue(*name);
JSFunction::SetFunctionNameNoPrefix(thread, func, key);
}
Local<StringRef> FunctionRef::GetName(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSFunctionBase> func = JSHandle<JSFunctionBase>(thread, JSNApiHelper::ToJSTaggedValue(this));
JSHandle<JSTaggedValue> name = JSFunctionBase::GetFunctionName(thread, func);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<StringRef>(name);
}
bool FunctionRef::IsNative(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSFunctionBase> func = JSHandle<JSFunctionBase>(thread, JSNApiHelper::ToJSTaggedValue(this));
JSMethod *method = func->GetMethod();
return method->IsNative();
}
// ----------------------------------- ArrayRef ----------------------------------------
Local<ArrayRef> ArrayRef::New(const EcmaVM *vm, int32_t length)
{
JSThread *thread = vm->GetJSThread();
JSTaggedNumber arrayLen(length);
JSHandle<JSTaggedValue> array = JSArray::ArrayCreate(thread, arrayLen);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ArrayRef>(array);
}
int32_t ArrayRef::Length([[maybe_unused]] const EcmaVM *vm)
{
return JSArray::Cast(JSNApiHelper::ToJSTaggedValue(this).GetTaggedObject())->GetArrayLength();
}
Local<JSValueRef> ArrayRef::GetValueAt(const EcmaVM *vm, Local<JSValueRef> obj, uint32_t index)
{
JSThread *thread = vm->GetAssociatedJSThread();
JSHandle<JSTaggedValue> object = JSNApiHelper::ToJSHandle(obj);
JSHandle<JSTaggedValue> result = JSArray::FastGetPropertyByValue(thread, object, index);
return JSNApiHelper::ToLocal<JSValueRef>(result);
}
bool ArrayRef::SetValueAt(const EcmaVM *vm, Local<JSValueRef> obj, uint32_t index, Local<JSValueRef> value)
{
JSThread *thread = vm->GetAssociatedJSThread();
JSHandle<JSTaggedValue> objectHandle = JSNApiHelper::ToJSHandle(obj);
JSHandle<JSTaggedValue> valueHandle = JSNApiHelper::ToJSHandle(value);
return JSArray::FastSetPropertyByValue(thread, objectHandle, index, valueHandle);
}
// ---------------------------------- Promise --------------------------------------
Local<PromiseCapabilityRef> PromiseCapabilityRef::New(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<GlobalEnv> globalEnv = vm->GetGlobalEnv();
JSHandle<JSTaggedValue> constructor(globalEnv->GetPromiseFunction());
JSHandle<JSTaggedValue> capability(JSPromise::NewPromiseCapability(thread, constructor));
return JSNApiHelper::ToLocal<PromiseCapabilityRef>(capability);
}
Local<PromiseRef> PromiseCapabilityRef::GetPromise(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<PromiseCapability> capacity(JSNApiHelper::ToJSHandle(this));
return JSNApiHelper::ToLocal<PromiseRef>(JSHandle<JSTaggedValue>(thread, capacity->GetPromise()));
}
bool PromiseCapabilityRef::Resolve(const EcmaVM *vm, Local<JSValueRef> value)
{
JSThread *thread = vm->GetJSThread();
const GlobalEnvConstants *constants = thread->GlobalConstants();
JSHandle<JSTaggedValue> arg = JSNApiHelper::ToJSHandle(value);
JSHandle<PromiseCapability> capacity(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> resolve(thread, capacity->GetResolve());
JSHandle<JSTaggedValue> undefined(thread, constants->GetUndefined());
InternalCallParams *arguments = thread->GetInternalCallParams();
arguments->MakeArgv(arg);
JSFunction::Call(thread, resolve, undefined, 1, arguments->GetArgv());
RETURN_VALUE_IF_ABRUPT(thread, false);
return true;
}
bool PromiseCapabilityRef::Reject(const EcmaVM *vm, Local<JSValueRef> reason)
{
JSThread *thread = vm->GetJSThread();
const GlobalEnvConstants *constants = thread->GlobalConstants();
JSHandle<JSTaggedValue> arg = JSNApiHelper::ToJSHandle(reason);
JSHandle<PromiseCapability> capacity(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> reject(thread, capacity->GetReject());
JSHandle<JSTaggedValue> undefined(thread, constants->GetUndefined());
InternalCallParams *arguments = thread->GetInternalCallParams();
arguments->MakeArgv(arg);
JSFunction::Call(thread, reject, undefined, 1, arguments->GetArgv());
RETURN_VALUE_IF_ABRUPT(thread, false);
return true;
}
Local<PromiseRef> PromiseRef::Catch(const EcmaVM *vm, Local<FunctionRef> handler)
{
JSThread *thread = vm->GetJSThread();
const GlobalEnvConstants *constants = thread->GlobalConstants();
JSHandle<JSTaggedValue> promise = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> catchKey(thread, constants->GetPromiseCatchString());
JSHandle<JSTaggedValue> reject = JSNApiHelper::ToJSHandle(handler);
ecmascript::InternalCallParams *arguments = thread->GetInternalCallParams();
arguments->MakeArgv(reject);
JSTaggedValue result = JSFunction::Invoke(thread, promise, catchKey, 1, arguments->GetArgv());
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<PromiseRef>(JSHandle<JSTaggedValue>(thread, result));
}
Local<PromiseRef> PromiseRef::Then(const EcmaVM *vm, Local<FunctionRef> handler)
{
JSThread *thread = vm->GetJSThread();
const GlobalEnvConstants *constants = thread->GlobalConstants();
JSHandle<JSTaggedValue> promise = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> thenKey(thread, constants->GetPromiseThenString());
JSHandle<JSTaggedValue> resolver = JSNApiHelper::ToJSHandle(handler);
ecmascript::InternalCallParams *arguments = thread->GetInternalCallParams();
arguments->MakeArgv(resolver.GetTaggedValue(), constants->GetUndefined());
JSTaggedValue result = JSFunction::Invoke(thread, promise, thenKey, 2, arguments->GetArgv()); // 2: two args
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<PromiseRef>(JSHandle<JSTaggedValue>(thread, result));
}
Local<PromiseRef> PromiseRef::Then(const EcmaVM *vm, Local<FunctionRef> onFulfilled, Local<FunctionRef> onRejected)
{
JSThread *thread = vm->GetJSThread();
const GlobalEnvConstants *constants = thread->GlobalConstants();
JSHandle<JSTaggedValue> promise = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> thenKey(thread, constants->GetPromiseThenString());
JSHandle<JSTaggedValue> resolver = JSNApiHelper::ToJSHandle(onFulfilled);
JSHandle<JSTaggedValue> reject = JSNApiHelper::ToJSHandle(onRejected);
ecmascript::InternalCallParams *arguments = thread->GetInternalCallParams();
arguments->MakeArgv(resolver, reject);
JSTaggedValue result = JSFunction::Invoke(thread, promise, thenKey, 2, arguments->GetArgv()); // 2: two args
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<PromiseRef>(JSHandle<JSTaggedValue>(thread, result));
}
// ---------------------------------- Promise -------------------------------------
// ---------------------------------- Buffer -----------------------------------
Local<ArrayBufferRef> ArrayBufferRef::New(const EcmaVM *vm, int32_t length)
{
JSThread *thread = vm->GetJSThread();
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSArrayBuffer> arrayBuffer = factory->NewJSArrayBuffer(length);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ArrayBufferRef>(JSHandle<JSTaggedValue>(arrayBuffer));
}
Local<ArrayBufferRef> ArrayBufferRef::New(
const EcmaVM *vm, void *buffer, int32_t length, const Deleter &deleter, void *data)
{
JSThread *thread = vm->GetJSThread();
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSArrayBuffer> arrayBuffer =
factory->NewJSArrayBuffer(buffer, length, reinterpret_cast<ecmascript::DeleteEntryPoint>(deleter), data);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ArrayBufferRef>(JSHandle<JSTaggedValue>(arrayBuffer));
}
int32_t ArrayBufferRef::ByteLength(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSArrayBuffer> arrayBuffer(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> length(thread, arrayBuffer->GetArrayBufferByteLength());
if (!length->IsNumber()) {
return 0;
}
return length->GetNumber();
}
void *ArrayBufferRef::GetBuffer()
{
JSHandle<JSArrayBuffer> arrayBuffer(JSNApiHelper::ToJSHandle(this));
JSTaggedValue bufferData = arrayBuffer->GetArrayBufferData();
if (!bufferData.IsJSNativePointer()) {
return nullptr;
}
return JSNativePointer::Cast(bufferData.GetTaggedObject())->GetExternalPointer();
}
// ---------------------------------- Buffer -----------------------------------
// ---------------------------------- DataView -----------------------------------
Local<DataViewRef> DataViewRef::New(
const EcmaVM *vm, Local<ArrayBufferRef> arrayBuffer, int32_t byteOffset, int32_t byteLength)
{
JSThread *thread = vm->GetJSThread();
ObjectFactory *factory = vm->GetFactory();
JSHandle<JSArrayBuffer> buffer(JSNApiHelper::ToJSHandle(arrayBuffer));
JSHandle<JSDataView> dataView = factory->NewJSDataView(buffer, byteOffset, byteLength);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<DataViewRef>(JSHandle<JSTaggedValue>(dataView));
}
int32_t DataViewRef::ByteLength()
{
JSHandle<JSDataView> dataView(JSNApiHelper::ToJSHandle(this));
JSTaggedValue length = dataView->GetByteLength();
if (!length.IsNumber()) {
return 0;
}
return length.GetNumber();
}
int32_t DataViewRef::ByteOffset()
{
JSHandle<JSDataView> dataView(JSNApiHelper::ToJSHandle(this));
JSTaggedValue offset = dataView->GetByteOffset();
if (!offset.IsNumber()) {
return 0;
}
return offset.GetNumber();
}
Local<ArrayBufferRef> DataViewRef::GetArrayBuffer(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSDataView> dataView(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> arrayBuffer(thread, dataView->GetViewedArrayBuffer());
return JSNApiHelper::ToLocal<ArrayBufferRef>(arrayBuffer);
}
// ---------------------------------- DataView -----------------------------------
// ---------------------------------- TypedArray -----------------------------------
int32_t TypedArrayRef::ByteLength(const EcmaVM *vm)
{
JSHandle<JSTypedArray> typedArray(JSNApiHelper::ToJSHandle(this));
JSTaggedValue length = typedArray->GetByteLength();
if (!length.IsNumber()) {
return 0;
}
return length.GetNumber();
}
int32_t TypedArrayRef::ByteOffset(const EcmaVM *vm)
{
JSHandle<JSTypedArray> typedArray(JSNApiHelper::ToJSHandle(this));
JSTaggedValue length = typedArray->GetByteOffset();
if (!length.IsNumber()) {
return 0;
}
return length.GetNumber();
}
int32_t TypedArrayRef::ArrayLength(const EcmaVM *vm)
{
JSHandle<JSTypedArray> typedArray(JSNApiHelper::ToJSHandle(this));
JSTaggedValue length = typedArray->GetArrayLength();
if (!length.IsNumber()) {
return 0;
}
return length.GetNumber();
}
Local<ArrayBufferRef> TypedArrayRef::GetArrayBuffer(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSObject> typeArray(JSNApiHelper::ToJSHandle(this));
JSHandle<JSTaggedValue> arrayBuffer(thread, JSTypedArray::Cast(*typeArray)->GetViewedArrayBuffer());
return JSNApiHelper::ToLocal<ArrayBufferRef>(arrayBuffer);
}
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TYPED_ARRAY_NEW(Type) \
Local<Type##Ref> Type##Ref::New( \
const EcmaVM *vm, Local<ArrayBufferRef> buffer, int32_t byteOffset, int32_t length) \
{ \
JSThread *thread = vm->GetJSThread(); \
JSHandle<GlobalEnv> env = vm->GetGlobalEnv(); \
\
JSHandle<JSTaggedValue> func = env->Get##Type##Function(); \
JSHandle<JSArrayBuffer> arrayBuffer(JSNApiHelper::ToJSHandle(buffer)); \
ecmascript::InternalCallParams *argv = thread->GetInternalCallParams(); \
argv->MakeArgv(arrayBuffer.GetTaggedValue(), JSTaggedValue(byteOffset), JSTaggedValue(length)); \
array_size_t argc = 3; \
JSTaggedValue result = JSFunction::Construct(thread, func, argc, argv->GetArgv(), func); \
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm)); \
JSHandle<JSTaggedValue> resultHandle(thread, result); \
return JSNApiHelper::ToLocal<Type##Ref>(resultHandle); \
}
TYPED_ARRAY_ALL(TYPED_ARRAY_NEW)
#undef TYPED_ARRAY_NEW
// ---------------------------------- TypedArray -----------------------------------
// ---------------------------------- Error ---------------------------------------
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define EXCEPTION_ERROR_NEW(name, type) \
Local<JSValueRef> Exception::name(const EcmaVM *vm, Local<StringRef> message) \
{ \
JSThread *thread = vm->GetJSThread(); \
ObjectFactory *factory = vm->GetFactory(); \
\
JSHandle<EcmaString> messageValue(JSNApiHelper::ToJSHandle(message)); \
JSHandle<JSTaggedValue> result(factory->NewJSError(ErrorType::type, messageValue)); \
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm)); \
return JSNApiHelper::ToLocal<JSValueRef>(result); \
}
EXCEPTION_ERROR_ALL(EXCEPTION_ERROR_NEW)
#undef EXCEPTION_ERROR_NEW
// ---------------------------------- Error ---------------------------------------
// ---------------------------------- JSON ------------------------------------------
Local<JSValueRef> JSON::Parse(const EcmaVM *vm, Local<StringRef> string)
{
JSThread *thread = vm->GetJSThread();
JsonParser parser(thread);
JSHandle<JSTaggedValue> result =
parser.Parse(EcmaString::Cast(JSNApiHelper::ToJSTaggedValue(*string).GetTaggedObject()));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<JSValueRef>(result);
}
Local<JSValueRef> JSON::Stringify(const EcmaVM *vm, Local<JSValueRef> json)
{
JSThread *thread = vm->GetJSThread();
auto constants = thread->GlobalConstants();
JsonStringifier stringifier(thread);
JSHandle<JSTaggedValue> str = stringifier.Stringify(
JSNApiHelper::ToJSHandle(json), constants->GetHandledUndefined(), constants->GetHandledUndefined());
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<JSValueRef>(str);
}
Local<StringRef> RegExpRef::GetOriginalSource(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSRegExp> regExp(JSNApiHelper::ToJSHandle(this));
JSTaggedValue source = regExp->GetOriginalSource();
if (!source.IsString()) {
auto constants = thread->GlobalConstants();
return JSNApiHelper::ToLocal<StringRef>(constants->GetHandledEmptyString());
}
JSHandle<JSTaggedValue> sourceHandle(thread, source);
return JSNApiHelper::ToLocal<StringRef>(sourceHandle);
}
Local<StringRef> DateRef::ToString(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSDate> date(JSNApiHelper::ToJSHandle(this));
JSTaggedValue dateStr = date->ToString(thread);
if (!dateStr.IsString()) {
auto constants = thread->GlobalConstants();
return JSNApiHelper::ToLocal<StringRef>(constants->GetHandledEmptyString());
}
JSHandle<JSTaggedValue> dateStrHandle(thread, dateStr);
return JSNApiHelper::ToLocal<StringRef>(dateStrHandle);
}
int32_t MapRef::GetSize()
{
JSHandle<JSMap> map(JSNApiHelper::ToJSHandle(this));
return map->GetSize();
}
int32_t SetRef::GetSize()
{
JSHandle<JSSet> set(JSNApiHelper::ToJSHandle(this));
return set->GetSize();
}
// ----------------------------------- FunctionCallback ---------------------------------
JSTaggedValue Callback::RegisterCallback(ecmascript::EcmaRuntimeCallInfo *info)
{
// Constructor
JSThread *thread = info->GetThread();
JSHandle<JSTaggedValue> constructor = BuiltinsBase::GetConstructor(info);
if (!constructor->IsJSFunction()) {
return JSTaggedValue::False();
}
JSHandle<JSFunction> function(constructor);
JSHandle<JSTaggedValue> extraInfoValue(thread, function->GetFunctionExtraInfo());
if (!extraInfoValue->IsJSFunctionExtraInfo()) {
return JSTaggedValue::False();
}
JSHandle<JSFunctionExtraInfo> extraInfo(extraInfoValue);
// vm
Region *region = Region::ObjectAddressToRange(extraInfo.GetTaggedValue().GetTaggedObject());
if (region == nullptr) {
return JSTaggedValue::False();
}
EcmaVM *vm = region->GetSpace()->GetHeap()->GetEcmaVM();
// data
JSHandle<JSTaggedValue> data(thread, extraInfo->GetData());
if (!data->IsHeapObject()) {
return JSTaggedValue::False();
}
JSHandle<JSNativePointer> dataObj(data);
// callBack
JSHandle<JSTaggedValue> callBack(thread, extraInfo->GetCallback());
if (!callBack->IsHeapObject()) {
return JSTaggedValue::False();
}
JSHandle<JSNativePointer> callBackObj(callBack);
FunctionCallback nativeFunc = (reinterpret_cast<FunctionCallback>(callBackObj->GetExternalPointer()));
// this
JSHandle<JSTaggedValue> thisValue(BuiltinsBase::GetThis(info));
// arguments
std::vector<Local<JSValueRef>> arguments;
array_size_t length = info->GetArgsNumber();
for (array_size_t i = 0; i < length; ++i) {
arguments.emplace_back(JSNApiHelper::ToLocal<JSValueRef>(BuiltinsBase::GetCallArg(info, i)));
}
Local<JSValueRef> result = nativeFunc(vm,
JSNApiHelper::ToLocal<JSValueRef>(thisValue),
arguments.data(),
arguments.size(),
dataObj->GetExternalPointer());
return JSNApiHelper::ToJSHandle(result).GetTaggedValue();
}
JSTaggedValue Callback::RegisterCallbackWithNewTarget(ecmascript::EcmaRuntimeCallInfo *info)
{
// Constructor
JSThread *thread = info->GetThread();
JSHandle<JSTaggedValue> constructor = BuiltinsBase::GetConstructor(info);
if (!constructor->IsJSFunction()) {
return JSTaggedValue::False();
}
JSHandle<JSFunction> function(constructor);
JSHandle<JSTaggedValue> extraInfoValue(thread, function->GetFunctionExtraInfo());
if (!extraInfoValue->IsJSFunctionExtraInfo()) {
return JSTaggedValue::False();
}
JSHandle<JSFunctionExtraInfo> extraInfo(extraInfoValue);
// vm
Region *region = Region::ObjectAddressToRange(extraInfo.GetTaggedValue().GetTaggedObject());
if (region == nullptr) {
return JSTaggedValue::False();
}
EcmaVM *vm = region->GetSpace()->GetHeap()->GetEcmaVM();
// data
JSHandle<JSTaggedValue> data(thread, extraInfo->GetData());
if (!data->IsHeapObject()) {
return JSTaggedValue::False();
}
JSHandle<JSNativePointer> dataObj(data);
// callBack
JSHandle<JSTaggedValue> callBack(thread, extraInfo->GetCallback());
if (!callBack->IsHeapObject()) {
return JSTaggedValue::False();
}
JSHandle<JSNativePointer> callBackObj(callBack);
FunctionCallbackWithNewTarget nativeFunc =
(reinterpret_cast<FunctionCallbackWithNewTarget>(callBackObj->GetExternalPointer()));
// newTarget
JSHandle<JSTaggedValue> newTarget(BuiltinsBase::GetNewTarget(info));
// this
JSHandle<JSTaggedValue> thisValue(BuiltinsBase::GetThis(info));
// arguments
std::vector<Local<JSValueRef>> arguments;
array_size_t length = info->GetArgsNumber();
for (array_size_t i = 0; i < length; ++i) {
arguments.emplace_back(JSNApiHelper::ToLocal<JSValueRef>(BuiltinsBase::GetCallArg(info, i)));
}
Local<JSValueRef> result = nativeFunc(vm,
JSNApiHelper::ToLocal<JSValueRef>(thisValue),
JSNApiHelper::ToLocal<JSValueRef>(newTarget),
arguments.data(),
arguments.size(),
dataObj->GetExternalPointer());
return JSNApiHelper::ToJSHandle(result).GetTaggedValue();
}
// ------------------------------------- JSExecutionScope ------------------------------
JSExecutionScope::JSExecutionScope(const EcmaVM *vm)
{
(void)vm;
}
JSExecutionScope::~JSExecutionScope()
{
last_current_thread_ = nullptr;
is_revert_ = false;
}
// ----------------------------------- JSValueRef --------------------------------------
Local<PrimitiveRef> JSValueRef::Undefined(const EcmaVM *vm)
{
return JSNApiHelper::ToLocal<PrimitiveRef>(JSHandle<JSTaggedValue>(vm->GetJSThread(), JSTaggedValue::Undefined()));
}
Local<PrimitiveRef> JSValueRef::Null(const EcmaVM *vm)
{
return JSNApiHelper::ToLocal<PrimitiveRef>(JSHandle<JSTaggedValue>(vm->GetJSThread(), JSTaggedValue::Null()));
}
Local<PrimitiveRef> JSValueRef::True(const EcmaVM *vm)
{
return JSNApiHelper::ToLocal<PrimitiveRef>(JSHandle<JSTaggedValue>(vm->GetJSThread(), JSTaggedValue::True()));
}
Local<PrimitiveRef> JSValueRef::False(const EcmaVM *vm)
{
return JSNApiHelper::ToLocal<PrimitiveRef>(JSHandle<JSTaggedValue>(vm->GetJSThread(), JSTaggedValue::False()));
}
Local<JSValueRef> JSValueRef::Exception(const EcmaVM *vm)
{
return JSNApiHelper::ToLocal<JSValueRef>(JSHandle<JSTaggedValue>(vm->GetJSThread(), JSTaggedValue::Exception()));
}
Local<ObjectRef> JSValueRef::ToObject(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
if (IsUndefined() || IsNull()) {
return Exception(vm);
}
JSHandle<JSTaggedValue> obj(JSTaggedValue::ToObject(thread, JSNApiHelper::ToJSHandle(this)));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<ObjectRef>(obj);
}
Local<StringRef> JSValueRef::ToString(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
if (!obj->IsString()) {
obj = JSHandle<JSTaggedValue>(JSTaggedValue::ToString(thread, obj));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
}
return JSNApiHelper::ToLocal<StringRef>(obj);
}
Local<NativePointerRef> JSValueRef::ToNativePointer(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<NativePointerRef>(obj);
}
bool JSValueRef::BooleaValue()
{
return JSNApiHelper::ToJSTaggedValue(this).ToBoolean();
}
int64_t JSValueRef::IntegerValue(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSTaggedNumber number = JSTaggedValue::ToInteger(thread, JSNApiHelper::ToJSHandle(this));
RETURN_VALUE_IF_ABRUPT(thread, 0);
return number.GetNumber();
}
uint32_t JSValueRef::Uint32Value(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
uint32_t number = JSTaggedValue::ToUint32(thread, JSNApiHelper::ToJSHandle(this));
RETURN_VALUE_IF_ABRUPT(thread, 0);
return number;
}
int32_t JSValueRef::Int32Value(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
int32_t number = JSTaggedValue::ToInt32(thread, JSNApiHelper::ToJSHandle(this));
RETURN_VALUE_IF_ABRUPT(thread, 0);
return number;
}
Local<BooleanRef> JSValueRef::ToBoolean(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> booleanObj = JSHandle<JSTaggedValue>(thread, JSTaggedValue(obj->ToBoolean()));
return JSNApiHelper::ToLocal<BooleanRef>(booleanObj);
}
Local<NumberRef> JSValueRef::ToNumber(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> number(thread, JSTaggedValue::ToNumber(thread, obj));
RETURN_VALUE_IF_ABRUPT(thread, JSValueRef::Exception(vm));
return JSNApiHelper::ToLocal<NumberRef>(number);
}
bool JSValueRef::IsStrictEquals(const EcmaVM *vm, Local<JSValueRef> value)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> xValue = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> yValue = JSNApiHelper::ToJSHandle(value);
return JSTaggedValue::StrictEqual(thread, xValue, yValue);
}
Local<StringRef> JSValueRef::Typeof(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
JSTaggedValue value = FastRuntimeStub::FastTypeOf(thread, JSNApiHelper::ToJSTaggedValue(this));
return JSNApiHelper::ToLocal<StringRef>(JSHandle<JSTaggedValue>(thread, value));
}
bool JSValueRef::InstanceOf(const EcmaVM *vm, Local<JSValueRef> value)
{
JSThread *thread = vm->GetJSThread();
JSHandle<JSTaggedValue> origin = JSNApiHelper::ToJSHandle(this);
JSHandle<JSTaggedValue> target = JSNApiHelper::ToJSHandle(value);
bool result = JSObject::InstanceOf(thread, origin, target);
RETURN_VALUE_IF_ABRUPT(thread, false);
return result;
}
bool JSValueRef::IsUndefined()
{
return JSNApiHelper::ToJSTaggedValue(this).IsUndefined();
}
bool JSValueRef::IsNull()
{
return JSNApiHelper::ToJSTaggedValue(this).IsNull();
}
bool JSValueRef::IsHole()
{
return JSNApiHelper::ToJSTaggedValue(this).IsHole();
}
bool JSValueRef::IsTrue()
{
return JSNApiHelper::ToJSTaggedValue(this).IsTrue();
}
bool JSValueRef::IsFalse()
{
return JSNApiHelper::ToJSTaggedValue(this).IsFalse();
}
bool JSValueRef::IsNumber()
{
return JSNApiHelper::ToJSTaggedValue(this).IsNumber();
}
bool JSValueRef::IsInt()
{
return JSNApiHelper::ToJSTaggedValue(this).IsInt();
}
bool JSValueRef::WithinInt32()
{
return JSNApiHelper::ToJSTaggedValue(this).WithinInt32();
}
bool JSValueRef::IsBoolean()
{
return JSNApiHelper::ToJSTaggedValue(this).IsBoolean();
}
bool JSValueRef::IsString()
{
return JSNApiHelper::ToJSTaggedValue(this).IsString();
}
bool JSValueRef::IsSymbol()
{
return JSNApiHelper::ToJSTaggedValue(this).IsSymbol();
}
bool JSValueRef::IsObject()
{
return JSNApiHelper::ToJSTaggedValue(this).IsECMAObject();
}
bool JSValueRef::IsArray(const EcmaVM *vm)
{
JSThread *thread = vm->GetJSThread();
return JSNApiHelper::ToJSTaggedValue(this).IsArray(thread);
}
bool JSValueRef::IsConstructor()
{
JSTaggedValue value = JSNApiHelper::ToJSTaggedValue(this);
return value.IsHeapObject() && value.IsConstructor();
}
bool JSValueRef::IsFunction()
{
JSTaggedValue value = JSNApiHelper::ToJSTaggedValue(this);
return value.IsHeapObject() && value.IsCallable();
}
bool JSValueRef::IsProxy()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSProxy();
}
bool JSValueRef::IsException()
{
return JSNApiHelper::ToJSTaggedValue(this).IsException();
}
bool JSValueRef::IsPromise()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSPromise();
}
bool JSValueRef::IsDataView()
{
return JSNApiHelper::ToJSTaggedValue(this).IsDataView();
}
bool JSValueRef::IsTypedArray()
{
return JSNApiHelper::ToJSTaggedValue(this).IsTypedArray();
}
bool JSValueRef::IsNativePointer()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSNativePointer();
}
bool JSValueRef::IsNativeObject()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSNativeObject();
}
bool JSValueRef::IsDate()
{
return JSNApiHelper::ToJSTaggedValue(this).IsDate();
}
bool JSValueRef::IsError()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSError();
}
bool JSValueRef::IsMap()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSMap();
}
bool JSValueRef::IsSet()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSSet();
}
bool JSValueRef::IsWeakMap()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSWeakMap();
}
bool JSValueRef::IsWeakSet()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSWeakSet();
}
bool JSValueRef::IsRegExp()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSRegExp();
}
bool JSValueRef::IsArrayIterator()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSArrayIterator();
}
bool JSValueRef::IsStringIterator()
{
return JSNApiHelper::ToJSTaggedValue(this).IsStringIterator();
}
bool JSValueRef::IsSetIterator()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSSetIterator();
}
bool JSValueRef::IsMapIterator()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSMapIterator();
}
bool JSValueRef::IsArrayBuffer()
{
return JSNApiHelper::ToJSTaggedValue(this).IsArrayBuffer();
}
bool JSValueRef::IsUint8Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSUint8Array();
}
bool JSValueRef::IsInt8Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSInt8Array();
}
bool JSValueRef::IsUint8ClampedArray()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSUint8ClampedArray();
}
bool JSValueRef::IsInt16Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSInt16Array();
}
bool JSValueRef::IsUint16Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSUint16Array();
}
bool JSValueRef::IsInt32Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSInt32Array();
}
bool JSValueRef::IsUint32Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSUint32Array();
}
bool JSValueRef::IsFloat32Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSFloat32Array();
}
bool JSValueRef::IsFloat64Array()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSFloat64Array();
}
bool JSValueRef::IsJSPrimitiveRef()
{
return JSNApiHelper::ToJSTaggedValue(this).IsJSPrimitiveRef();
}
bool JSValueRef::IsJSPrimitiveNumber()
{
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
return JSPrimitiveRef::Cast(obj->GetHeapObject())->IsNumber();
}
bool JSValueRef::IsJSPrimitiveInt()
{
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
return JSPrimitiveRef::Cast(obj->GetHeapObject())->IsInt();
}
bool JSValueRef::IsJSPrimitiveBoolean()
{
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
return JSPrimitiveRef::Cast(obj->GetHeapObject())->IsBoolean();
}
bool JSValueRef::IsJSPrimitiveString()
{
JSHandle<JSTaggedValue> obj = JSNApiHelper::ToJSHandle(this);
return JSPrimitiveRef::Cast(obj->GetHeapObject())->IsString();
}
} // namespace panda
|
//
// stream_client.cpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "asio.hpp"
#if defined(ASIO_HAS_LOCAL_SOCKETS)
using asio::local::stream_protocol;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: stream_client <file>\n";
return 1;
}
asio::io_service io_service;
stream_protocol::socket s(io_service);
s.connect(stream_protocol::endpoint(argv[1]));
using namespace std; // For strlen.
std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = strlen(request);
asio::write(s, asio::buffer(request, request_length));
char reply[max_length];
size_t reply_length = asio::read(s,
asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
#else // defined(ASIO_HAS_LOCAL_SOCKETS)
# error Local sockets not available on this platform.
#endif // defined(ASIO_HAS_LOCAL_SOCKETS)
|
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
const double PI=acos(-1.0);
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define MP(x, y) make_pair(x, y)
#define SZ(c) (int)c.size()
#define PB(x) push_back(x)
#define F(i,L,R) for (int i = L; i < R; i++)
#define FF(i,L,R) for (int i = L; i <= R; i++)
#define FR(i,L,R) for (int i = L; i > R; i--)
#define FRF(i,L,R) for (int i = L; i >= R; i--)
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define ALL(p) p.begin(),p.end()
#define ALLR(p) p.rbegin(),p.rend()
#define SET(p) memset(p, -1, sizeof(p))
#define CLR(p) memset(p, 0, sizeof(p))
#define MEM(p, v) memset(p, v, sizeof(p))
#define CPY(d, s) memcpy(d, s, sizeof(s))
#define getI(a) scanf("%d", &a)
#define getII(a,b) scanf("%d%d", &a, &b)
#define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c)
#define getC(n) scanf("%c",&n)
#define getL(n) scanf("%I64d",&n)
#define getF(n) scanf("%lf",&n)
#define getS(n) scanf("%s",n)
#define vi vector < int >
#define vii vector < vector < int > >
#define pii pair< int, int >
#define psi pair< string, int >
#define ff first
#define ss second
#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define ld long double
#define debug(a) { cout << a <<endl; }
#define debugI() { cout << "*" <<endl; }
#define debugII() { cout << "**" <<endl; }
#define debugIII() { cout << "***" <<endl; }
template< class T > inline T _abs(T n) { return ((n) < 0 ? -(n) : (n)); }
template< class T > inline T _max(T a, T b) { return (!((a)<(b))?(a):(b)); }
template< class T > inline T _min(T a, T b) { return (((a)<(b))?(a):(b)); }
template< class T > inline T _swap(T &a, T &b) { a=a^b;b=a^b;a=a^b;}
template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); }
int brk[]={1,6,1,2,2,3,1,4,0,1};
int main() {
//READ("in.txt");
//WRITE("out.txt");
int a,b;
while(~getII(a,b))
{
int x=0,y=0,x1,y1;
int c=1;
int cnt=0;
for(int i=0;;i++)
{
if(i%4==0)
{
x1=x+c;
y1=y;
}
else if(i%4==1)
{
x1=x;
y1=y+c;
}
else if(i%4==2)
{
x1=x-c;
y1=y;
}
else if(i%4==3)
{
x1=x;
y1=y-c;
}
if(i%2==0) c++;
cout << x << " " << y << " " <<x1 <<" "<<y1 <<endl;
if(a>=x && a<=x1 && b>=y && b<=y1) break;
cnt++;
x=x1;
y=y1;
}
debug(cnt);
}
return 0;
}
|
#include "stdafx.h"
#include "FFMpegPlayer.h"
#include "utils/utils.h"
#include "utils/InterConnector.h"
#include "main_window/sounds/SoundsManager.h"
#include "FrameRenderer.h"
#ifdef __WIN32__
#include "win32/WindowRenderer.h"
#endif //__WIN32__
Q_LOGGING_CATEGORY(ffmpegPlayer, "ffmpegPlayer")
namespace
{
double currentTimeInSeconds()
{
return (double)ffmpeg::av_gettime() / 1000000.0;
}
constexpr bool isCompressedType(Ui::thread_message_type _type) noexcept
{
return _type == Ui::thread_message_type::tmt_get_next_video_frame;
}
void alignedImageBufferCleanupHandler(void* data)
{
auto buffer = static_cast<uchar*>(data);
delete[] buffer;
}
QImage createAlignedImage(QSize size, const int _align)
{
const auto width = size.width();
const auto height = size.height();
const auto widthalign = _align / 4;
const auto neededwidth = width + ((width % widthalign) ? (widthalign - (width % widthalign)) : 0);
const auto bytesperline = neededwidth * 4;
auto buffer = new uchar[bytesperline * height + _align];
auto cleanupdata = static_cast<void*>(buffer);
auto bufferval = reinterpret_cast<uintptr_t>(buffer);
auto alignedbuffer = buffer + ((bufferval % _align) ? (_align - (bufferval % _align)) : 0);
return QImage(alignedbuffer, width, height, bytesperline, QImage::Format_ARGB32, alignedImageBufferCleanupHandler, cleanupdata);
}
bool isAlignedImage(const QImage& image, const int _align)
{
return !(reinterpret_cast<uintptr_t>(image.constBits()) % _align) && !(image.bytesPerLine() % _align);
}
constexpr std::chrono::milliseconds onDataReadyTimeout() noexcept { return std::chrono::milliseconds(50); }
}
class AVCodecScope
{
public:
AVCodecScope()
{
ffmpeg::av_register_all();
ffmpeg::avcodec_register_all();
}
~AVCodecScope() { }
} g_AVCodecScope;
struct RLottieCacheDisable
{
RLottieCacheDisable()
{
rlottie::configureModelCacheSize(0);
}
} g_LottieCacheDisabler;
namespace Ui
{
constexpr int32_t maxQueueSize(1024 * 1024 * 15);
constexpr int32_t minFramesCount(25);
static ffmpeg::AVPacket flush_pkt_data;
bool isFlushPacket(const ffmpeg::AVPacket& _packet)
{
return _packet.data == (uint8_t*)&flush_pkt_data;
}
static ffmpeg::AVPacket quit_pkt;
bool isQuitPacket(const ffmpeg::AVPacket& _packet)
{
return _packet.data == (uint8_t*)&quit_pkt;
}
constexpr int64_t empty_pts = -1000000;
bool ThreadMessagesQueue::getMessage(ThreadMessage& _message, std::function<bool()> _isQuit, int32_t _wait_timeout)
{
condition_.tryAcquire(1, _wait_timeout);
decltype(messages_) tmpList;
{
std::scoped_lock lock(queue_mutex_);
if (_isQuit() || messages_.empty())
return false;
tmpList.splice(tmpList.cbegin(), messages_, messages_.cbegin());
}
_message = std::move(tmpList.front());
return true;
}
bool ThreadMessagesQueue::getAllMessages(ThreadMessageList& _messages, std::function<bool()> _isQuit, int32_t _wait_timeout)
{
condition_.tryAcquire(1, _wait_timeout);
decltype(messages_) tmpList;
{
std::scoped_lock lock(queue_mutex_);
if (_isQuit() || messages_.empty())
return false;
_messages = std::exchange(messages_, std::move(tmpList));
}
return true;
}
void ThreadMessagesQueue::pushMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
decltype(messages_) tmpList;
tmpList.push_back(_message);
const auto compressedType = isCompressedType(_message.message_);
{
std::scoped_lock lock(queue_mutex_);
const auto skipMessage = compressedType && std::any_of(messages_.cbegin(), messages_.cend(),
[&_message](const auto& x)
{
return x.videoId_ == _message.videoId_ && x.message_ == _message.message_;
});
if (!skipMessage)
{
if (_clear_others)
messages_.remove_if([id = _message.videoId_](const auto& x) { return x.videoId_ == id; });
messages_.splice(_forward ? messages_.cbegin() : messages_.cend(), tmpList, tmpList.cbegin());
}
}
condition_.release(1);
}
void ThreadMessagesQueue::clear()
{
decltype(messages_) tmpList;
{
std::scoped_lock lock(queue_mutex_);
tmpList.splice(tmpList.cbegin(), messages_);
}
}
//////////////////////////////////////////////////////////////////////////
// PacketQueue
//////////////////////////////////////////////////////////////////////////
PacketQueue::PacketQueue()
: packets_(0),
size_(0)
{
}
PacketQueue::~PacketQueue()
{
freeData();
}
void PacketQueue::freeData(std::function<void(ffmpeg::AVPacket& _packet)> _callback)
{
std::scoped_lock locker(mutex_);
for (auto iter = list_.begin(); iter != list_.end(); ++iter)
{
if (_callback)
_callback(*iter);
if (iter->data && !isFlushPacket(*iter) && !isQuitPacket(*iter))
ffmpeg::av_packet_unref(&(*iter));
}
list_.clear();
size_ = 0;
packets_ = 0;
}
void PacketQueue::push(ffmpeg::AVPacket* _packet)
{
decltype(list_) tmpList;
tmpList.push_back(*_packet);
{
std::scoped_lock locker(mutex_);
list_.splice(list_.end(), tmpList, tmpList.begin());
++packets_;
if (!isFlushPacket(*_packet))
size_ += _packet->size;
}
}
bool PacketQueue::get(/*out*/ ffmpeg::AVPacket& _packet)
{
decltype(list_) tmpList;
{
std::scoped_lock locker(mutex_);
if (list_.empty())
return false;
tmpList.splice(tmpList.begin(), list_, list_.begin());
--packets_;
size_ -= tmpList.front().size;
}
_packet = tmpList.front();
return true;
}
int32_t PacketQueue::getSize() const
{
return size_;
}
int32_t PacketQueue::getPackets() const
{
return packets_;
}
MediaData::MediaData()
: videoQueue_(QSharedPointer<PacketQueue>::create())
, audioQueue_(QSharedPointer<PacketQueue>::create())
{
}
//////////////////////////////////////////////////////////////////////////
// VideoContext
//////////////////////////////////////////////////////////////////////////
VideoContext::VideoContext()
: quit_(false)
, curr_id_(0)
{
QObject::connect(this, &VideoContext::audioQuit, this, &VideoContext::onAudioQuit);
QObject::connect(this, &VideoContext::videoQuit, this, &VideoContext::onVideoQuit);
QObject::connect(this, &VideoContext::demuxQuit, this, &VideoContext::onDemuxQuit);
QObject::connect(this, &VideoContext::streamsClosed, this, &VideoContext::onStreamsClosed);
}
VideoContext::~VideoContext() = default;
void VideoContext::init(MediaData& _media)
{
ffmpeg::AVPacket flush_pkt_v, flush_pkt_a;
initFlushPacket(flush_pkt_a);
initFlushPacket(flush_pkt_v);
pushVideoPacket(&flush_pkt_v, _media);
pushAudioPacket(&flush_pkt_a, _media);
}
uint32_t VideoContext::addVideo(uint32_t _id)
{
const auto id = _id == 0 ? reserveId() : _id;
{
auto mediaData = std::make_shared<MediaData>();
std::scoped_lock lock(mediaDataMutex_);
mediaData_[id] = std::move(mediaData);
}
{
std::scoped_lock lock(activeVideosMutex_);
activeVideos_[id] = true;
}
return id;
}
uint32_t VideoContext::reserveId()
{
return ++curr_id_;
}
void VideoContext::deleteVideo(uint32_t _videoId)
{
{
std::scoped_lock lock(mediaDataMutex_);
mediaData_.erase(_videoId);
}
{
std::scoped_lock lock(activeVideosMutex_);
activeVideos_.erase(_videoId);
}
getMediaContainer()->stopMedia(_videoId);
}
ffmpeg::AVStream* VideoContext::openStream(int32_t _type, ffmpeg::AVFormatContext* _context)
{
ffmpeg::AVStream* stream = 0;
im_assert(_context);
int32_t streamIndex = ffmpeg::av_find_best_stream(_context, (ffmpeg::AVMediaType) _type, -1, -1, NULL, 0);
if (streamIndex < 0)
{
return 0;
}
stream = _context->streams[streamIndex];
ffmpeg::AVCodecContext* codecContext = stream->codec;
// Find suitable codec
ffmpeg::AVCodec* codec = ffmpeg::avcodec_find_decoder(codecContext->codec_id);
if (!codec)
{
// Codec not found
return 0;
}
if (avcodec_open2(codecContext, codec, 0) < 0)
{
// Failed to open codec
return 0;
}
return stream;
}
void VideoContext::closeStream(ffmpeg::AVStream* _stream)
{
if (_stream && _stream->codec)
{
avcodec_close(_stream->codec);
}
}
int32_t VideoContext::getVideoStreamIndex(MediaData& _media) const
{
return _media.videoStream_ ? _media.videoStream_->index : 0;
}
int32_t VideoContext::getAudioStreamIndex(MediaData& _media) const
{
if (_media.audioStream_)
return _media.audioStream_->index;
return -1;
}
bool VideoContext::isQuit() const
{
return quit_;
}
bool VideoContext::isVideoQuit(int _videoId) const
{
std::scoped_lock lock(activeVideosMutex_);
const auto it = std::as_const(activeVideos_).find(_videoId);
if (it == std::as_const(activeVideos_).end())
return false;
return !it->second;
}
void VideoContext::setVideoQuit(int _videoId)
{
std::scoped_lock lock(activeVideosMutex_);
const auto it = activeVideos_.find(_videoId);
if (it != activeVideos_.end())
it->second = false;
}
void VideoContext::setQuit(bool _val)
{
quit_ = _val;
}
int32_t VideoContext::readAVPacket(/*OUT*/ffmpeg::AVPacket* _packet, MediaData& _media)
{
return ffmpeg::av_read_frame(_media.formatContext_, _packet);
}
int32_t VideoContext::readAVPacketPause(MediaData& _media)
{
return ffmpeg::av_read_pause(_media.formatContext_);
}
int32_t VideoContext::readAVPacketPlay(MediaData& _media)
{
return ffmpeg::av_read_play(_media.formatContext_);
}
bool VideoContext::isEof(int32_t _error, MediaData& _media)
{
return (_error == AVERROR_EOF || ffmpeg::avio_feof(_media.formatContext_->pb));
}
bool VideoContext::isStreamError(MediaData& _media)
{
if (_media.formatContext_->pb && _media.formatContext_->pb->error)
{
im_assert(false);
return true;
}
return false;
}
void VideoContext::initFlushPacket(ffmpeg::AVPacket& _packet)
{
ffmpeg::av_init_packet(&_packet);
_packet.data = (uint8_t*)&flush_pkt_data;
_packet.dts = empty_pts;
_packet.pts = empty_pts;
_packet.size = 0;
}
bool VideoContext::getNextVideoFrame(/*OUT*/ffmpeg::AVFrame* _frame, ffmpeg::AVPacket* _packet, VideoData& _videoData, MediaData& _media, uint32_t _videoId)
{
if (!_media.videoStream_)
return false;
ffmpeg::AVCodecContext* videoCodecContext = _media.videoStream_->codec;
while (!isVideoQuit(_videoId))
{
if (!_videoData.stream_finished_)
{
if (!_media.videoQueue_->get(*_packet))
continue;
}
if (isFlushPacket(*_packet))
{
if (_packet->dts != empty_pts)
{
_media.seek_position_ = _packet->dts;
Q_EMIT seekedV(_videoId);
}
flushVideoBuffers(_media);
continue;
}
if (isQuitPacket(*_packet))
return false;
if (!_packet->data)
_videoData.stream_finished_ = true;
int got_frame = 0;
int len = ffmpeg::avcodec_decode_video2(videoCodecContext, _frame, &got_frame, _packet);
if (_packet->data)
ffmpeg::av_packet_unref(_packet);
if (len < 0)
return false;
if (got_frame)
{
if (_media.seek_position_ > 0)
{
if (_frame->pkt_dts < _media.seek_position_)
{
ffmpeg::av_frame_unref(_frame);
continue;
}
}
_media.seek_position_ = 0;
return true;
}
else if (_videoData.stream_finished_)
{
_videoData.eof_ = true;
return false;
}
}
return false;
}
void pushNullPacket(PacketQueue& _queue, int32_t _streamIndex)
{
ffmpeg::AVPacket pkt1, *pkt = &pkt1;
ffmpeg::av_init_packet(pkt);
pkt->data = NULL;
pkt->size = 0;
pkt->stream_index = _streamIndex;
_queue.push(pkt);
}
void VideoContext::pushVideoPacket(ffmpeg::AVPacket* _packet, MediaData& _media)
{
if (!_packet)
return pushNullPacket(*(_media.videoQueue_), getVideoStreamIndex(_media));
return _media.videoQueue_->push(_packet);
}
int32_t VideoContext::getVideoQueuePackets(MediaData& _media) const
{
return _media.videoQueue_->getPackets();
}
int32_t VideoContext::getVideoQueueSize(MediaData& _media) const
{
return _media.videoQueue_->getSize();
}
void VideoContext::pushAudioPacket(ffmpeg::AVPacket* _packet, MediaData& _media)
{
if (!_packet)
return pushNullPacket((*_media.audioQueue_), getAudioStreamIndex(_media));
return _media.audioQueue_->push(_packet);
}
int32_t VideoContext::getAudioQueuePackets(MediaData& _media) const
{
return _media.audioQueue_->getPackets();
}
int32_t VideoContext::getAudioQueueSize(MediaData& _media) const
{
return _media.audioQueue_->getSize();
}
void VideoContext::clearAudioQueue(MediaData& _media)
{
_media.audioQueue_->freeData();
}
void VideoContext::clearVideoQueue(MediaData& _media)
{
_media.videoQueue_->freeData();
}
void VideoContext::cleanupOnExit()
{
std::scoped_lock lock(mediaDataMutex_);
for (const auto& [id, data] : mediaData_)
{
qCDebug(ffmpegPlayer) << "cleanup active media id = " << id;
clearAudioQueue(*data);
clearVideoQueue(*data);
if (data->streamClosed_)
continue;
data->streamClosed_ = true;
closeFile(*data);
}
}
QImage VideoContext::getFirstFrame(const QString& _file)
{
static std::mutex firstFrameMutex_;
std::scoped_lock lock(firstFrameMutex_);
QImage result;
ffmpeg::AVFormatContext* ctx = nullptr;
ffmpeg::AVStream* videoStream = nullptr;
ffmpeg::AVCodecContext* codecContext = nullptr;
do
{
int32_t err = ffmpeg::avformat_open_input(&ctx, _file.toStdString().c_str(), 0, 0);
if (err < 0)
break;
err = ffmpeg::avformat_find_stream_info(ctx, 0);
if (err < 0)
break;
videoStream = openStream(ffmpeg::AVMEDIA_TYPE_VIDEO, ctx);
if (!videoStream)
break;
codecContext = videoStream->codec;
ffmpeg::AVDictionary* dictionary = videoStream->metadata;
int32_t rotation = 0;
if (dictionary)
{
ffmpeg::AVDictionaryEntry* entryRotate = ffmpeg::av_dict_get(dictionary, "rotate", 0, AV_DICT_IGNORE_SUFFIX);
if (entryRotate && entryRotate->value && entryRotate->value[0] != '\0')
{
rotation = QString::fromLatin1(entryRotate->value).toInt();
}
}
int32_t width = codecContext->width;
int32_t height = codecContext->height;
int32_t videoStreamIndex = videoStream->index;
ffmpeg::AVPacket packet;
ffmpeg::AVFrame* frame = ffmpeg::av_frame_alloc();
while (ffmpeg::av_read_frame(ctx, &packet) >= 0)
{
if (packet.stream_index == videoStreamIndex)
{
int got_frame = 0;
int len = ffmpeg::avcodec_decode_video2(codecContext, frame, &got_frame, &packet);
if (len < 0)
{
ffmpeg::av_packet_unref(&packet);
break;
}
if (got_frame)
{
QSize scaledSize(width, height);
int align = 256;
while (1)
{
if (frame->linesize[0] % align == 0)
break;
align = align / 2;
}
ffmpeg::AVFrame* frameRGB = ffmpeg::av_frame_alloc();
int numBytes = ffmpeg::av_image_get_buffer_size(ffmpeg::AV_PIX_FMT_RGBA, scaledSize.width(), scaledSize.height(), align);
std::vector<uint8_t> scaledBuffer(numBytes);
av_image_fill_arrays(frameRGB->data, frameRGB->linesize, &scaledBuffer[0], ffmpeg::AV_PIX_FMT_RGBA, scaledSize.width(), scaledSize.height(), align);
ffmpeg::SwsContext* swsContext = nullptr;
swsContext = sws_getCachedContext(swsContext, frame->width, frame->height, ffmpeg::AVPixelFormat(frame->format), scaledSize.width(), scaledSize.height(), ffmpeg::AV_PIX_FMT_RGBA, SWS_POINT, 0, 0, 0);
ffmpeg::sws_scale(swsContext, frame->data, frame->linesize, 0, frame->height, frameRGB->data, frameRGB->linesize);
QImage lastFrame(scaledSize.width(), scaledSize.height(), QImage::Format_RGBA8888);
for (int32_t y = 0; y < scaledSize.height(); ++y)
{
memcpy(lastFrame.scanLine(y), frameRGB->data[0] + y * frameRGB->linesize[0], scaledSize.width() * 4);
}
if (rotation)
{
lastFrame = lastFrame.transformed(QTransform().rotate(rotation));
}
result = lastFrame;
ffmpeg::av_frame_unref(frameRGB);
ffmpeg::av_frame_free(&frameRGB);
sws_freeContext(swsContext);
ffmpeg::av_packet_unref(&packet);
break;
}
}
ffmpeg::av_packet_unref(&packet);
}
ffmpeg::av_frame_unref(frame);
ffmpeg::av_frame_free(&frame);
} while (false);
if (videoStream)
closeStream(videoStream);
if (ctx)
avformat_close_input(&ctx);
return result;
}
int64_t VideoContext::getDuration(const QString& _file)
{
static std::mutex durationMutext;
std::scoped_lock lock(durationMutext);
int64_t result = -1;
ffmpeg::AVFormatContext* ctx = nullptr;
do
{
int32_t err = ffmpeg::avformat_open_input(&ctx, _file.toStdString().c_str(), 0, 0);
if (err < 0)
break;
err = ffmpeg::avformat_find_stream_info(ctx, 0);
if (err < 0)
break;
result = ctx->duration / AV_TIME_BASE;
} while (false);
if (ctx)
avformat_close_input(&ctx);
return result;
}
bool VideoContext::getGotAudio(const QString& _file)
{
static std::mutex gotAudioMutext;
std::scoped_lock lock(gotAudioMutext);
bool result = true;
ffmpeg::AVFormatContext* ctx = nullptr;
int32_t err = ffmpeg::avformat_open_input(&ctx, _file.toStdString().c_str(), 0, 0);
if (err >= 0)
{
int32_t streamIndex = ffmpeg::av_find_best_stream(ctx, ffmpeg::AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
result = streamIndex >= 0;
}
if (ctx)
avformat_close_input(&ctx);
return result;
}
bool VideoContext::openStreams(uint32_t _mediaId, const QString& _file, MediaData& _media)
{
//qDebug() << "openStreams " << _mediaId;
int32_t err = 0;
if (_media.isLottie_)
{
_media.lottieRenderer_ = LottieHandleCache::instance().getHandle(_file);
if (!_media.lottieRenderer_)
{
Q_EMIT streamsOpenFailed(_mediaId);
return false;
}
_media.duration_ = std::ceil(_media.lottieRenderer_->duration());
_media.videoClock_ = 1. / _media.lottieRenderer_->frameRate();
_media.frameLastDelay_ = _media.videoClock_;
_media.size_ = _media.lottieRenderer_.originalSize();
_media.scaledSize_ = _media.size_;
}
else
{
err = ffmpeg::avformat_open_input(&_media.formatContext_, _file.toStdString().c_str(), 0, 0);
if (err < 0)
{
Q_EMIT streamsOpenFailed(_mediaId);
return false;
}
// Retrieve stream information
err = ffmpeg::avformat_find_stream_info(_media.formatContext_, 0);
if (err < 0)
{
Q_EMIT streamsOpenFailed(_mediaId);
return false;
}
// Open video and audio streams
_media.videoStream_ = openStream(ffmpeg::AVMEDIA_TYPE_VIDEO, _media.formatContext_);
if (!_media.videoStream_)
{
Q_EMIT streamsOpenFailed(_mediaId);
return false;
}
_media.codecContext_ = _media.videoStream_->codec;
_media.audioStream_ = openStream(ffmpeg::AVMEDIA_TYPE_AUDIO, _media.formatContext_);
}
Q_EMIT streamsOpened(_mediaId);
return true;
}
bool VideoContext::openFile(MediaData& _media)
{
if (_media.isLottie_)
{
if (!_media.lottieRenderer_)
return false;
}
else
{
// Create conversion context
ffmpeg::AVCodecContext* videoCodecContext = _media.videoStream_->codec;
ffmpeg::AVDictionary* dictionary = _media.videoStream_->metadata;
if (dictionary)
{
ffmpeg::AVDictionaryEntry* entryRotate = ffmpeg::av_dict_get(dictionary, "rotate", 0, AV_DICT_IGNORE_SUFFIX);
if (entryRotate && entryRotate->value && entryRotate->value[0] != '\0')
{
_media.rotation_ = QString::fromLatin1(entryRotate->value).toInt();
}
}
_media.size_ = { videoCodecContext->width, videoCodecContext->height };
_media.duration_ = _media.formatContext_->duration / (AV_TIME_BASE / 1000);
_media.scaledSize_ = _media.size_;
}
resetFrameTimer(_media);
return true;
}
void VideoContext::closeFile(MediaData& _media)
{
if (_media.isLottie_)
{
_media.lottieRenderer_ = LottieHandle();
}
else
{
closeStream(_media.audioStream_);
closeStream(_media.videoStream_);
_media.audioStream_ = nullptr;
_media.videoStream_ = nullptr;
if (_media.formatContext_)
avformat_close_input(&_media.formatContext_);
}
}
int32_t VideoContext::getWidth(MediaData& _media) const
{
return _media.size_.width();
}
int32_t VideoContext::getHeight(MediaData& _media) const
{
return _media.size_.height();
}
int32_t VideoContext::getRotation(MediaData& _media) const
{
return _media.rotation_;
}
int64_t VideoContext::getDuration(MediaData& _media) const
{
return _media.duration_;
}
QSize VideoContext::getSourceSize(MediaData& _media) const
{
return _media.size_;
}
QSize VideoContext::getTargetSize(MediaData& _media) const
{
return _media.scaledSize_;
}
double VideoContext::getVideoTimebase(MediaData& _media)
{
return ffmpeg::av_q2d(_media.videoStream_->time_base);
}
double VideoContext::getAudioTimebase(MediaData& _media)
{
return ffmpeg::av_q2d(_media.audioStream_->time_base);
}
double VideoContext::synchronizeVideo(ffmpeg::AVFrame* _frame, double _pts, MediaData& _media)
{
ffmpeg::AVCodecContext* videoCodecContext = _media.videoStream_->codec;
if (_pts > std::numeric_limits<double>::epsilon())
{
/* if we have pts, set video clock to it */
_media.videoClock_ = _pts;
}
else
{
/* if we aren't given a pts, set it to the clock */
_pts = _media.videoClock_;
}
/* update the video clock */
double frameDelay = ffmpeg::av_q2d(videoCodecContext->time_base);
/* if we are repeating a frame, adjust clock accordingly */
frameDelay += _frame->repeat_pict * (frameDelay * 0.5);
_media.videoClock_ += frameDelay;
return _pts;
}
double VideoContext::computeDelay(double _picturePts, MediaData& _media)
{
if (_media.isLottie_)
{
const auto delay = std::max(_media.videoClock_, 0.01);
_media.frameTimer_ += delay;
_media.frameLastDelay_ = delay;
return delay;
}
double delay = _picturePts - _media.frameLastPts_;
if (std::exchange(_media.frameLastPtsReset_, false) || delay <= 0.0 || delay >= 10.0)
{
qCDebug(ffmpegPlayer) << "!!! delay incorrect" << delay << "->" << _media.frameLastDelay_;
// Delay is incorrect or last frame pts was reset - use previous one
delay = _media.frameLastDelay_;
}
// Save for next time
_media.frameLastPts_ = _picturePts;
_media.frameLastDelay_ = delay;
_media.frameTimer_ += delay;
qCDebug(ffmpegPlayer) << "media frame timer = " << int(_media.frameTimer_);
double actual_delay = _media.frameTimer_ - currentTimeInSeconds();
int64_t current_time = ffmpeg::av_gettime();
qCDebug(ffmpegPlayer) << "actual delay = " << int(actual_delay * 1000.0);
if (_media.syncWithAudio_)
{
int64_t timeDiff = current_time - _media.audioClockTime_;
double timeDiff_d = ((double)timeDiff) / (double)1000000.0;
double pts_audio = _media.audioClock_ + timeDiff_d;
qCDebug(ffmpegPlayer) << "_picture_pts = " << int(_picturePts * 1000.0);
qCDebug(ffmpegPlayer) << "pts_audio = " << int(pts_audio * 1000.0);
double diff = _picturePts - pts_audio;
if (fabs(diff) > 0.010)
{
double correction = std::min(fabs(actual_delay * 0.1), fabs(diff));
if (diff < 0.0)
correction *= -1.0;
actual_delay += correction;
_media.frameTimer_ += correction;
qCDebug(ffmpegPlayer) << "sync with audio diff = " << int(diff * 1000.0);
qCDebug(ffmpegPlayer) << "actual delay after corrections = " << int(actual_delay * 1000.0);
}
}
return std::max(actual_delay, 0.01);
}
bool VideoContext::initDecodeAudioData(MediaData& _media)
{
if (!_media.hasAudio())
return true;
_media.audioData_.frame_ = ffmpeg::av_frame_alloc();
// Generate some AL Buffers for streaming
openal::alGenBuffers(audio::num_buffers, _media.audioData_.uiBuffers_);
// Generate a Source to playback the Buffers
openal::alGenSources(1, &_media.audioData_.uiSource_);
_media.audioData_.audioCodecContext_ = _media.audioStream_->codec;
_media.audioData_.layout_ = _media.audioData_.audioCodecContext_->channel_layout;
_media.audioData_.channels_ = _media.audioData_.audioCodecContext_->channels;
_media.audioData_.freq_ = _media.audioData_.audioCodecContext_->sample_rate;
if (_media.audioData_.layout_ == 0 && _media.audioData_.channels_ > 0)
{
if (_media.audioData_.channels_ == 1)
_media.audioData_.layout_ = AV_CH_LAYOUT_MONO;
else
_media.audioData_.layout_ = AV_CH_LAYOUT_STEREO;
}
ffmpeg::AVSampleFormat inputFormat = _media.audioData_.audioCodecContext_->sample_fmt;
switch (_media.audioData_.layout_)
{
case AV_CH_LAYOUT_MONO:
switch (inputFormat)
{
case ffmpeg::AV_SAMPLE_FMT_U8:
case ffmpeg::AV_SAMPLE_FMT_U8P:
_media.audioData_.fmt_ = AL_FORMAT_MONO8;
_media.audioData_.sampleSize_ = 1;
break;
case ffmpeg::AV_SAMPLE_FMT_S16:
case ffmpeg::AV_SAMPLE_FMT_S16P:
_media.audioData_.fmt_ = AL_FORMAT_MONO16;
_media.audioData_.sampleSize_ = sizeof(uint16_t);
break;
default:
_media.audioData_.sampleSize_ = -1;
break;
}
break;
case AV_CH_LAYOUT_STEREO:
switch (inputFormat)
{
case ffmpeg::AV_SAMPLE_FMT_U8:
_media.audioData_.fmt_ = AL_FORMAT_STEREO8;
_media.audioData_.sampleSize_ = 2;
break;
case ffmpeg::AV_SAMPLE_FMT_S16:
_media.audioData_.fmt_ = AL_FORMAT_STEREO16;
_media.audioData_.sampleSize_ = 2 * sizeof(uint16_t);
break;
default:
_media.audioData_.sampleSize_ = -1;
break;
}
break;
default:
_media.audioData_.sampleSize_ = -1;
break;
}
if (_media.audioData_.freq_ != 44100 && _media.audioData_.freq_ != 48000)
_media.audioData_.sampleSize_ = -1;
if (_media.audioData_.sampleSize_ < 0)
{
_media.audioData_.swrContext_ = ffmpeg::swr_alloc();
if (!_media.audioData_.swrContext_)
return false;
int64_t src_ch_layout = _media.audioData_.layout_, dst_ch_layout = audio::outChannelLayout;
_media.audioData_.srcRate_ = _media.audioData_.freq_;
ffmpeg::AVSampleFormat src_sample_fmt = inputFormat, dst_sample_fmt = audio::outFormat;
_media.audioData_.dstRate_ = (_media.audioData_.freq_ != 44100 && _media.audioData_.freq_ != 48000) ? audio::outFrequency : _media.audioData_.freq_;
ffmpeg::av_opt_set_int(_media.audioData_.swrContext_, "in_channel_layout", src_ch_layout, 0);
ffmpeg::av_opt_set_int(_media.audioData_.swrContext_, "in_sample_rate", _media.audioData_.srcRate_, 0);
ffmpeg::av_opt_set_sample_fmt(_media.audioData_.swrContext_, "in_sample_fmt", src_sample_fmt, 0);
ffmpeg::av_opt_set_int(_media.audioData_.swrContext_, "out_channel_layout", dst_ch_layout, 0);
ffmpeg::av_opt_set_int(_media.audioData_.swrContext_, "out_sample_rate", _media.audioData_.dstRate_, 0);
ffmpeg::av_opt_set_sample_fmt(_media.audioData_.swrContext_, "out_sample_fmt", dst_sample_fmt, 0);
if (swr_init(_media.audioData_.swrContext_) < 0)
return false;
_media.audioData_.sampleSize_ = audio::outChannels * sizeof(uint16_t);
_media.audioData_.freq_ = _media.audioData_.dstRate_;
//!!!int64_t len_ = ffmpeg::av_rescale_rnd(Len_, DstRate_, SrcRate_, AV_ROUND_UP);
_media.audioData_.fmt_ = AL_FORMAT_STEREO16;
_media.audioData_.maxResampleSamples_ = ffmpeg::av_rescale_rnd(audio::blockSize / _media.audioData_.sampleSize_, _media.audioData_.dstRate_, _media.audioData_.srcRate_, ffmpeg::AV_ROUND_UP);
if (ffmpeg::av_samples_alloc_array_and_samples(&_media.audioData_.outSamplesData_, 0, audio::outChannels, _media.audioData_.maxResampleSamples_, audio::outFormat, 0) < 0)
return false;
}
return true;
}
void VideoContext::freeDecodeAudioData(MediaData& _media)
{
if (_media.audioData_.frame_)
ffmpeg::av_frame_free(&_media.audioData_.frame_);
if (_media.audioData_.swrContext_)
ffmpeg::swr_free(&_media.audioData_.swrContext_);
if (_media.audioData_.outSamplesData_)
{
ffmpeg::av_freep(&_media.audioData_.outSamplesData_[0]);
ffmpeg::av_freep(&_media.audioData_.outSamplesData_);
}
openal::alDeleteSources(1, &_media.audioData_.uiSource_);
openal::alDeleteBuffers(audio::num_buffers, _media.audioData_.uiBuffers_);
}
bool VideoContext::readFrameAudio(
ffmpeg::AVPacket* _packet,
AudioData& _audioData,
openal::ALvoid** _frameData,
openal::ALsizei& _frameDataSize,
bool& _flush,
int& _seekCount,
MediaData& _media,
uint32_t _videoId)
{
int64_t seek_position_audio = -1;
for (;;)
{
if (isVideoQuit(_videoId))
return false;
if (!_media.audioQueue_->get(*_packet))
{
continue;
}
if (!_packet->data)
{
_audioData.stream_finished_ = true;
}
else if (isQuitPacket(*_packet))
{
return false;
}
else if (isFlushPacket(*_packet))
{
_flush = true;
//qDebug() << "Audio thread: start seek";
flushAudioBuffers(_media);
if (_packet->pts != empty_pts)
{
seek_position_audio = _packet->pts;
++_seekCount;
}
continue;
}
int got_frame = 0;
if (!_media.audioData_.audioCodecContext_)
return false;
int len = avcodec_decode_audio4(_media.audioData_.audioCodecContext_, _media.audioData_.frame_, &got_frame, _packet);
if (_packet->data)
{
ffmpeg::av_packet_unref(_packet);
}
if (len < 0)
return false;
if (!got_frame)
{
if (_audioData.stream_finished_)
{
_audioData.eof_ = true;
return false;
}
continue;
}
else
{
setStartTimeAudio(_media.audioData_.frame_->pkt_dts, _media);
if (seek_position_audio > 0 && _media.audioData_.frame_->pkt_dts < seek_position_audio)
{
ffmpeg::av_frame_unref(_media.audioData_.frame_);
continue;
}
seek_position_audio = 0;
}
if (_media.audioData_.outSamplesData_)
{
int64_t delay = ffmpeg::swr_get_delay(_media.audioData_.swrContext_, _media.audioData_.srcRate_);
int64_t dstSamples = ffmpeg::av_rescale_rnd(delay + _media.audioData_.frame_->nb_samples, _media.audioData_.dstRate_, _media.audioData_.srcRate_, ffmpeg::AV_ROUND_UP);
if (dstSamples > _media.audioData_.maxResampleSamples_)
{
_media.audioData_.maxResampleSamples_ = dstSamples;
ffmpeg::av_free(_media.audioData_.outSamplesData_[0]);
if (ffmpeg::av_samples_alloc(_media.audioData_.outSamplesData_, 0, audio::outChannels, _media.audioData_.maxResampleSamples_, audio::outFormat, 1) < 0)
{
_media.audioData_.outSamplesData_[0] = 0;
return false;
}
}
int32_t res = 0;
if ((res = ffmpeg::swr_convert(_media.audioData_.swrContext_, _media.audioData_.outSamplesData_, dstSamples, (const uint8_t**)_media.audioData_.frame_->extended_data, _media.audioData_.frame_->nb_samples)) < 0)
return false;
qint32 resultLen = ffmpeg::av_samples_get_buffer_size(0, audio::outChannels, res, audio::outFormat, 1);
*_frameData = _media.audioData_.outSamplesData_[0];
_frameDataSize = resultLen;
}
else
{
*_frameData = _media.audioData_.frame_->extended_data[0];
_frameDataSize = _media.audioData_.frame_->nb_samples * _media.audioData_.sampleSize_;
}
return true;
}
}
static void stopPttIfNeeded(const MediaData& _media)
{
if (!_media.mute_ && _media.volume_ > 0)
Q_EMIT Utils::InterConnector::instance().stopPttRecord();
}
bool VideoContext::playNextAudioFrame(
ffmpeg::AVPacket* _packet,
/*in out*/ AudioData& _audioData,
bool& _flush,
int& _seekCount,
MediaData& _media,
uint32_t _videoId)
{
qCDebug(ffmpegPlayer) << "playNextAudioFrame";
Ui::GetSoundsManager()->checkAudioDevice();
openal::ALint iBuffersProcessed = 0;
openal::ALvoid* frameData = 0;
openal::ALsizei frameDataSize = 0;
// set volume
openal::ALfloat volume = (_media.mute_ ? (0.0) : (float(_media.volume_) / 100.0));
openal::alSourcef(_media.audioData_.uiSource_, AL_GAIN, volume);
openal::ALint iState = 0;
openal::ALint iQueuedBuffers = 0;
if (!_media.audioData_.queueInited_)
{
for (int i = 0; i < audio::num_buffers; ++i)
{
_flush = false;
if (!readFrameAudio(_packet, _audioData, &frameData, frameDataSize, _flush, _seekCount, _media, _videoId))
return false;
if (_flush)
{
flushBuffers(_media);
return true;
}
openal::alBufferData(_media.audioData_.uiBuffers_[i], _media.audioData_.fmt_, frameData, frameDataSize, _media.audioData_.freq_);
openal::alSourceQueueBuffers(_media.audioData_.uiSource_, 1, &_media.audioData_.uiBuffers_[i]);
_media.audio_queue_ptss_.push(_media.audioData_.frame_->pkt_pts);
}
_media.audioData_.queueInited_ = true;
}
openal::alGetSourcei(_media.audioData_.uiSource_, AL_BUFFERS_PROCESSED, &iBuffersProcessed);
while (iBuffersProcessed)
{
_media.audioData_.uiBuffer_ = 0;
openal::alSourceUnqueueBuffers(_media.audioData_.uiSource_, 1, &_media.audioData_.uiBuffer_);
_flush = false;
if (!readFrameAudio(_packet, _audioData, &frameData, frameDataSize, _flush, _seekCount, _media, _videoId))
return false;
if (_flush)
{
flushBuffers(_media);
return true;
}
openal::alBufferData(_media.audioData_.uiBuffer_, _media.audioData_.fmt_, frameData, frameDataSize, _media.audioData_.freq_);
openal::alSourceQueueBuffers(_media.audioData_.uiSource_, 1, &_media.audioData_.uiBuffer_);
_media.audio_queue_ptss_.push(_media.audioData_.frame_->pkt_pts);
iBuffersProcessed--;
_media.audio_queue_ptss_.pop();
}
openal::ALfloat offset = 0;
openal::alGetSourcef(_media.audioData_.uiSource_, AL_SEC_OFFSET, &offset);
if (!_media.audio_queue_ptss_.empty())
{
double pts = _media.audio_queue_ptss_.front();
if (pts == AV_NOPTS_VALUE)
{
pts = 0.0;
}
pts *= getAudioTimebase(_media);
pts += offset;
_audioData.offset_ = pts;
qCDebug(ffmpegPlayer) << "_audioData.offset_ = " << _audioData.offset_;
}
else
{
qCDebug(ffmpegPlayer) << "_media.audio_queue_ptss_.empty() = true";
}
openal::alGetSourcei(_media.audioData_.uiSource_, AL_SOURCE_STATE, &iState);
const auto time_now = std::chrono::system_clock::now();
static auto lastDelayTime = time_now;
if ((time_now - lastDelayTime) > std::chrono::milliseconds(1000))
{
lastDelayTime = time_now;
Ui::GetSoundsManager()->delayDeviceTimer();
}
if (iState != AL_PLAYING)
{
// If there are Buffers in the Source Queue then the Source was starved of audio
// data, so needs to be restarted (because there is more audio data to play)
openal::alGetSourcei(_media.audioData_.uiSource_, AL_BUFFERS_QUEUED, &iQueuedBuffers);
if (iQueuedBuffers)
{
stopPttIfNeeded(_media);
Ui::GetSoundsManager()->sourcePlay(_media.audioData_.uiSource_);
}
else
{
// Finished playing
return true;
}
}
return true;
}
void VideoContext::flushBuffers(MediaData& _media)
{
openal::alSourceStop(_media.audioData_.uiSource_);
openal::alDeleteSources(1, &_media.audioData_.uiSource_);
openal::alDeleteBuffers(audio::num_buffers, _media.audioData_.uiBuffers_);
openal::alGenBuffers(audio::num_buffers, _media.audioData_.uiBuffers_);
openal::alGenSources(1, &_media.audioData_.uiSource_);
_media.audioData_.queueInited_ = false;
_media.audio_queue_ptss_ = {};
}
void VideoContext::cleanupAudioBuffers(MediaData& _media)
{
_media.audioData_.buffersProcessed_ = 0;
openal::alGetSourcei(_media.audioData_.uiSource_, AL_BUFFERS_PROCESSED, &_media.audioData_.buffersProcessed_);
while (_media.audioData_.buffersProcessed_)
{
_media.audioData_.uiBuffer_ = 0;
openal::alSourceUnqueueBuffers(_media.audioData_.uiSource_, 1, &_media.audioData_.uiBuffer_);
--_media.audioData_.buffersProcessed_;
}
}
void VideoContext::suspendAudio(MediaData& _media)
{
openal::alSourcePause(_media.audioData_.uiSource_);
}
void VideoContext::stopAudio(MediaData& _media)
{
openal::alSourceStop(_media.audioData_.uiSource_);
}
void VideoContext::updateScaledVideoSize(uint32_t _videoId, const QSize& _sz)
{
ThreadMessage msg(_videoId, thread_message_type::tmt_update_scaled_size);
msg.x_ = _sz.width();
msg.y_ = _sz.height();
if (auto mediaData = getMediaData(_videoId))
{
const auto rotation = getRotation(*mediaData);
if (rotation == 90 || rotation == 270)
std::swap(msg.x_, msg.y_);
}
postVideoThreadMessage(msg, false);
}
void VideoContext::postVideoThreadMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
videoThreadMessagesQueue_.pushMessage(_message, _forward, _clear_others);
}
void VideoContext::postDemuxThreadMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
demuxThreadMessageQueue_.pushMessage(_message, _forward, _clear_others);
}
bool VideoContext::getDemuxThreadMessage(ThreadMessage& _message, int32_t _waitTimeout)
{
return demuxThreadMessageQueue_.getMessage(_message, [this] {return isQuit(); }, _waitTimeout);
}
void VideoContext::postAudioThreadMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
audioThreadMessageQueue_.pushMessage(_message, _forward, _clear_others);
}
bool VideoContext::getAudioThreadMessage(ThreadMessage& _message, int32_t _waitTimeout)
{
return audioThreadMessageQueue_.getMessage(_message, [this] {return isQuit(); }, _waitTimeout);
}
void VideoContext::clearMessageQueue()
{
videoThreadMessagesQueue_.clear();
audioThreadMessageQueue_.clear();
demuxThreadMessageQueue_.clear();
}
decode_thread_state VideoContext::getAudioThreadState(MediaData& _media) const
{
return _media.audioData_.state_;
}
void VideoContext::setAudioThreadState(const decode_thread_state& _state, MediaData& _media)
{
_media.audioData_.state_ = _state;
}
bool VideoContext::getVideoThreadMessage(ThreadMessage& _message, int32_t _waitTimeout)
{
return videoThreadMessagesQueue_.getMessage(_message, [this] {return isQuit(); }, _waitTimeout);
}
bool VideoContext::getAllVideoThreadMessages(ThreadMessageList& _messages, int32_t _waitTimeout)
{
return videoThreadMessagesQueue_.getAllMessages(_messages, [this] {return isQuit(); }, _waitTimeout);
}
bool VideoContext::updateScaleContext(MediaData& _media, const QSize _sz)
{
if (_media.scaledSize_ != _sz)
{
_media.scaledSize_ = _sz;
_media.needUpdateSwsContext_ = true;
Q_EMIT videoSizeChanged(_media.scaledSize_);
}
return true;
}
void VideoContext::freeScaleContext(MediaData& _media)
{
if (_media.frameRGB_)
{
ffmpeg::av_frame_unref(_media.frameRGB_);
ffmpeg::av_frame_free(&_media.frameRGB_);
}
_media.frameRGB_ = nullptr;
sws_freeContext(_media.swsContext_);
}
void VideoContext::setVolume(int32_t _volume, MediaData& _media)
{
_media.volume_ = _volume;
stopPttIfNeeded(_media);
}
void VideoContext::setMute(bool _mute, MediaData& _media)
{
_media.mute_ = _mute;
stopPttIfNeeded(_media);
}
void VideoContext::resetFrameTimer(MediaData& _media)
{
_media.frameTimer_ = currentTimeInSeconds();
}
void VideoContext::resetLastFramePts(MediaData& _media)
{
_media.frameLastPts_ = 0.0;
_media.frameLastPtsReset_ = true;
}
bool VideoContext::seekMs(uint32_t _videoId, int _tsms, MediaData& _media)
{
if (_media.isLottie_)
{
Q_EMIT seekedA(_videoId);
Q_EMIT seekedV(_videoId);
return false;
}
auto calc_ts = [_tsms](ffmpeg::AVStream* _stream)
{
int64_t ts = 0;
if (_stream)
{
ts = ffmpeg::av_rescale(_tsms, _stream->time_base.den, _stream->time_base.num);
ts /= 1000;
}
return ts;
};
const auto ts_video = calc_ts(_media.videoStream_);
const auto ts_audio = calc_ts(_media.audioStream_);
return seekFrame(_videoId, ts_video, ts_audio, _media);
}
bool VideoContext::seekFrame(uint32_t _videoId, int64_t _ts_video, int64_t _ts_audio, MediaData& _media)
{
if (ffmpeg::avformat_seek_file(_media.formatContext_, _media.videoStream_->index, INT64_MIN
, _media.startTimeVideo_ + _ts_video, INT64_MAX, 0) < 0)
{
return false;
}
_media.videoQueue_->freeData([_videoId, this](ffmpeg::AVPacket& _packet)
{
if (isFlushPacket(_packet))
{
qCDebug(ffmpegPlayer) << "Q_EMIT seekedV from clear";
Q_EMIT seekedV(_videoId);
}
});
_media.audioQueue_->freeData([_videoId, this](ffmpeg::AVPacket& _packet)
{
if (isFlushPacket(_packet))
{
qCDebug(ffmpegPlayer) << "Q_EMIT seekedA from clear";
Q_EMIT seekedA(_videoId);
}
});
ffmpeg::AVPacket flush_pkt_v;
initFlushPacket(flush_pkt_v);
flush_pkt_v.dts = (_media.startTimeVideo_ + _ts_video);
pushVideoPacket(&flush_pkt_v, _media);
if (_media.hasAudio())
{
ffmpeg::AVPacket flush_pkt_a;
initFlushPacket(flush_pkt_a);
flush_pkt_a.pts = (_media.startTimeAudio_ + _ts_audio);
pushAudioPacket(&flush_pkt_a, _media);
}
else
{
Q_EMIT seekedA(_videoId);
}
return true;
}
void VideoContext::flushVideoBuffers(MediaData& _media)
{
if (_media.videoStream_)
{
ffmpeg::avcodec_flush_buffers(_media.videoStream_->codec);
}
}
void VideoContext::flushAudioBuffers(MediaData& _media)
{
if (_media.audioStream_)
{
ffmpeg::avcodec_flush_buffers(_media.audioStream_->codec);
}
}
void VideoContext::resetVideoClock(MediaData& _media)
{
_media.videoClock_ = 0.0;
}
void VideoContext::resetAudioClock(MediaData& _media)
{
_media.audioClock_ = 0.0;
}
void VideoContext::setStartTimeVideo(const int64_t& _startTime, MediaData& _media)
{
if (_media.startTimeVideoSet_)
return;
_media.startTimeVideoSet_ = true;
_media.startTimeVideo_ = _startTime;
}
const int64_t& VideoContext::getStartTimeVideo(MediaData& _media) const
{
return _media.startTimeVideo_;
}
void VideoContext::setStartTimeAudio(const int64_t& _startTime, MediaData& _media)
{
if (_media.startTimeAudioSet_)
return;
_media.startTimeAudioSet_ = true;
_media.startTimeAudio_ = _startTime;
}
const int64_t& VideoContext::getStartTimeAudio(MediaData& _media) const
{
return _media.startTimeAudio_;
}
std::shared_ptr<MediaData> VideoContext::getMediaData(uint32_t _videoId) const
{
std::scoped_lock lock(mediaDataMutex_);
const auto it = std::as_const(mediaData_).find(_videoId);
if (it == std::as_const(mediaData_).end())
return nullptr;
return it->second;
}
void VideoContext::onAudioQuit(uint32_t _videoId)
{
Utils::ensureMainThread();
auto media_ptr = getMediaContainer()->ctx_.getMediaData(_videoId);
if (!media_ptr)
return;
media_ptr->audioQuitRecv_ = true;
sendCloseStreams(_videoId);
}
void VideoContext::onVideoQuit(uint32_t _videoId)
{
Utils::ensureMainThread();
auto media_ptr = getMediaContainer()->ctx_.getMediaData(_videoId);
if (!media_ptr)
return;
media_ptr->videoQuitRecv_ = true;
sendCloseStreams(_videoId);
}
void VideoContext::onDemuxQuit(uint32_t _videoId)
{
Utils::ensureMainThread();
auto media_ptr = getMediaContainer()->ctx_.getMediaData(_videoId);
if (!media_ptr)
return;
media_ptr->demuxQuitRecv_ = true;
sendCloseStreams(_videoId);
}
void VideoContext::onStreamsClosed(uint32_t _videoId)
{
Utils::ensureMainThread();
deleteVideo(_videoId);
}
void VideoContext::sendCloseStreams(uint32_t _videoId)
{
auto media_ptr = getMediaContainer()->ctx_.getMediaData(_videoId);
if (!media_ptr)
return;
if (media_ptr->demuxQuitRecv_ && media_ptr->audioQuitRecv_ && media_ptr->videoQuitRecv_)
{
getMediaContainer()->postDemuxThreadMessage(ThreadMessage(_videoId, thread_message_type::tmt_close_streams), true, true);
}
}
//////////////////////////////////////////////////////////////////////////
// DemuxThread
//////////////////////////////////////////////////////////////////////////
DemuxThread::DemuxThread(VideoContext& _ctx)
: ctx_(_ctx)
{
setObjectName(qsl("Demux"));
}
void DemuxThread::run()
{
qCDebug(ffmpegPlayer) << "demux thread started";
int32_t waitMsgTimeout = 0;
ffmpeg::AVPacket packet;
std::unordered_map<uint32_t, DemuxData> demuxData;
ThreadMessage msg;
while (!ctx_.isQuit())
{
decode_thread_state state = decode_thread_state::dts_none;
int64_t seekPosition = -1;
bool eof = false;
if (ctx_.getDemuxThreadMessage(msg, waitMsgTimeout))
{
auto iterData = demuxData.find(msg.videoId_);
bool videoDataFound = (iterData != demuxData.end());
if (videoDataFound)
{
state = iterData->second.state;
seekPosition = iterData->second.seekPosition;
eof = iterData->second.eof;
}
switch (msg.message_)
{
case thread_message_type::tmt_init:
{
if (!videoDataFound)
{
auto emplace_result = demuxData.insert(std::make_pair(msg.videoId_, Ui::DemuxData()));
if (!emplace_result.second)
{
im_assert(false);
continue;
}
iterData = emplace_result.first;
iterData->second.media_ = ctx_.getMediaData(msg.videoId_);
videoDataFound = true;
}
Q_EMIT ctx_.demuxInited(msg.videoId_);
break;
}
case thread_message_type::tmt_open_streams:
{
qCDebug(ffmpegPlayer) << "open stream videoId = " << msg.videoId_;
auto media_ptr = ctx_.getMediaData(msg.videoId_);
if (!media_ptr || media_ptr->demuxQuitRecv_)
continue;
getMediaContainer()->ctx_.openStreams(msg.videoId_, msg.str_, *media_ptr);
continue;
}
case thread_message_type::tmt_close_streams:
{
qCDebug(ffmpegPlayer) << "close stream videoId = " << msg.videoId_;
auto media_ptr = ctx_.getMediaData(msg.videoId_);
if (!media_ptr || media_ptr->streamClosed_)
continue;
media_ptr->streamClosed_ = true;
ctx_.clearAudioQueue(*media_ptr);
ctx_.clearVideoQueue(*media_ptr);
getMediaContainer()->ctx_.closeFile(*media_ptr);
Q_EMIT ctx_.streamsClosed(msg.videoId_);
continue;
}
case thread_message_type::tmt_get_first_frame:
{
Q_EMIT getMediaContainer()->frameReady(ctx_.getFirstFrame(msg.str_), msg.str_);
continue;
}
case thread_message_type::tmt_quit:
{
qCDebug(ffmpegPlayer) << "demux quit videoId = " << msg.videoId_;
if (videoDataFound)
{
demuxData.erase(iterData);
iterData = demuxData.end();
videoDataFound = false;
}
auto media_ptr = ctx_.getMediaData(msg.videoId_);
if (!media_ptr)
{
Q_EMIT ctx_.demuxQuit(msg.videoId_);
continue;
}
ctx_.pushVideoPacket(&quit_pkt, *media_ptr);
ctx_.pushAudioPacket(&quit_pkt, *media_ptr);
Q_EMIT ctx_.demuxQuit(msg.videoId_);
break;
}
case thread_message_type::tmt_play:
{
if (videoDataFound)
state = decode_thread_state::dts_playing;
break;
}
case thread_message_type::tmt_pause:
{
if (videoDataFound)
state = decode_thread_state::dts_paused;
break;
}
case thread_message_type::tmt_seek_position:
{
if (videoDataFound)
{
if (seekPosition >= 0)
{
Q_EMIT ctx_.seekedV(msg.videoId_);
Q_EMIT ctx_.seekedA(msg.videoId_);
}
seekPosition = msg.x_;
}
break;
}
default:
continue;
}
if (videoDataFound)
{
iterData->second.state = state;
iterData->second.seekPosition = seekPosition;
}
}
waitMsgTimeout = demuxData.empty() ? 60000 : 10;
for (auto& [videoId, data] : demuxData)
{
state = data.state;
seekPosition = data.seekPosition;
eof = data.eof;
auto media_ptr = data.media_.lock();
if (!media_ptr)
continue;
auto& media = *media_ptr;
if (data.inited && media.formatContext_)
{
if (state == decode_thread_state::dts_paused)
ctx_.readAVPacketPause(media);
else
ctx_.readAVPacketPlay(media);
}
if (state == decode_thread_state::dts_paused)
continue;
if (seekPosition >= 0)
{
ctx_.seekMs(videoId, seekPosition, media);
seekPosition = -1;
data.seekPosition = seekPosition;
eof = false;
data.eof = eof;
}
if (
(
(ctx_.getAudioQueueSize(media) > maxQueueSize || !media.hasAudio())
&& (ctx_.getVideoQueueSize(media) > maxQueueSize || !media.hasVideo())
)
||
(
(ctx_.getAudioQueuePackets(media) > minFramesCount || !media.hasAudio())
&& (ctx_.getVideoQueuePackets(media) > minFramesCount || !media.hasVideo())
)
)
{
continue;
}
if (media.isLottie_)
{
data.inited = true;
data.eof = false;
waitMsgTimeout = 1;
while (ctx_.getVideoQueuePackets(media) <= minFramesCount)
ctx_.pushVideoPacket(0, media);
Q_EMIT ctx_.dataReady(videoId);
continue;
}
int32_t readPacketError = ctx_.readAVPacket(&packet, media);
if (readPacketError < 0)
{
if (ctx_.isEof(readPacketError, media) && !eof)
{
if (media.hasAudio())
ctx_.pushAudioPacket(0, media);
ctx_.pushVideoPacket(0, media);
eof = true;
}
data.eof = eof;
// TODO : do smth with this error
if (ctx_.isStreamError(media))
continue;
continue;
}
else
{
eof = false;
}
waitMsgTimeout = 1;
data.eof = eof;
int32_t videoStreamIndex = ctx_.getVideoStreamIndex(media);
int32_t audioStreamIndex = ctx_.getAudioStreamIndex(media);
if (packet.stream_index == videoStreamIndex)
{
ctx_.pushVideoPacket(&packet, media);
}
else if (packet.stream_index == audioStreamIndex)
{
ctx_.pushAudioPacket(&packet, media);
}
else
{
av_packet_unref(&packet);
}
if (!data.inited)
{
data.inited = true;
Q_EMIT ctx_.dataReady(videoId);
}
}
}
ctx_.cleanupOnExit();
qCDebug(ffmpegPlayer) << "demux thread finished";
}
//////////////////////////////////////////////////////////////////////////
// VideoDecodeThread
//////////////////////////////////////////////////////////////////////////
VideoDecodeThread::VideoDecodeThread(VideoContext& _ctx)
: ctx_(_ctx)
{
setObjectName(qsl("VideoDecode"));
}
void VideoDecodeThread::run()
{
qCDebug(ffmpegPlayer) << "video decode thread start";
ffmpeg::AVFrame* frame = ffmpeg::av_frame_alloc();
std::unordered_map<uint32_t, VideoData> videoData;
ThreadMessageList messages;
std::vector<LottieRenderData> lottieData;
lottieData.reserve(1000);
int32_t waitMsgTimeout = 60000;
ffmpeg::AVPacket av_packet;
while (!ctx_.isQuit())
{
if (!ctx_.getAllVideoThreadMessages(messages, waitMsgTimeout))
continue;
qCDebug(ffmpegPlayer) << "video decode processing" << messages.size() << "messages";
for (auto& msg : messages)
{
const auto videoId = msg.videoId_;
auto it = videoData.find(videoId);
if (it == videoData.end())
{
if (msg.message_ == thread_message_type::tmt_init)
{
VideoData data;
data.current_state_ = decode_thread_state::dts_playing;
data.stream_finished_ = false;
data.eof_ = false;
data.media_ = ctx_.getMediaData(videoId);
it = videoData.insert({ videoId, std::move(data) }).first;
}
else if (msg.message_ == thread_message_type::tmt_quit)
{
Q_EMIT ctx_.videoQuit(videoId);
continue;
}
else
{
continue;
}
}
auto& data = it->second;
if (processDataMessage(data, msg))
continue;
auto media_ptr = data.media_.lock();
if (!media_ptr)
continue;
auto& media = *media_ptr;
switch (msg.message_)
{
case thread_message_type::tmt_quit:
{
videoData.erase(it);
ctx_.freeScaleContext(media);
Q_EMIT ctx_.videoQuit(videoId);
break;
}
case thread_message_type::tmt_update_scaled_size:
{
const QSize scaledSize = ctx_.getTargetSize(media);
QSize newSize(msg.x_, msg.y_);
if (scaledSize != newSize)
ctx_.updateScaleContext(media, newSize);
break;
}
case thread_message_type::tmt_get_next_video_frame:
{
if (data.current_state_ == decode_thread_state::dts_end_of_media || data.current_state_ == decode_thread_state::dts_failed)
break;
if (media.isLottie_)
{
auto rdata = renderLottieFrame(data, media, videoId);
if (rdata.isValid())
lottieData.emplace_back(std::move(rdata));
}
else
{
renderVideoFrame(data, media, frame, av_packet, videoId);
}
break;
}
default:
break;
}
}
for (auto& rdata : lottieData)
{
rdata.fut_.get();
Q_EMIT ctx_.nextframeReady(rdata.videoId_, rdata.frame_, currentTimeInSeconds(), false);
if (auto media = rdata.media_.lock())
media->lottieRenderer_.setFrame(rdata.frameNo_, rdata.frame_);
}
lottieData.clear();
}
for (const auto& [_, data] : videoData)
if (auto media = data.media_.lock())
ctx_.freeScaleContext(*media);
ffmpeg::av_frame_unref(frame);
ffmpeg::av_frame_free(&frame);
qCDebug(ffmpegPlayer) << "video decode thread finished";
}
LottieRenderData VideoDecodeThread::renderLottieFrame(VideoData& _data, MediaData& _media, int32_t _videoId)
{
if (!_media.lottieRenderer_ || ctx_.isQuit() || ctx_.isVideoQuit(_videoId))
return {};
const auto startTimeSet = _media.startTimeVideoSet_;
ctx_.setStartTimeVideo(currentTimeInSeconds(), _media);
if (!startTimeSet)
_media.frameTimer_ = _media.startTimeVideo_;
const auto totalFrames = _media.lottieRenderer_->totalFrame();
unsigned int frameNo = int((_media.frameTimer_ - _media.startTimeVideo_) / _media.videoClock_);
_data.eof_ = false;
if (frameNo < totalFrames)
{
qCDebug(ffmpegPlayer) << "lottie render" << frameNo << "/" << (totalFrames - 1);
const auto scaledSize = ctx_.getTargetSize(_media);
QImage lastFrame = getLastFrame(_data);
if (lastFrame.isNull() || lastFrame.size() != scaledSize || !lastFrame.isDetached())
lastFrame = QImage(scaledSize, QImage::Format_ARGB32_Premultiplied);
LottieRenderData rdata;
rdata.frame_ = std::move(lastFrame);
rdata.videoId_ = _videoId;
rdata.frameNo_ = frameNo;
rdata.media_ = _data.media_;
rlottie::Surface surface((uint32_t*)rdata.frame_.bits(), rdata.frame_.width(), rdata.frame_.height(), rdata.frame_.bytesPerLine());
rdata.fut_ = _media.lottieRenderer_.renderFrame(frameNo, std::move(surface));
return rdata;
}
else
{
qCDebug(ffmpegPlayer) << "lottie render EOF";
_data.current_state_ = decode_thread_state::dts_end_of_media;
_data.stream_finished_ = false;
_media.startTimeVideoSet_ = false;
Q_EMIT ctx_.nextframeReady(_videoId, QImage(), 0, true);
}
return {};
}
void VideoDecodeThread::renderVideoFrame(VideoData& _data, MediaData& _media, ffmpeg::AVFrame* _frame, ffmpeg::AVPacket& _av_packet, int32_t _videoId)
{
ffmpeg::av_frame_unref(_frame);
_data.eof_ = false;
if (ctx_.getNextVideoFrame(_frame, &_av_packet, _data, _media, _videoId))
{
ctx_.setStartTimeVideo(_frame->pkt_dts, _media);
// Consider sync
double pts = _frame->pkt_dts;
if (pts == AV_NOPTS_VALUE)
pts = _frame->pkt_pts;
if (pts == AV_NOPTS_VALUE)
pts = 0;
pts *= ctx_.getVideoTimebase(_media);
pts = ctx_.synchronizeVideo(_frame, pts, _media);
if (ctx_.isQuit())
return;
auto scaledSize = ctx_.getTargetSize(_media);
const auto sourceSize = ctx_.getSourceSize(_media);
auto targetRatio = static_cast<double>(sourceSize.width()) / sourceSize.height();
if (scaledSize.width() > scaledSize.height())
scaledSize.rheight() = scaledSize.width() / targetRatio;
else
scaledSize.rwidth() = scaledSize.height() * targetRatio;
scaledSize = scaledSize.boundedTo(sourceSize);
const auto rotation = ctx_.getRotation(_media);
if (scaledSize.width() == 0)
scaledSize.setWidth(1);
if (scaledSize.height() == 0)
scaledSize.setHeight(1);
auto lastFrame = getLastFrame(_data);
int align = 256;
if constexpr (platform::is_windows()) // spike for opengl
{
align = 4;
}
else // spike for osx
{
while (true)
{
if (_frame->linesize[0] % align == 0)
break;
align = align / 2;
}
}
if (lastFrame.isNull() || lastFrame.size() != scaledSize || !lastFrame.isDetached() || !isAlignedImage(lastFrame, align))
lastFrame = createAlignedImage(scaledSize, align);
if ((_media.needUpdateSwsContext_) || (_frame->format != -1 && _frame->format != _media.codecContext_->pix_fmt) || !_media.swsContext_)
{
_media.needUpdateSwsContext_ = false;
_media.swsContext_ = sws_getCachedContext(
_media.swsContext_,
_frame->width,
_frame->height,
ffmpeg::AVPixelFormat(_frame->format), scaledSize.width(), scaledSize.height(), ffmpeg::AV_PIX_FMT_BGRA, SWS_POINT, 0, 0, 0);
}
uint8_t* toData[AV_NUM_DATA_POINTERS] = { lastFrame.bits(), nullptr };
int toLinesize[AV_NUM_DATA_POINTERS] = { lastFrame.bytesPerLine(), 0 };
ffmpeg::sws_scale(_media.swsContext_, _frame->data, _frame->linesize, 0, _frame->height, toData, toLinesize);
if (rotation)
lastFrame = lastFrame.transformed(QTransform().rotate(rotation));
Q_EMIT ctx_.nextframeReady(_videoId, lastFrame, pts, false);
}
else if (_data.eof_)
{
_data.current_state_ = decode_thread_state::dts_end_of_media;
_data.stream_finished_ = false;
ctx_.resetVideoClock(_media);
Q_EMIT ctx_.nextframeReady(_videoId, QImage(), 0, true);
}
}
QImage VideoDecodeThread::getLastFrame(VideoData& _data) const
{
QImage lastFrame = _data.emptyFrames_.empty() ? QImage() : std::move(_data.emptyFrames_.front());
if (!_data.emptyFrames_.empty())
_data.emptyFrames_.pop_front();
return lastFrame;
}
bool VideoDecodeThread::processDataMessage(VideoData& _data, ThreadMessage& _msg) const
{
switch (_msg.message_)
{
case thread_message_type::tmt_pause:
if (_data.current_state_ != decode_thread_state::dts_failed)
_data.current_state_ = decode_thread_state::dts_paused;
break;
case thread_message_type::tmt_play:
if (_data.current_state_ != decode_thread_state::dts_failed)
_data.current_state_ = decode_thread_state::dts_playing;
break;
case thread_message_type::tmt_seek_position:
if (_data.current_state_ == decode_thread_state::dts_end_of_media)
_data.current_state_ = decode_thread_state::dts_playing;
break;
case thread_message_type::tmt_empty_frame:
if (_data.emptyFrames_.size() < 5)
_data.emptyFrames_.emplace_back(std::move(_msg.emptyFrame_));
break;
default:
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// AudioDecodeThread
//////////////////////////////////////////////////////////////////////////
AudioDecodeThread::AudioDecodeThread(VideoContext& _ctx)
: ctx_(_ctx)
{
setObjectName(qsl("AudioDecode"));
}
void AudioDecodeThread::run()
{
qCDebug(ffmpegPlayer) << "audio decode thread start";
std::unordered_map<uint32_t, AudioData> audioData;
bool flush = false;
ffmpeg::AVPacket packet;
ThreadMessage msg;
auto isPlaying = [](const auto& media_ptr)
{
return
media_ptr &&
media_ptr->hasAudio() &&
media_ptr->audioData_.state_ == decode_thread_state::dts_playing;
};
while (!ctx_.isQuit())
{
const auto has_playing = std::any_of(audioData.cbegin(), audioData.cend(), [isPlaying](const auto& x)
{
return isPlaying(x.second.media_.lock());
});
if (!flush && ctx_.getAudioThreadMessage(msg, has_playing ? 10 : 60000))
{
const auto videoId = msg.videoId_;
auto it = audioData.find(videoId);
if (it == audioData.end())
{
if (msg.message_ == thread_message_type::tmt_init)
{
auto media = ctx_.getMediaData(videoId);
if (!media || media->isLottie_ || !ctx_.initDecodeAudioData(*media))
continue;
AudioData data;
data.eof_ = false;
data.stream_finished_ = false;
data.media_ = media;
it = audioData.insert({ videoId, std::move(data) }).first;
ctx_.setMute(msg.x_, *media);
ctx_.setVolume(msg.y_, *media);
}
else if (msg.message_ == thread_message_type::tmt_quit)
{
Q_EMIT ctx_.audioQuit(videoId);
continue;
}
else
{
continue;
}
}
auto media_ptr = it->second.media_.lock();
if (!media_ptr)
continue;
auto& media = *media_ptr;
switch (msg.message_)
{
case thread_message_type::tmt_set_volume:
{
ctx_.setVolume(msg.x_, media);
break;
}
case thread_message_type::tmt_pause:
{
ctx_.setAudioThreadState(decode_thread_state::dts_paused, media);
ctx_.suspendAudio(media);
break;
}
case thread_message_type::tmt_play:
{
ctx_.setAudioThreadState(decode_thread_state::dts_playing, media);
break;
}
case thread_message_type::tmt_set_mute:
{
ctx_.setMute(msg.x_, media);
break;
}
case thread_message_type::tmt_quit:
{
ctx_.freeDecodeAudioData(media);
audioData.erase(it);
Q_EMIT ctx_.audioQuit(videoId);
break;
}
case thread_message_type::tmt_set_finished:
{
ctx_.setAudioThreadState(decode_thread_state::dts_end_of_media, media);
it->second.eof_ = true;
break;
}
case thread_message_type::tmt_reinit_audio:
{
ctx_.flushBuffers(media);
break;
}
default:
break;
}
}
flush = false;
if (ctx_.isQuit())
break;
for (auto& [videoId, data] : audioData)
{
data.eof_ = false;
auto media_ptr = data.media_.lock();
if (!isPlaying(media_ptr))
continue;
auto& media = *media_ptr;
bool local_flush = false;
int seekCount = 0;
ctx_.playNextAudioFrame(&packet, data, local_flush, seekCount, media, videoId);
int64_t current_time = ffmpeg::av_gettime();
constexpr int64_t sync_period = 1000 * 200; // 200 milliseconds
if ((current_time - data.last_sync_time_) > sync_period)
{
data.last_sync_time_ = current_time;
//qDebug() << "Audio thread: emit audioTime";
//qDebug() << "Audio thread: offset = " << data.offset_;
Q_EMIT ctx_.audioTime(videoId, current_time, data.offset_);
}
if (seekCount)
{
for (int i = 0; i < seekCount; ++i)
Q_EMIT ctx_.seekedA(videoId);
}
flush |= local_flush;
if (data.eof_)
{
ctx_.setAudioThreadState(decode_thread_state::dts_end_of_media, media);
data.stream_finished_ = false;
}
}
}
for (const auto& [_, data] : audioData)
if (auto media = data.media_.lock())
ctx_.freeDecodeAudioData(*media);
qCDebug(ffmpegPlayer) << "audio decode thread finish";
}
static int lockmgr(void **mtx, enum ffmpeg::AVLockOp op)
{
switch (op)
{
case ffmpeg::AV_LOCK_CREATE:
{
*mtx = new std::mutex();
return 0;
}
case ffmpeg::AV_LOCK_OBTAIN:
{
((std::mutex*) *mtx)->lock();
return 0;
}
case ffmpeg::AV_LOCK_RELEASE:
{
((std::mutex*) *mtx)->unlock();
return 0;
}
case ffmpeg::AV_LOCK_DESTROY:
{
delete ((std::mutex*) *mtx);
return 0;
}
}
return 1;
}
const auto mouse_move_rate = std::chrono::milliseconds(200);
PlayersList::PlayersList()
{
connect(&getMediaContainer()->ctx_, &VideoContext::nextframeReady, this, &PlayersList::onNextFrameReady);
}
PlayersList::~PlayersList() = default;
PlayersList& PlayersList::getPlayersList()
{
static PlayersList players;
return players;
}
void PlayersList::addPlayer(FFMpegPlayer* _player)
{
playersList_.push_back(_player);
}
void PlayersList::removePlayer(FFMpegPlayer* _player)
{
playersList_.erase(std::remove_if(playersList_.begin(), playersList_.end(), [_player](const auto& _val)
{
return (_val == _player);
}), playersList_.end());
}
void PlayersList::onNextFrameReady(uint32_t _videoId, const QImage& _image, double _pts, bool _eof)
{
auto iterPlayer = std::find_if(playersList_.begin(), playersList_.end(), [_videoId](const auto& _player)
{
return (_videoId == _player->getMedia());
});
if (iterPlayer != playersList_.end())
(*iterPlayer)->onNextFrameReady(_image, _pts, _eof);
}
//////////////////////////////////////////////////////////////////////////
// FFMpegPlayer
//////////////////////////////////////////////////////////////////////////
FFMpegPlayer::FFMpegPlayer(QWidget* _parent, std::shared_ptr<FrameRenderer> _renderer, bool _continius)
: QObject(_parent),
mediaId_(0),
restoreVolume_(100),
volume_(100),
isFirstFrame_(true),
updatePositonRate_(platform::is_apple() ? 1000 : 100),
state_(decode_thread_state::dts_none),
lastVideoPosition_(0),
lastPostedPosition_(0),
lastEmitMouseMove_(std::chrono::system_clock::now() - mouse_move_rate),
stopped_(false),
started_(false),
continius_(_continius),
replay_(false),
mute_(false),
dataReady_(false),
pausedByUser_(false),
seek_request_id_(0)
{
static auto is_init = false;
if (!is_init && ffmpeg::av_lockmgr_register(lockmgr)) // TODO
{
}
is_init = true;
setRenderer(_renderer);
timer_ = new QTimer(this);
timer_->setTimerType(Qt::PreciseTimer);
connect(timer_, &QTimer::timeout, this, &FFMpegPlayer::onTimer);
connect(&getMediaContainer()->ctx_, &VideoContext::dataReady, this, &FFMpegPlayer::onDataReady);
connect(&getMediaContainer()->ctx_, &VideoContext::streamsOpenFailed, this, &FFMpegPlayer::streamsOpenFailed);
connect(&getMediaContainer()->ctx_, &VideoContext::audioTime, this, &FFMpegPlayer::onAudioTime);
connect(&getMediaContainer()->ctx_, &VideoContext::seekedV, this, &FFMpegPlayer::seekedV);
connect(&getMediaContainer()->ctx_, &VideoContext::seekedA, this, &FFMpegPlayer::seekedA);
connect(GetSoundsManager(), &SoundsManager::deviceListChanged, this, &FFMpegPlayer::onDeviceListChanged);
PlayersList::getPlayersList().addPlayer(this);
}
FFMpegPlayer::~FFMpegPlayer()
{
stop();
PlayersList::getPlayersList().removePlayer(this);
}
void FFMpegPlayer::seeked(uint32_t _videoId, const bool _fromAudio)
{
if (_videoId != mediaId_)
return;
--seek_request_id_;
qCDebug(ffmpegPlayer) << (_fromAudio ? "seekedA" : "seekedV") << " seek_request_id_ = " << seek_request_id_;
if (seek_request_id_ < 0)
{
//im_assert(false);
seek_request_id_ = 0;
}
if (seek_request_id_ == 0)
{
if (auto media = getMediaContainer()->ctx_.getMediaData(mediaId_))
getMediaContainer()->resetLastFramePts(*media);
}
}
void FFMpegPlayer::seekedV(uint32_t _videoId)
{
seeked(_videoId, false);
}
void FFMpegPlayer::seekedA(uint32_t _videoId)
{
seeked(_videoId, true);
}
void FFMpegPlayer::onDeviceListChanged()
{
const auto messsage = ThreadMessage(mediaId_, thread_message_type::tmt_reinit_audio);
getMediaContainer()->postAudioThreadMessage(messsage, true);
}
void FFMpegPlayer::onNextFrameReady(const QImage& _image, double _pts, bool _eof)
{
if (!_eof)
{
if (state_ == decode_thread_state::dts_playing)
decodedFrames_.emplace_back(_image, _pts);
if (!firstFrame_)
{
firstFrame_ = std::make_unique<DecodedFrame>(_image, _pts);
Q_EMIT firstFrameReady();
}
}
else
{
decodedFrames_.emplace_back(_eof);
getMediaContainer()->postAudioThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_set_finished), false);
}
}
void FFMpegPlayer::onDataReady(uint32_t _videoId)
{
// TODO : use signal mapper
if (_videoId != mediaId_)
return;
timer_->stop();
Q_EMIT durationChanged(getDuration());
dataReady_ = true;
if (!getMediaContainer()->is_decods_inited_)
{
getMediaContainer()->VideoDecodeThreadStart(mediaId_);
getMediaContainer()->AudioDecodeThreadStart(mediaId_);
getMediaContainer()->is_decods_inited_ = true;
timer_->start(onDataReadyTimeout());
}
else
{
timer_->start(0);
}
}
void FFMpegPlayer::onAudioTime(uint32_t _videoId, int64_t _avtime, double _offset)
{
if (_videoId != mediaId_)
return;
if (seek_request_id_ > 0)
return;
auto media = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media)
return;
//qDebug() << "media->syncWithAudio_ = " << media->syncWithAudio_;
media->syncWithAudio_ = true;
media->audioClock_ = _offset;
media->audioClockTime_ = _avtime;
qCDebug(ffmpegPlayer) << "media->audioClock_" << media->audioClock_;
qCDebug(ffmpegPlayer) << "media->audioClockTime_" << media->audioClockTime_;
}
uint32_t FFMpegPlayer::stop()
{
if (stopped_)
return mediaId_;
state_ = decode_thread_state::dts_none;
timer_->stop();
decodedFrames_.clear();
if (!continius_)
stopped_ = true;
getMediaContainer()->ctx_.setVideoQuit(mediaId_);
const auto messsage = ThreadMessage(mediaId_, thread_message_type::tmt_quit);
getMediaContainer()->postDemuxThreadMessage(messsage, true, true);
getMediaContainer()->postVideoThreadMessage(messsage, true, true);
getMediaContainer()->postAudioThreadMessage(messsage, true, true);
auto ret = mediaId_;
mediaId_ = 0;
return ret;
}
void FFMpegPlayer::updateVideoPosition(const DecodedFrame& _frame)
{
if (_frame.eof_)
{
auto media = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media)
return;
Q_EMIT positionChanged(getMediaContainer()->getDuration(*media));
lastVideoPosition_ = 0;
lastPostedPosition_ = 0;
}
else if (seek_request_id_ == 0)
{
qint64 videoClock = (_frame.pts_ * 1000);
lastVideoPosition_ = videoClock;
if ((lastVideoPosition_ - lastPostedPosition_) > updatePositonRate_)
{
lastPostedPosition_ = lastVideoPosition_;
Q_EMIT positionChanged(lastVideoPosition_);
}
}
}
void FFMpegPlayer::onTimer()
{
qCDebug(ffmpegPlayer) << "real timer time = " << int((std::chrono::system_clock::now() - prev_frame_time_) / std::chrono::milliseconds(1));
auto renderer = weak_renderer_.lock();
if (!getStarted())
{
if (renderer)
renderer->redraw();
pause();
return;
}
auto media = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media)
{
timer_->stop();
return;
}
if (isFirstFrame_)
{
isFirstFrame_ = false;
getMediaContainer()->resetFrameTimer(*media);
}
if (getMediaContainer()->isQuit(mediaId_))
{
timer_->stop();
return;
}
if (state_ != decode_thread_state::dts_playing)
return;
if (decodedFrames_.empty())
{
if (getStarted())
{
const int interval = std::min(100., (media->frameLastDelay_ > 0. ? media->frameLastDelay_ : 0.1) * 1000.0 + 0.5);
qCDebug(ffmpegPlayer) << "!!! decoded frames empty, timer restart" << interval << "id" << mediaId_;
timer_->start(interval);
}
getMediaContainer()->postVideoThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_get_next_video_frame), false);
return;
}
if (dataReady_)
{
Q_EMIT dataReady();
dataReady_ = false;
}
auto& frame = decodedFrames_.front();
updateVideoPosition(frame);
if (frame.eof_)
{
decodedFrames_.pop_front();
timer_->stop();
if (continius_ && !replay_)
{
stop();
loadFromQueue();
}
else
{
state_ = decode_thread_state::dts_end_of_media;
}
if (renderer)
{
if (firstFrame_ && !continius_)
renderer->updateFrame(firstFrame_->image_);
renderer->redraw();
}
// // TODO : use another way
// if (!continius_ || mediaId_ != 0)
// play(true);
if (replay_)
{
play(true);
}
else
{
stop();
Q_EMIT mediaFinished();
}
return;
}
//qDebug() << "send "<< QTime::currentTime() <<"get next id onTimer2 " << mediaId_;
getMediaContainer()->postVideoThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_get_next_video_frame), false);
if (renderer)
renderer->updateFrame(frame.image_);
ThreadMessage msg(mediaId_, thread_message_type::tmt_empty_frame);
msg.setEmptyFrame(std::exchange(frame.image_, {}));
getMediaContainer()->postVideoThreadMessage(msg, false);
prev_frame_time_ = std::chrono::system_clock::now();
double delay = (seek_request_id_ ? 0.1 : getMediaContainer()->computeDelay(frame.pts_, *media));
int timeout = (int)(delay * 1000.0 + 0.5);
if (getStarted() && timeout != timer_->interval())
{
qCDebug(ffmpegPlayer) << "restart timer" << timer_->interval() << "->" << timeout;
timer_->setInterval(timeout);
}
qCDebug(ffmpegPlayer) << "seek" << seek_request_id_ << "delay" << delay << "timeout is =" << timeout;
decodedFrames_.pop_front();
if (renderer)
renderer->redraw();
}
bool FFMpegPlayer::openMedia(const QString& _mediaPath, bool _isLottie, bool _isLottieInstantPreview, uint32_t _id)
{
if (!continius_)
stopped_ = false;
uint32_t mediaId = getMediaContainer()->init(_id);
openStreamsConnection_ = connect(&getMediaContainer()->ctx_, &VideoContext::streamsOpened, this, &FFMpegPlayer::onStreamsOpened);
auto media = getMediaContainer()->ctx_.getMediaData(mediaId);
if (!media)
return false;
media->isLottie_ = _isLottie;
if (_isLottie && _isLottieInstantPreview)
setPreview(LottieHandleCache::instance().getHandle(_mediaPath).renderFirstFrame(getVideoSize()));
getMediaContainer()->DemuxThreadStart(mediaId);
auto msg = ThreadMessage(mediaId, thread_message_type::tmt_open_streams);
msg.str_ = _mediaPath;
getMediaContainer()->postDemuxThreadMessage(msg, false);
if (mediaId_ == 0 || !continius_)
{
mediaId_ = mediaId;
Q_EMIT mediaChanged(mediaId_);
}
else
{
if (_id != 0)
queuedMedia_.push_front(mediaId);
else
queuedMedia_.push_back(mediaId);
}
return true;// getMediaContainer()->openFile(_mediaPath, *media);
}
void FFMpegPlayer::onRendererSize(const QSize _sz)
{
getMediaContainer()->updateVideoScaleSize(getMedia(), Utils::scale_bitmap(_sz));
}
void FFMpegPlayer::onStreamsOpened(uint32_t _videoId)
{
if (_videoId != mediaId_)
{
if (!continius_)
return;
const auto queued = std::find(queuedMedia_.begin(), queuedMedia_.end(), _videoId);
if (queued == queuedMedia_.end())
return;
}
disconnect(openStreamsConnection_);
auto media = getMediaContainer()->ctx_.getMediaData(_videoId);
if (!media || !media->hasVideo())
return;
getMediaContainer()->openFile(*media);
Q_EMIT fileLoaded();
}
void FFMpegPlayer::play(bool _init)
{
qCDebug(ffmpegPlayer) << "call play(bool _init = " << _init << ')';
if (!_init)
{
if (auto renderer = weak_renderer_.lock())
renderer->redraw();
return;
}
auto media_ptr = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media_ptr)
return;
auto& media = *media_ptr;
setStarted(_init);
if (state_ == decode_thread_state::dts_none)
{
QObject::connect(&getMediaContainer()->ctx_, &VideoContext::demuxInited, this, [this](const uint32_t _videoId)
{
if (_videoId != mediaId_)
return;
if (state_ == decode_thread_state::dts_playing || state_ == decode_thread_state::dts_paused)
{
ThreadMessage msg(mediaId_, thread_message_type::tmt_init);
getMediaContainer()->postVideoThreadMessage(msg, false);
msg.x_ = mute_;
msg.y_ = volume_;
getMediaContainer()->postAudioThreadMessage(msg, false);
if (auto renderer = weak_renderer_.lock())
onRendererSize(renderer->getWidget()->size());
getMediaContainer()->postVideoThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_get_next_video_frame), false);
if (auto media_ptr = getMediaContainer()->ctx_.getMediaData(mediaId_))
getMediaContainer()->resetFrameTimer(*media_ptr);
}
});
getMediaContainer()->DemuxThreadStart(mediaId_);
getMediaContainer()->postDemuxThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_init), false);
}
else if (/*started_ || */state_ == decode_thread_state::dts_paused)
{
getMediaContainer()->postDemuxThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_play), false);
getMediaContainer()->postVideoThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_play), false);
getMediaContainer()->postAudioThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_play), false);
timer_->start(0);
getMediaContainer()->resetFrameTimer(media);
}
else if (state_ == decode_thread_state::dts_end_of_media)
{
setPosition(0);
getMediaContainer()->postDemuxThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_play), false);
getMediaContainer()->postVideoThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_play), false);
getMediaContainer()->postAudioThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_play), false);
state_ = decode_thread_state::dts_playing;
getMediaContainer()->resetFrameTimer(media);
timer_->start(0);
}
state_ = decode_thread_state::dts_playing;
Q_EMIT played();
}
bool FFMpegPlayer::canPause() const
{
auto renderer = weak_renderer_.lock();
return renderer && !renderer->isActiveImageNull();
}
void FFMpegPlayer::pause()
{
qCDebug(ffmpegPlayer) << "call pause()";
if (state_ == decode_thread_state::dts_playing && canPause())
{
// don't pause demux thread fix for getNextFrame
//getMediaContainer()->postDemuxThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_pause), false);
getMediaContainer()->postVideoThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_pause), false);
getMediaContainer()->postAudioThreadMessage(ThreadMessage(mediaId_, thread_message_type::tmt_pause), false);
state_ = decode_thread_state::dts_paused;
}
timer_->stop();
Q_EMIT paused();
}
void FFMpegPlayer::setPosition(int64_t _position)
{
++seek_request_id_; // for video thread
++seek_request_id_; // for audio thread
qCDebug(ffmpegPlayer) << "seek request id = " << seek_request_id_ << " position = " << _position << " videoId = " << mediaId_;
auto media = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media)
return;
media->syncWithAudio_ = false;
media->audioClock_ = 0.0;
media->audioClockTime_ = 0;
//qDebug() << "media->syncWithAudio_ = " << media->syncWithAudio_;
decodedFrames_.clear();
ThreadMessage msg(mediaId_, thread_message_type::tmt_seek_position);
msg.x_ = (int32_t)_position;
getMediaContainer()->postDemuxThreadMessage(msg, false);
getMediaContainer()->postVideoThreadMessage(msg, false);
getMediaContainer()->postAudioThreadMessage(msg, false);
getMediaContainer()->resetFrameTimer(*media);
getMediaContainer()->resetLastFramePts(*media);
lastVideoPosition_ = _position;
lastPostedPosition_ = _position;
}
void FFMpegPlayer::resetPosition()
{
lastVideoPosition_ = 0;
lastPostedPosition_ = 0;
}
void FFMpegPlayer::setUpdatePositionRate(int _rate)
{
updatePositonRate_ = _rate;
}
void FFMpegPlayer::setVolume(int32_t _volume)
{
volume_ = _volume;
ThreadMessage msg(mediaId_, thread_message_type::tmt_set_volume);
msg.x_ = _volume;
getMediaContainer()->postAudioThreadMessage(msg, false);
}
int32_t FFMpegPlayer::getVolume() const
{
return volume_;
}
void FFMpegPlayer::setMute(bool _mute)
{
ThreadMessage msg(mediaId_, thread_message_type::tmt_set_mute);
msg.x_ = _mute;
getMediaContainer()->postAudioThreadMessage(msg, false);
mute_ = _mute;
}
bool FFMpegPlayer::isMute() const
{
return mute_;
}
QSize FFMpegPlayer::getVideoSize() const
{
auto media_ptr = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media_ptr)
return QSize();
auto& media = *media_ptr;
auto size = getMediaContainer()->ctx_.getSourceSize(media);
if (auto rot = getVideoRotation(); rot == 90 || rot == 270)
return size.transposed();
return size;
}
int32_t FFMpegPlayer::getVideoRotation() const
{
auto media_ptr = getMediaContainer()->ctx_.getMediaData(mediaId_);
if (!media_ptr)
return 0;
return getMediaContainer()->getRotation(*media_ptr);
}
int64_t FFMpegPlayer::getDuration() const
{
if (auto media = getMediaContainer()->ctx_.getMediaData(mediaId_))
return media->duration_;
return -1;
}
bool FFMpegPlayer::eventFilter(QObject* _obj, QEvent* _event)
{
if (auto renderer = weak_renderer_.lock())
{
QObject* objectRenderer = qobject_cast<QObject*>(renderer->getWidget());
if (objectRenderer == _obj)
{
if (QEvent::Leave == _event->type())
{
Q_EMIT mouseLeaveEvent(QPrivateSignal());
}
else if (QEvent::MouseMove == _event->type())
{
const auto currentTime = std::chrono::system_clock::now();
if (currentTime - lastEmitMouseMove_ > mouse_move_rate)
{
lastEmitMouseMove_ = currentTime;
Q_EMIT mouseMoved(QPrivateSignal());
}
}
}
}
return QObject::eventFilter(_obj, _event);
}
void FFMpegPlayer::setPaused(bool _paused)
{
if (_paused)
{
pause();
}
else
{
play(false /* _init */);
}
}
void FFMpegPlayer::setPausedByUser(const bool _paused)
{
pausedByUser_ = _paused;
}
bool FFMpegPlayer::isPausedByUser() const
{
return pausedByUser_;
}
QMovie::MovieState FFMpegPlayer::state() const
{
if (state_ == decode_thread_state::dts_playing)
return QMovie::Running;
else if (state_ == decode_thread_state::dts_paused)
return QMovie::Paused;
else
return QMovie::NotRunning;
}
void FFMpegPlayer::setPreview(QPixmap _preview)
{
setPreview(_preview.toImage());
}
void FFMpegPlayer::setPreview(QImage _preview)
{
if (auto renderer = weak_renderer_.lock())
{
renderer->updateFrame(_preview);
renderer->redraw();
}
}
QPixmap FFMpegPlayer::getActiveImage() const
{
if (auto renderer = weak_renderer_.lock())
return QPixmap::fromImage(renderer->getActiveImage());
return QPixmap();
}
QImage FFMpegPlayer::getFirstFrame() const
{
return firstFrame_ ? firstFrame_->image_ : QImage();
}
bool FFMpegPlayer::getStarted() const
{
return started_;
}
void FFMpegPlayer::setStarted(bool _started)
{
started_ = _started;
}
void FFMpegPlayer::loadFromQueue()
{
if (queuedMedia_.empty())
{
Q_EMIT mediaChanged(-1);
return;
}
mediaId_ = queuedMedia_.front();
queuedMedia_.pop_front();
Q_EMIT mediaChanged(mediaId_);
}
void FFMpegPlayer::removeFromQueue(uint32_t _media)
{
queuedMedia_.remove(_media);
}
void FFMpegPlayer::clearQueue()
{
for (auto i : queuedMedia_)
{
getMediaContainer()->ctx_.setVideoQuit(i);
const auto message = ThreadMessage(i, thread_message_type::tmt_quit);
getMediaContainer()->postDemuxThreadMessage(message, true, true);
getMediaContainer()->postVideoThreadMessage(message, true, true);
getMediaContainer()->postAudioThreadMessage(message, true, true);
}
queuedMedia_.clear();
}
bool FFMpegPlayer::queueIsEmpty() const
{
return queuedMedia_.empty();
}
int FFMpegPlayer::queueSize() const
{
return queuedMedia_.size();
}
uint32_t FFMpegPlayer::getLastMedia() const
{
return queuedMedia_.empty() ? mediaId_ : queuedMedia_.back();
}
uint32_t FFMpegPlayer::getMedia() const
{
return mediaId_;
}
uint32_t FFMpegPlayer::reserveId()
{
return getMediaContainer()->ctx_.reserveId();
}
void FFMpegPlayer::setReplay(bool _replay)
{
replay_ = _replay;
}
void FFMpegPlayer::setRestoreVolume(const int32_t _volume)
{
restoreVolume_ = volume_;
}
int32_t FFMpegPlayer::getRestoreVolume() const
{
return restoreVolume_;
}
void FFMpegPlayer::setRenderer(std::shared_ptr<FrameRenderer> _renderer)
{
_renderer->filterEvents(this);
_renderer->setSizeCallback([this](auto _size) { onRendererSize(_size); });
onRendererSize(_renderer->getWidget()->size());
weak_renderer_ = std::move(_renderer);
}
//////////////////////////////////////////////////////////////////////////
// MediaContainer
//////////////////////////////////////////////////////////////////////////
std::unique_ptr<MediaContainer> g_media_container;
MediaContainer* getMediaContainer()
{
if (!g_media_container)
{
Utils::ensureMainThread();
g_media_container = std::make_unique<MediaContainer>();
}
return g_media_container.get();
}
void ResetMediaContainer()
{
if (g_media_container)
g_media_container.reset();
}
MediaContainer::MediaContainer()
: is_decods_inited_(false)
, is_demux_inited_(false)
, demuxThread_(ctx_)
, videoDecodeThread_(ctx_)
, audioDecodeThread_(ctx_)
{}
MediaContainer::~MediaContainer()
{
Utils::ensureMainThread();
if (ctx_.isQuit())
return;
setQuit();
const auto message = ThreadMessage(0, thread_message_type::tmt_wake_up);
postDemuxThreadMessage(message, true);
postVideoThreadMessage(message, true);
postAudioThreadMessage(message, true);
VideoDecodeThreadWait();
AudioDecodeThreadWait();
DemuxThreadWait();
ffmpeg::av_lockmgr_register(NULL);
ffmpeg::avformat_network_deinit();
}
void MediaContainer::VideoDecodeThreadStart(uint32_t _mediaId)
{
videoDecodeThread_.start();
}
void MediaContainer::AudioDecodeThreadStart(uint32_t _mediaId)
{
audioDecodeThread_.start();
}
void MediaContainer::DemuxThreadStart(uint32_t _mediaId)
{
if (!is_demux_inited_)
{
demuxThread_.start();
is_demux_inited_ = true;
}
}
void MediaContainer::stopMedia(uint32_t _mediaId)
{
//qDebug() << "stop media " << _mediaId;
if (active_video_ids_.count(_mediaId) == 0)
return;
active_video_ids_.erase(_mediaId);
if (!active_video_ids_.empty())
return;
if (ctx_.isQuit())
return;
setQuit();
postDemuxThreadMessage(ThreadMessage(_mediaId, thread_message_type::tmt_wake_up), true);
postVideoThreadMessage(ThreadMessage(_mediaId, thread_message_type::tmt_wake_up), true);
postAudioThreadMessage(ThreadMessage(_mediaId, thread_message_type::tmt_wake_up), true);
//qDebug() << "before wait " << QTime::currentTime();
VideoDecodeThreadWait();
AudioDecodeThreadWait();
DemuxThreadWait();
clearMessageQueue();
//qDebug() << "after wait " << QTime::currentTime();
is_decods_inited_ = false;
is_demux_inited_ = false;
ffmpeg::av_lockmgr_register(NULL);
}
int32_t MediaContainer::getWidth(MediaData& _media) const
{
return ctx_.getWidth(_media);
}
int32_t MediaContainer::getHeight(MediaData& _media) const
{
return ctx_.getHeight(_media);
}
int32_t MediaContainer::getRotation(MediaData& _media) const
{
return ctx_.getRotation(_media);
}
int64_t MediaContainer::getDuration(MediaData& _media) const
{
return ctx_.getDuration(_media);
}
void MediaContainer::postVideoThreadMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
ctx_.postVideoThreadMessage(_message, _forward, _clear_others);
}
void MediaContainer::updateVideoScaleSize(const uint32_t _mediaId, const QSize _sz)
{
ctx_.updateScaledVideoSize(_mediaId, _sz);
}
void MediaContainer::postDemuxThreadMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
ctx_.postDemuxThreadMessage(_message, _forward, _clear_others);
}
void MediaContainer::postAudioThreadMessage(const ThreadMessage& _message, bool _forward, bool _clear_others)
{
ctx_.postAudioThreadMessage(_message, _forward, _clear_others);
}
void MediaContainer::clearMessageQueue()
{
ctx_.clearMessageQueue();
}
void MediaContainer::resetFrameTimer(MediaData& _media)
{
ctx_.resetFrameTimer(_media);
}
void MediaContainer::resetLastFramePts(MediaData& _media)
{
ctx_.resetLastFramePts(_media);
}
bool MediaContainer::isQuit(uint32_t _mediaId) const
{
return ctx_.isQuit();
}
void MediaContainer::setQuit(bool _val)
{
//qDebug() << "setQuit " << _val << " " << QTime::currentTime();
ctx_.setQuit(_val);
}
bool MediaContainer::openFile(MediaData& _media)
{
return ctx_.openFile(_media);
}
void MediaContainer::closeFile(MediaData& _media)
{
ctx_.closeFile(_media);
}
double MediaContainer::computeDelay(double _picturePts, MediaData& _media)
{
return ctx_.computeDelay(_picturePts, _media);
}
uint32_t MediaContainer::init(uint32_t _id)
{
auto id = ctx_.addVideo(_id);
if (active_video_ids_.empty())
{
ffmpeg::av_init_packet(&quit_pkt);
quit_pkt.data = (uint8_t*)&quit_pkt;
}
auto media_ptr = getMediaContainer()->ctx_.getMediaData(id);
if (media_ptr)
{
auto& media = *media_ptr;
ctx_.init(media);
if (active_video_ids_.empty())
{
setQuit(false);
Ui::GetSoundsManager();
}
active_video_ids_.insert(id);
}
else
{
im_assert(!"MediaContainer: fail on init");
}
return id;
}
void MediaContainer::DemuxThreadWait()
{
demuxThread_.wait();
}
void MediaContainer::VideoDecodeThreadWait()
{
videoDecodeThread_.wait();
}
void MediaContainer::AudioDecodeThreadWait()
{
audioDecodeThread_.wait();
}
MediaContainer* getMediaPreview(const QString& _media)
{
Ui::ThreadMessage msg;
msg.str_ = _media;
msg.message_ = thread_message_type::tmt_get_first_frame;
MediaContainer* container = getMediaContainer();
container->postDemuxThreadMessage(msg, false);
return container;
}
}
|
#ifdef _WIN32
#include "../file_operations.h"
#include "win_extend_path_limit.h"
#include <system_error> // std::system_error
#include <ctime> // std::time_t
#include <Windows.h> // WinAPI
namespace filesystem
{
bool isExists(const Path &path)
{
const auto result = GetFileAttributesW(MAKE_EXTENDED_PATH(path).c_str());
if (result == INVALID_FILE_ATTRIBUTES)
{
const auto err = GetLastError();
switch (err)
{
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
return false;
default:
throw std::system_error(GetLastError(), std::system_category());
}
}
return true;
}
FileType getFileType(const Path &path)
{
const auto result = GetFileAttributesW(MAKE_EXTENDED_PATH(path).c_str());
if (result == INVALID_FILE_ATTRIBUTES)
{
throw std::system_error(GetLastError(), std::system_category());
}
return (result & FILE_ATTRIBUTE_DIRECTORY) ? FileType::directory : FileType::file;
}
std::uint64_t getFileSize(const Path &path)
{
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
if (!GetFileAttributesExW(MAKE_EXTENDED_PATH(path).c_str(),
GetFileExInfoStandard,
&fileInfo))
{
throw std::system_error(GetLastError(), std::system_category());
}
ULARGE_INTEGER result;
result.LowPart = fileInfo.nFileSizeLow;
result.HighPart = fileInfo.nFileSizeHigh;
return result.QuadPart;
}
std::chrono::system_clock::time_point getModifyDate(const Path &path)
{
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
if (!GetFileAttributesExW(MAKE_EXTENDED_PATH(path).c_str(),
GetFileExInfoStandard,
&fileInfo))
{
throw std::system_error(GetLastError(), std::system_category());
}
ULARGE_INTEGER result;
result.LowPart = fileInfo.ftLastWriteTime.dwLowDateTime;
result.HighPart = fileInfo.ftLastWriteTime.dwHighDateTime;
return std::chrono::system_clock::from_time_t(result.QuadPart / 10000000ULL - 11644473600ULL);
}
void rename(const Path &oldPath, const Path &newPath)
{
if (!MoveFileW(MAKE_EXTENDED_PATH(oldPath).c_str(), MAKE_EXTENDED_PATH(newPath).c_str()))
{
throw std::system_error(GetLastError(), std::system_category());
}
}
}
#else // #ifdef _WIN32
#error "Macro _WIN32 isn't defined. Check target OS (required Windows) for this build"
#endif // #ifdef _WIN32
|
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*
* PublisherImpl.cpp
*
*/
#include <fastdds/publisher/PublisherImpl.hpp>
#include <fastdds/publisher/DataWriterImpl.hpp>
#include <fastdds/domain/DomainParticipantImpl.hpp>
#include <fastdds/topic/TopicDescriptionImpl.hpp>
#include <fastdds/dds/publisher/Publisher.hpp>
#include <fastdds/dds/publisher/PublisherListener.hpp>
#include <fastdds/dds/publisher/DataWriter.hpp>
#include <fastdds/dds/publisher/qos/DataWriterQos.hpp>
#include <fastdds/dds/topic/TypeSupport.hpp>
#include <fastdds/rtps/participant/RTPSParticipant.h>
#include <fastdds/dds/log/Log.hpp>
#include <fastrtps/attributes/PublisherAttributes.h>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <functional>
namespace eprosima {
namespace fastdds {
namespace dds {
using fastrtps::xmlparser::XMLProfileManager;
using fastrtps::xmlparser::XMLP_ret;
using fastrtps::rtps::InstanceHandle_t;
using fastrtps::Duration_t;
using fastrtps::PublisherAttributes;
static void set_qos_from_attributes(
DataWriterQos& qos,
const PublisherAttributes& attr)
{
qos.writer_resource_limits().matched_subscriber_allocation = attr.matched_subscriber_allocation;
qos.properties() = attr.properties;
qos.throughput_controller() = attr.throughputController;
qos.endpoint().unicast_locator_list = attr.unicastLocatorList;
qos.endpoint().multicast_locator_list = attr.multicastLocatorList;
qos.endpoint().remote_locator_list = attr.remoteLocatorList;
qos.endpoint().history_memory_policy = attr.historyMemoryPolicy;
qos.endpoint().user_defined_id = attr.getUserDefinedID();
qos.endpoint().entity_id = attr.getEntityID();
qos.reliable_writer_qos().times = attr.times;
qos.reliable_writer_qos().disable_positive_acks = attr.qos.m_disablePositiveACKs;
qos.durability() = attr.qos.m_durability;
qos.durability_service() = attr.qos.m_durabilityService;
qos.deadline() = attr.qos.m_deadline;
qos.latency_budget() = attr.qos.m_latencyBudget;
qos.liveliness() = attr.qos.m_liveliness;
qos.reliability() = attr.qos.m_reliability;
qos.lifespan() = attr.qos.m_lifespan;
qos.user_data().setValue(attr.qos.m_userData);
qos.ownership() = attr.qos.m_ownership;
qos.ownership_strength() = attr.qos.m_ownershipStrength;
qos.destination_order() = attr.qos.m_destinationOrder;
qos.representation() = attr.qos.representation;
qos.publish_mode() = attr.qos.m_publishMode;
qos.history() = attr.topic.historyQos;
qos.resource_limits() = attr.topic.resourceLimitsQos;
}
PublisherImpl::PublisherImpl(
DomainParticipantImpl* p,
const PublisherQos& qos,
PublisherListener* listen)
: participant_(p)
, qos_(&qos == &PUBLISHER_QOS_DEFAULT ? participant_->get_default_publisher_qos() : qos)
, listener_(listen)
, publisher_listener_(this)
, user_publisher_(nullptr)
, rtps_participant_(p->rtps_participant())
, default_datawriter_qos_(DATAWRITER_QOS_DEFAULT)
{
PublisherAttributes pub_attr;
XMLProfileManager::getDefaultPublisherAttributes(pub_attr);
set_qos_from_attributes(default_datawriter_qos_, pub_attr);
}
void PublisherImpl::disable()
{
set_listener(nullptr);
user_publisher_->set_listener(nullptr);
{
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto it = writers_.begin(); it != writers_.end(); ++it)
{
for (DataWriterImpl* dw : it->second)
{
dw->disable();
}
}
}
}
PublisherImpl::~PublisherImpl()
{
{
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto it = writers_.begin(); it != writers_.end(); ++it)
{
for (DataWriterImpl* dw : it->second)
{
delete dw;
}
}
writers_.clear();
}
delete user_publisher_;
}
const PublisherQos& PublisherImpl::get_qos() const
{
return qos_;
}
ReturnCode_t PublisherImpl::set_qos(
const PublisherQos& qos)
{
if (&qos == &PUBLISHER_QOS_DEFAULT)
{
const PublisherQos& default_qos = participant_->get_default_publisher_qos();
if (!can_qos_be_updated(qos_, default_qos))
{
return ReturnCode_t::RETCODE_IMMUTABLE_POLICY;
}
set_qos(qos_, default_qos, false);
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto topic_writers : writers_)
{
for (auto writer : topic_writers.second)
{
writer->publisher_qos_updated();
}
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t ret_val = check_qos(qos);
if (!ret_val)
{
return ret_val;
}
if (!can_qos_be_updated(qos_, qos))
{
return ReturnCode_t::RETCODE_IMMUTABLE_POLICY;
}
set_qos(qos_, qos, false);
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto topic_writers : writers_)
{
for (auto writer : topic_writers.second)
{
writer->publisher_qos_updated();
}
}
return ReturnCode_t::RETCODE_OK;
}
const PublisherListener* PublisherImpl::get_listener() const
{
return listener_;
}
ReturnCode_t PublisherImpl::set_listener(
PublisherListener* listener)
{
listener_ = listener;
return ReturnCode_t::RETCODE_OK;
}
void PublisherImpl::PublisherWriterListener::on_publication_matched(
DataWriter* writer,
const PublicationMatchedStatus& info)
{
if (publisher_->listener_ != nullptr)
{
publisher_->listener_->on_publication_matched(writer, info);
}
}
void PublisherImpl::PublisherWriterListener::on_liveliness_lost(
DataWriter* writer,
const LivelinessLostStatus& status)
{
if (publisher_->listener_ != nullptr)
{
publisher_->listener_->on_liveliness_lost(writer, status);
}
}
void PublisherImpl::PublisherWriterListener::on_offered_deadline_missed(
DataWriter* writer,
const fastrtps::OfferedDeadlineMissedStatus& status)
{
if (publisher_->listener_ != nullptr)
{
publisher_->listener_->on_offered_deadline_missed(writer, status);
}
}
DataWriter* PublisherImpl::create_datawriter(
Topic* topic,
const DataWriterQos& qos,
DataWriterListener* listener,
const StatusMask& mask)
{
logInfo(PUBLISHER, "CREATING WRITER IN TOPIC: " << topic->get_name());
//Look for the correct type registration
TypeSupport type_support = participant_->find_type(topic->get_type_name());
/// Preconditions
// Check the type was registered.
if (type_support.empty())
{
logError(PUBLISHER, "Type: " << topic->get_type_name() << " Not Registered");
return nullptr;
}
if (!DataWriterImpl::check_qos(qos))
{
return nullptr;
}
topic->get_impl()->reference();
DataWriterImpl* impl = new DataWriterImpl(
this,
type_support,
topic,
qos,
listener);
if (impl->writer_ == nullptr)
{
logError(PUBLISHER, "Problem creating associated Writer");
delete impl;
topic->get_impl()->dereference();
return nullptr;
}
DataWriter* writer = new DataWriter(impl, mask);
impl->user_datawriter_ = writer;
//REGISTER THE WRITER
WriterQos wqos = qos.get_writerqos(qos_, topic->get_qos());
fastrtps::TopicAttributes topic_att = DataWriterImpl::get_topic_attributes(qos, *topic, type_support);
rtps_participant_->registerWriter(impl->writer_, topic_att, wqos);
{
std::lock_guard<std::mutex> lock(mtx_writers_);
writers_[topic->get_name()].push_back(impl);
}
return writer;
}
DataWriter* PublisherImpl::create_datawriter_with_profile(
Topic* topic,
const std::string& profile_name,
DataWriterListener* listener,
const StatusMask& mask)
{
// TODO (ILG): Change when we have full XML support for DDS QoS profiles
PublisherAttributes attr;
if (XMLP_ret::XML_OK == XMLProfileManager::fillPublisherAttributes(profile_name, attr))
{
DataWriterQos qos = default_datawriter_qos_;
set_qos_from_attributes(qos, attr);
return create_datawriter(topic, qos, listener, mask);
}
return nullptr;
}
ReturnCode_t PublisherImpl::delete_datawriter(
DataWriter* writer)
{
if (user_publisher_ != writer->get_publisher())
{
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
std::lock_guard<std::mutex> lock(mtx_writers_);
auto vit = writers_.find(writer->get_topic()->get_name());
if (vit != writers_.end())
{
auto dw_it = std::find(vit->second.begin(), vit->second.end(), writer->impl_);
if (dw_it != vit->second.end())
{
(*dw_it)->set_listener(nullptr);
(*dw_it)->get_topic()->get_impl()->dereference();
delete (*dw_it);
vit->second.erase(dw_it);
if (vit->second.empty())
{
writers_.erase(vit);
}
return ReturnCode_t::RETCODE_OK;
}
}
return ReturnCode_t::RETCODE_ERROR;
}
DataWriter* PublisherImpl::lookup_datawriter(
const std::string& topic_name) const
{
std::lock_guard<std::mutex> lock(mtx_writers_);
auto it = writers_.find(topic_name);
if (it != writers_.end() && it->second.size() > 0)
{
return it->second.front()->user_datawriter_;
}
return nullptr;
}
bool PublisherImpl::get_datawriters(
std::vector<DataWriter*>& writers) const
{
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto vit : writers_)
{
for (DataWriterImpl* dw : vit.second)
{
writers.push_back(dw->user_datawriter_);
}
}
return true;
}
bool PublisherImpl::has_datawriters() const
{
if (writers_.empty())
{
return false;
}
return true;
}
bool PublisherImpl::contains_entity(
const fastrtps::rtps::InstanceHandle_t& handle) const
{
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto vit : writers_)
{
for (DataWriterImpl* dw : vit.second)
{
InstanceHandle_t h(dw->guid());
if (h == handle)
{
return true;
}
}
}
return false;
}
/* TODO
bool PublisherImpl::suspend_publications()
{
logError(PUBLISHER, "Operation not implemented");
return false;
}
*/
/* TODO
bool PublisherImpl::resume_publications()
{
logError(PUBLISHER, "Operation not implemented");
return false;
}
*/
/* TODO
bool PublisherImpl::begin_coherent_changes()
{
logError(PUBLISHER, "Operation not implemented");
return false;
}
*/
/* TODO
bool PublisherImpl::end_coherent_changes()
{
logError(PUBLISHER, "Operation not implemented");
return false;
}
*/
ReturnCode_t PublisherImpl::set_default_datawriter_qos(
const DataWriterQos& qos)
{
if (&qos == &DATAWRITER_QOS_DEFAULT)
{
reset_default_datawriter_qos();
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t ret_val = DataWriterImpl::check_qos(qos);
if (!ret_val)
{
return ret_val;
}
DataWriterImpl::set_qos(default_datawriter_qos_, qos, true);
return ReturnCode_t::RETCODE_OK;
}
void PublisherImpl::reset_default_datawriter_qos()
{
// TODO (ILG): Change when we have full XML support for DDS QoS profiles
DataWriterImpl::set_qos(default_datawriter_qos_, DATAWRITER_QOS_DEFAULT, true);
PublisherAttributes attr;
XMLProfileManager::getDefaultPublisherAttributes(attr);
set_qos_from_attributes(default_datawriter_qos_, attr);
}
const DataWriterQos& PublisherImpl::get_default_datawriter_qos() const
{
return default_datawriter_qos_;
}
/* TODO
bool PublisherImpl::copy_from_topic_qos(
fastrtps::WriterQos&,
const fastrtps::TopicAttributes&) const
{
logError(PUBLISHER, "Operation not implemented");
return false;
}
*/
ReturnCode_t PublisherImpl::wait_for_acknowledgments(
const Duration_t& max_wait)
{
Duration_t current = max_wait;
Duration_t begin, end;
std::lock_guard<std::mutex> lock(mtx_writers_);
for (auto& vit : writers_)
{
for (DataWriterImpl* dw : vit.second)
{
participant_->get_current_time(begin);
if (!dw->wait_for_acknowledgments(current))
{
return ReturnCode_t::RETCODE_ERROR;
}
// Check ellapsed time and decrement
participant_->get_current_time(end);
current = current - (end - begin);
if (current < fastrtps::c_TimeZero)
{
return ReturnCode_t::RETCODE_TIMEOUT;
}
}
}
return ReturnCode_t::RETCODE_OK;
}
const DomainParticipant* PublisherImpl::get_participant() const
{
return participant_->get_participant();
}
const Publisher* PublisherImpl::get_publisher() const
{
return user_publisher_;
}
/* TODO
bool PublisherImpl::delete_contained_entities()
{
logError(PUBLISHER, "Operation not implemented");
return false;
}
*/
const InstanceHandle_t& PublisherImpl::get_instance_handle() const
{
return handle_;
}
bool PublisherImpl::type_in_use(
const std::string& type_name) const
{
for (auto it : writers_)
{
for (DataWriterImpl* writer : it.second)
{
if (writer->get_topic()->get_type_name() == type_name)
{
return true; // Is in use
}
}
}
return false;
}
void PublisherImpl::set_qos(
PublisherQos& to,
const PublisherQos& from,
bool first_time)
{
if (first_time && !(to.presentation() == from.presentation()))
{
to.presentation(from.presentation());
to.presentation().hasChanged = true;
}
if (!(to.partition() == from.partition()))
{
to.partition() = from.partition();
to.partition().hasChanged = true;
}
if (!(to.group_data() == from.group_data()))
{
to.group_data() = from.group_data();
to.group_data().hasChanged = true;
}
if (!(to.entity_factory() == from.entity_factory()))
{
to.entity_factory() = from.entity_factory();
}
}
ReturnCode_t PublisherImpl::check_qos(
const PublisherQos& qos)
{
(void) qos;
return ReturnCode_t::RETCODE_OK;
}
bool PublisherImpl::can_qos_be_updated(
const PublisherQos& to,
const PublisherQos& from)
{
(void) to;
(void) from;
return true;
}
} // dds
} // fastdds
} // eprosima
|
#pragma once
#include <GL/glew.h>
#include <gl/GL.h>
#include <glm/glm.hpp>
#include <assimp/scene.h>
#include <vector>
#include <string>
#include "link/types.hpp"
namespace link
{
struct Vertex
{
Vertex() {}
Vertex(const glm::vec3& position, const glm::vec2& tex_coords, const glm::vec3& normal) : Position(position), TexCoords(tex_coords), Normal(normal) {}
glm::vec3 Position;
glm::vec2 TexCoords;
glm::vec3 Normal;
};
struct Mesh
{
u32 VAO, VBO, EBO;
GLenum mode;
std::vector<Vertex> vertices;
std::vector<u32> indices;
Mesh(const std::vector<Vertex>& vertices, const std::vector<u32>& indices, GLenum mode = GL_TRIANGLES);
Mesh(const std::vector<Vertex>& vertices, GLenum mode = GL_TRIANGLES);
void data_updated();
~Mesh();
void draw();
};
}
|
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: VoiceActivityDetectorNode.cpp (nodes)
// Authors: Chris Lovett
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "VoiceActivityDetectorNode.h"
#include <emitters/include/EmitterException.h>
#include <emitters/include/EmitterTypes.h>
#include <emitters/include/IREmitter.h>
#include <emitters/include/IRLocalValue.h>
namespace ell
{
using namespace emitters;
namespace nodes
{
using TickType = int64_t;
template <typename ValueType>
void VoiceActivityDetectorNode<ValueType>::Compute() const
{
int signal = _vad.process(_input.GetValue());
_output.SetOutput({ signal });
};
template <typename ValueType>
void VoiceActivityDetectorNode<ValueType>::Reset()
{
_vad.reset();
}
template <typename ValueType>
void VoiceActivityDetectorNode<ValueType>::Copy(model::ModelTransformer& transformer) const
{
const auto& newPortElements = transformer.GetCorrespondingInputs(_input);
auto newNode = transformer.AddNode<VoiceActivityDetectorNode<ValueType>>(newPortElements, _vad.getSampleRate(), _vad.getFrameDuration(), _vad.getTauUp(), _vad.getTauDown(), _vad.getLargeInput(), _vad.getGainAtt(), _vad.getThresholdUp(), _vad.getThresholdDown(), _vad.getLevelThreshold());
transformer.MapNodeOutput(output, newNode->output);
}
template <typename ValueType>
void VoiceActivityDetectorNode<ValueType>::Compile(model::IRMapCompiler& compiler, IRFunctionEmitter& function)
{
auto tauUpLiteral = function.template Literal<ValueType>(_vad.getTauUp());
auto tauDownLiteral = function.template Literal<ValueType>(_vad.getTauDown());
auto largeInputLiteral = function.template Literal<ValueType>(_vad.getLargeInput());
auto gainAttLiteral = function.template Literal<ValueType>(_vad.getGainAtt());
auto thresholdUpLiteral = function.template Literal<ValueType>(_vad.getThresholdUp());
auto thresholdDownLiteral = function.template Literal<ValueType>(_vad.getThresholdDown());
auto levelThresholdLiteral = function.template Literal<ValueType>(_vad.getLevelThreshold());
TypedOperator add = GetAddForValueType<ValueType>();
TypedOperator addTick = GetAddForValueType<TickType>();
TypedOperator subtract = GetSubtractForValueType<ValueType>();
TypedOperator multiply = GetMultiplyForValueType<ValueType>();
TypedOperator divide = GetDivideForValueType<ValueType>();
auto lessThan = GetComparison<ValueType>(BinaryPredicateType::less);
auto greaterThan = GetComparison<ValueType>(BinaryPredicateType::greater);
LLVMValue pInput = compiler.EnsurePortEmitted(input);
LLVMValue pOutput = compiler.EnsurePortEmitted(output);
const int inputSize = input.Size();
if (inputSize != _vad.getWindowSize())
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Input size must match VoiceActivityDetectorNode windowSize");
}
// assumes ValueType is either float or double.
auto windowSizeLiteral = function.template Literal<ValueType>(static_cast<ValueType>(_vad.getWindowSize()));
auto frameDurationLiteral = function.template Literal<ValueType>(static_cast<ValueType>(_vad.getFrameDuration()));
// Get LLVM types
auto& module = function.GetModule();
auto& emitter = function.GetEmitter();
auto elementType = emitter.Type(GetVariableType<ValueType>());
if (!llvm::VectorType::isValidElementType(elementType))
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Invalid element type for LLVM vector");
}
// Allocate global variable to hold the weights lookup table, first convert the weights to the rigth ValueType.
auto actualWeights = _vad.getWeights();
std::vector<ValueType> weights;
std::transform(actualWeights.begin(), actualWeights.end(), std::back_inserter(weights), [](double x) { return static_cast<ValueType>(x); });
//// Allocate global variable to hold the computed CMessageWeights.
llvm::GlobalVariable* gWeights = module.GlobalArray<ValueType>(compiler.GetGlobalName(*this, "weights"), weights);
//// Allocate global variable to hold the time
llvm::GlobalVariable* ticks = module.Global<TickType>(compiler.GetGlobalName(*this, "ticks"), 0);
// Allocate global variable to hold the previous time
llvm::GlobalVariable* lastTime = module.Global<ValueType>(compiler.GetGlobalName(*this, "lastTime"), 0);
// Allocate global variable to hold the previous power level
llvm::GlobalVariable* lastLevel = module.Global<ValueType>(compiler.GetGlobalName(*this, "lastLevel"), static_cast<ValueType>(0.1));
// Allocate global variable to hold the previous signal (because sometimes this function does not change it).
llvm::GlobalVariable* signal = module.Global<int>(compiler.GetGlobalName(*this, "signal"), 0);
// Compute the weighted power level of the given input (the commented code is from our reference implementation, see VoiceActivityDetector.cpp).
//double level = 0;
//for (int i = 0; i < _impl->_windowSize; i++)
//{
// level += data[i] * _impl->_cmw.getWeight(i);
//}
LLVMValue level = function.Variable(elementType, "level");
function.Store(level, function.Literal(static_cast<ValueType>(0.0)));
function.For(inputSize, [pInput, gWeights, multiply, add, level](IRFunctionEmitter& fn, LLVMValue index) {
auto value = fn.ValueAt(pInput, index);
auto w = fn.ValueAt(gWeights, index);
fn.OperationAndUpdate(level, add, fn.Operator(multiply, value, w));
});
// level = level / (double)_impl->_windowSize
function.OperationAndUpdate(level, divide, windowSizeLiteral);
// double time = _impl->_time++ * _impl->_frameDuration;
LLVMValue time = function.Variable(elementType, "time");
function.Store(time, function.CastValue<ValueType>(function.Load(ticks)));
function.OperationAndUpdate(time, multiply, frameDurationLiteral);
function.OperationAndUpdate(ticks, addTick, function.template Literal<TickType>(1)); // _time++
// signal = _impl->_tracker.classify(t, level);
//double timeDelta = time - this->_lastTime;
LLVMValue timeDelta = function.Variable(elementType, "timeDelta");
function.Store(timeDelta, function.Load(time));
function.OperationAndUpdate(timeDelta, subtract, function.Load(lastTime));
//double levelDelta = level - this->_lastLevel;
LLVMValue levelDelta = function.Variable(elementType, "levelDelta");
function.Store(levelDelta, function.Load(level));
function.OperationAndUpdate(levelDelta, subtract, function.Load(lastLevel));
// bugbug: the comparisons have to be done first outside the If/ElseIf/Else block otherwise we get weird compile errors.
auto cmp1 = function.Comparison(lessThan, function.Load(level), function.Load(lastLevel));
auto cmp2 = function.Comparison(greaterThan, function.Load(level), function.Operator(multiply, largeInputLiteral, function.Load(lastLevel)));
// for the function.If "endOnDestruct" to happen at the right time, if1 needs to be inside it's own block
{
//if (level < this->_lastLevel)
//{
// this->_lastLevel = this->_lastLevel + timeDelta / this->_tauDown * levelDelta;
// if (this->_lastLevel < level)
// {
// this->_lastLevel = level;
// }
//}
auto if1 = function.If(cmp1, [=](IRFunctionEmitter& fn) {
fn.Store(lastLevel, fn.Operator(add, fn.Load(lastLevel), fn.Operator(multiply, fn.Operator(divide, fn.Load(timeDelta), tauDownLiteral), fn.Load(levelDelta))));
fn.If(fn.Comparison(lessThan, fn.Load(lastLevel), fn.Load(level)), [lastLevel, level](IRFunctionEmitter& fn) {
fn.Store(lastLevel, fn.Load(level));
});
});
//else if (level > this->_largeInput * this->_lastLevel)
//{
// this->_lastLevel = this->_lastLevel + this->_gainAtt * timeDelta / this->_tauUp * levelDelta;
// if (this->_lastLevel > level)
// {
// this->_lastLevel = level;
// }
//}
if1.ElseIf(cmp2, [=](IRFunctionEmitter& fn) {
fn.Store(lastLevel, fn.Operator(add, fn.Load(lastLevel), fn.Operator(multiply, gainAttLiteral, fn.Operator(multiply, fn.Operator(divide, fn.Load(timeDelta), tauUpLiteral), fn.Load(levelDelta)))));
fn.If(fn.Comparison(greaterThan, fn.Load(lastLevel), fn.Load(level)), [lastLevel, level](IRFunctionEmitter& fn) {
fn.Store(lastLevel, fn.Load(level));
});
});
//else
//{
// this->_lastLevel = this->_lastLevel + timeDelta / this->_tauUp * levelDelta;
// if (this->_lastLevel > level)
// {
// this->_lastLevel = level;
// }
//}
if1.Else([=](IRFunctionEmitter& fn) {
fn.Store(lastLevel, fn.Operator(add, fn.Load(lastLevel), fn.Operator(multiply, fn.Operator(divide, fn.Load(timeDelta), tauUpLiteral), fn.Load(levelDelta))));
fn.If(fn.Comparison(greaterThan, fn.Load(lastLevel), fn.Load(level)), [lastLevel, level](IRFunctionEmitter& fn) {
fn.Store(lastLevel, fn.Load(level));
});
});
}
{
//if ((level > this->_thresholdUp * this->_lastLevel) && (level > this->_levelThreshold))
//{
// this->_signal = 1;
//}
function.If(function.LogicalAnd(
function.Comparison(greaterThan, function.Load(level), function.Operator(multiply, thresholdUpLiteral, function.Load(lastLevel))),
function.Comparison(greaterThan, function.Load(level), levelThresholdLiteral)),
[signal](IRFunctionEmitter& fn) {
fn.Store(signal, fn.Literal(1));
});
}
{
//if (level < this->_thresholdDown * this->_lastLevel)
//{
// this->_signal = 0;
//}
function.If(function.Comparison(lessThan, function.Load(level), function.Operator(multiply, thresholdDownLiteral, function.Load(lastLevel))), [signal](IRFunctionEmitter& fn) {
fn.Store(signal, fn.Literal(0));
});
}
//this->_lastTime = time;
function.Store(lastTime, function.Load(time));
// return this->_signal;
// Set the output
function.Store(pOutput, function.Load(signal));
// Add the internal reset function
std::string resetFunctionName = compiler.GetGlobalName(*this, "VADNodeReset");
emitters::IRFunctionEmitter& resetFunction = module.BeginResetFunction(resetFunctionName);
resetFunction.Store(lastTime, function.Literal(static_cast<ValueType>(0.0)));
resetFunction.Store(lastLevel, function.Literal(static_cast<ValueType>(0.0)));
resetFunction.Store(signal, function.Literal(0));
//resetFunction.Print("### GRU Node was reset\n"); // this is a handy way to debug whether the VAD node is working or not.
module.EndResetFunction();
}
template <typename ValueType>
void VoiceActivityDetectorNode<ValueType>::WriteToArchive(utilities::Archiver& archiver) const
{
CompilableNode::WriteToArchive(archiver);
archiver[defaultInputPortName] << _input;
archiver["vad"] << _vad;
}
template <typename ValueType>
void VoiceActivityDetectorNode<ValueType>::ReadFromArchive(utilities::Unarchiver& archiver)
{
CompilableNode::ReadFromArchive(archiver);
archiver[defaultInputPortName] >> _input;
archiver["vad"] >> _vad;
}
// Explicit specializations
template class VoiceActivityDetectorNode<float>;
template class VoiceActivityDetectorNode<double>;
} // namespace nodes
} // namespace ell
|
//------------------------------------------------------------------------------
/*
Portions of this file are from Vpallab: https://github.com/vpallabs
Copyright (c) 2013 - 2014 - Vpallab.com.
Please visit http://www.vpallab.com/
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012-2014 Ripple Labs Inc.
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.
*/
//==============================================================================
namespace ripple {
// Populate the UNL from a local validators.txt file.
Json::Value doUnlLoad (RPC::Context& context)
{
auto lock = getApp().masterLock();
if (getConfig ().VALIDATORS_FILE.empty ()
|| !getApp().getUNL ().nodeLoad (getConfig ().VALIDATORS_FILE))
{
return rpcError (rpcLOAD_FAILED);
}
return "loading";
}
} // ripple
|
// Copyright (c) 2011-2013 The HodlCash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include "uint256.h"
#include "arith_uint256.h"
#include <string>
#include "version.h"
BOOST_AUTO_TEST_SUITE(arith_uint256_tests)
///BOOST_FIXTURE_TEST_SUITE(arith_uint256_tests, BasicTestingSetup)
/// Convert vector to arith_uint256, via uint256 blob
inline arith_uint256 arith_uint256V(const std::vector<unsigned char>& vch)
{
return UintToArith256(uint256(vch));
}
const unsigned char R1Array[] =
"\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2"
"\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d";
const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c";
const double R1Ldouble = 0.4887374590559308955; // R1L equals roughly R1Ldouble * 2^256
const arith_uint256 R1L = arith_uint256V(std::vector<unsigned char>(R1Array,R1Array+32));
const uint64_t R1LLow64 = 0x121156cfdb4a529cULL;
const unsigned char R2Array[] =
"\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf"
"\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7";
const arith_uint256 R2L = arith_uint256V(std::vector<unsigned char>(R2Array,R2Array+32));
const char R1LplusR2L[] = "549FB09FEA236A1EA3E31D4D58F1B1369288D204211CA751527CFC175767850C";
const unsigned char ZeroArray[] =
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const arith_uint256 ZeroL = arith_uint256V(std::vector<unsigned char>(ZeroArray,ZeroArray+32));
const unsigned char OneArray[] =
"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const arith_uint256 OneL = arith_uint256V(std::vector<unsigned char>(OneArray,OneArray+32));
const unsigned char MaxArray[] =
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";
const arith_uint256 MaxL = arith_uint256V(std::vector<unsigned char>(MaxArray,MaxArray+32));
const arith_uint256 HalfL = (OneL << 255);
std::string ArrayToString(const unsigned char A[], unsigned int width)
{
std::stringstream Stream;
Stream << std::hex;
for (unsigned int i = 0; i < width; ++i)
{
Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1];
}
return Stream.str();
}
BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality
{
BOOST_CHECK(1 == 0+1);
// constructor arith_uint256(vector<char>):
BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32));
BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32));
BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32));
BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32));
BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32));
BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32));
// == and !=
BOOST_CHECK(R1L != R2L);
BOOST_CHECK(ZeroL != OneL);
BOOST_CHECK(OneL != ZeroL);
BOOST_CHECK(MaxL != ZeroL);
BOOST_CHECK(~MaxL == ZeroL);
BOOST_CHECK( ((R1L ^ R2L) ^ R1L) == R2L);
uint64_t Tmp64 = 0xc4dab720d9c7acaaULL;
for (unsigned int i = 0; i < 256; ++i)
{
BOOST_CHECK(ZeroL != (OneL << i));
BOOST_CHECK((OneL << i) != ZeroL);
BOOST_CHECK(R1L != (R1L ^ (OneL << i)));
BOOST_CHECK(((arith_uint256(Tmp64) ^ (OneL << i) ) != Tmp64 ));
}
BOOST_CHECK(ZeroL == (OneL << 256));
// String Constructor and Copy Constructor
BOOST_CHECK(arith_uint256("0x"+R1L.ToString()) == R1L);
BOOST_CHECK(arith_uint256("0x"+R2L.ToString()) == R2L);
BOOST_CHECK(arith_uint256("0x"+ZeroL.ToString()) == ZeroL);
BOOST_CHECK(arith_uint256("0x"+OneL.ToString()) == OneL);
BOOST_CHECK(arith_uint256("0x"+MaxL.ToString()) == MaxL);
BOOST_CHECK(arith_uint256(R1L.ToString()) == R1L);
BOOST_CHECK(arith_uint256(" 0x"+R1L.ToString()+" ") == R1L);
BOOST_CHECK(arith_uint256("") == ZeroL);
BOOST_CHECK(R1L == arith_uint256(R1ArrayHex));
BOOST_CHECK(arith_uint256(R1L) == R1L);
BOOST_CHECK((arith_uint256(R1L^R2L)^R2L) == R1L);
BOOST_CHECK(arith_uint256(ZeroL) == ZeroL);
BOOST_CHECK(arith_uint256(OneL) == OneL);
// uint64_t constructor
BOOST_CHECK( (R1L & arith_uint256("0xffffffffffffffff")) == arith_uint256(R1LLow64));
BOOST_CHECK(ZeroL == arith_uint256(0));
BOOST_CHECK(OneL == arith_uint256(1));
BOOST_CHECK(arith_uint256("0xffffffffffffffff") == arith_uint256(0xffffffffffffffffULL));
// Assignment (from base_uint)
arith_uint256 tmpL = ~ZeroL; BOOST_CHECK(tmpL == ~ZeroL);
tmpL = ~OneL; BOOST_CHECK(tmpL == ~OneL);
tmpL = ~R1L; BOOST_CHECK(tmpL == ~R1L);
tmpL = ~R2L; BOOST_CHECK(tmpL == ~R2L);
tmpL = ~MaxL; BOOST_CHECK(tmpL == ~MaxL);
}
void shiftArrayRight(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift)
{
for (unsigned int T=0; T < arrayLength; ++T)
{
unsigned int F = (T+bitsToShift/8);
if (F < arrayLength)
to[T] = from[F] >> (bitsToShift%8);
else
to[T] = 0;
if (F + 1 < arrayLength)
to[T] |= from[(F+1)] << (8-bitsToShift%8);
}
}
void shiftArrayLeft(unsigned char* to, const unsigned char* from, unsigned int arrayLength, unsigned int bitsToShift)
{
for (unsigned int T=0; T < arrayLength; ++T)
{
if (T >= bitsToShift/8)
{
unsigned int F = T-bitsToShift/8;
to[T] = from[F] << (bitsToShift%8);
if (T >= bitsToShift/8+1)
to[T] |= from[F-1] >> (8-bitsToShift%8);
}
else {
to[T] = 0;
}
}
}
BOOST_AUTO_TEST_CASE( shifts ) { // "<<" ">>" "<<=" ">>="
unsigned char TmpArray[32];
arith_uint256 TmpL;
for (unsigned int i = 0; i < 256; ++i)
{
shiftArrayLeft(TmpArray, OneArray, 32, i);
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (OneL << i));
TmpL = OneL; TmpL <<= i;
BOOST_CHECK(TmpL == (OneL << i));
BOOST_CHECK((HalfL >> (255-i)) == (OneL << i));
TmpL = HalfL; TmpL >>= (255-i);
BOOST_CHECK(TmpL == (OneL << i));
shiftArrayLeft(TmpArray, R1Array, 32, i);
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (R1L << i));
TmpL = R1L; TmpL <<= i;
BOOST_CHECK(TmpL == (R1L << i));
shiftArrayRight(TmpArray, R1Array, 32, i);
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (R1L >> i));
TmpL = R1L; TmpL >>= i;
BOOST_CHECK(TmpL == (R1L >> i));
shiftArrayLeft(TmpArray, MaxArray, 32, i);
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (MaxL << i));
TmpL = MaxL; TmpL <<= i;
BOOST_CHECK(TmpL == (MaxL << i));
shiftArrayRight(TmpArray, MaxArray, 32, i);
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (MaxL >> i));
TmpL = MaxL; TmpL >>= i;
BOOST_CHECK(TmpL == (MaxL >> i));
}
arith_uint256 c1L = arith_uint256(0x0123456789abcdefULL);
arith_uint256 c2L = c1L << 128;
for (unsigned int i = 0; i < 128; ++i) {
BOOST_CHECK((c1L << i) == (c2L >> (128-i)));
}
for (unsigned int i = 128; i < 256; ++i) {
BOOST_CHECK((c1L << i) == (c2L << (i-128)));
}
}
BOOST_AUTO_TEST_CASE( unaryOperators ) // ! ~ -
{
BOOST_CHECK(!ZeroL);
BOOST_CHECK(!(!OneL));
for (unsigned int i = 0; i < 256; ++i)
BOOST_CHECK(!(!(OneL<<i)));
BOOST_CHECK(!(!R1L));
BOOST_CHECK(!(!MaxL));
BOOST_CHECK(~ZeroL == MaxL);
unsigned char TmpArray[32];
for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = ~R1Array[i]; }
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (~R1L));
BOOST_CHECK(-ZeroL == ZeroL);
BOOST_CHECK(-R1L == (~R1L)+1);
for (unsigned int i = 0; i < 256; ++i)
BOOST_CHECK(-(OneL<<i) == (MaxL << i));
}
// Check if doing _A_ _OP_ _B_ results in the same as applying _OP_ onto each
// element of Aarray and Barray, and then converting the result into a arith_uint256.
#define CHECKBITWISEOPERATOR(_A_,_B_,_OP_) \
for (unsigned int i = 0; i < 32; ++i) { TmpArray[i] = _A_##Array[i] _OP_ _B_##Array[i]; } \
BOOST_CHECK(arith_uint256V(std::vector<unsigned char>(TmpArray,TmpArray+32)) == (_A_##L _OP_ _B_##L));
#define CHECKASSIGNMENTOPERATOR(_A_,_B_,_OP_) \
TmpL = _A_##L; TmpL _OP_##= _B_##L; BOOST_CHECK(TmpL == (_A_##L _OP_ _B_##L));
BOOST_AUTO_TEST_CASE( bitwiseOperators )
{
unsigned char TmpArray[32];
CHECKBITWISEOPERATOR(R1,R2,|)
CHECKBITWISEOPERATOR(R1,R2,^)
CHECKBITWISEOPERATOR(R1,R2,&)
CHECKBITWISEOPERATOR(R1,Zero,|)
CHECKBITWISEOPERATOR(R1,Zero,^)
CHECKBITWISEOPERATOR(R1,Zero,&)
CHECKBITWISEOPERATOR(R1,Max,|)
CHECKBITWISEOPERATOR(R1,Max,^)
CHECKBITWISEOPERATOR(R1,Max,&)
CHECKBITWISEOPERATOR(Zero,R1,|)
CHECKBITWISEOPERATOR(Zero,R1,^)
CHECKBITWISEOPERATOR(Zero,R1,&)
CHECKBITWISEOPERATOR(Max,R1,|)
CHECKBITWISEOPERATOR(Max,R1,^)
CHECKBITWISEOPERATOR(Max,R1,&)
arith_uint256 TmpL;
CHECKASSIGNMENTOPERATOR(R1,R2,|)
CHECKASSIGNMENTOPERATOR(R1,R2,^)
CHECKASSIGNMENTOPERATOR(R1,R2,&)
CHECKASSIGNMENTOPERATOR(R1,Zero,|)
CHECKASSIGNMENTOPERATOR(R1,Zero,^)
CHECKASSIGNMENTOPERATOR(R1,Zero,&)
CHECKASSIGNMENTOPERATOR(R1,Max,|)
CHECKASSIGNMENTOPERATOR(R1,Max,^)
CHECKASSIGNMENTOPERATOR(R1,Max,&)
CHECKASSIGNMENTOPERATOR(Zero,R1,|)
CHECKASSIGNMENTOPERATOR(Zero,R1,^)
CHECKASSIGNMENTOPERATOR(Zero,R1,&)
CHECKASSIGNMENTOPERATOR(Max,R1,|)
CHECKASSIGNMENTOPERATOR(Max,R1,^)
CHECKASSIGNMENTOPERATOR(Max,R1,&)
uint64_t Tmp64 = 0xe1db685c9a0b47a2ULL;
TmpL = R1L; TmpL |= Tmp64; BOOST_CHECK(TmpL == (R1L | arith_uint256(Tmp64)));
TmpL = R1L; TmpL |= 0; BOOST_CHECK(TmpL == R1L);
TmpL ^= 0; BOOST_CHECK(TmpL == R1L);
TmpL ^= Tmp64; BOOST_CHECK(TmpL == (R1L ^ arith_uint256(Tmp64)));
}
BOOST_AUTO_TEST_CASE( comparison ) // <= >= < >
{
arith_uint256 TmpL;
for (unsigned int i = 0; i < 256; ++i) {
TmpL= OneL<< i;
BOOST_CHECK( TmpL >= ZeroL && TmpL > ZeroL && ZeroL < TmpL && ZeroL <= TmpL);
BOOST_CHECK( TmpL >= 0 && TmpL > 0 && 0 < TmpL && 0 <= TmpL);
TmpL |= R1L;
BOOST_CHECK( TmpL >= R1L ); BOOST_CHECK( (TmpL == R1L) != (TmpL > R1L)); BOOST_CHECK( (TmpL == R1L) || !( TmpL <= R1L));
BOOST_CHECK( R1L <= TmpL ); BOOST_CHECK( (R1L == TmpL) != (R1L < TmpL)); BOOST_CHECK( (TmpL == R1L) || !( R1L >= TmpL));
BOOST_CHECK(! (TmpL < R1L)); BOOST_CHECK(! (R1L > TmpL));
}
}
BOOST_AUTO_TEST_CASE( plusMinus )
{
arith_uint256 TmpL = 0;
BOOST_CHECK(R1L+R2L == arith_uint256(R1LplusR2L));
TmpL += R1L;
BOOST_CHECK(TmpL == R1L);
TmpL += R2L;
BOOST_CHECK(TmpL == R1L + R2L);
BOOST_CHECK(OneL+MaxL == ZeroL);
BOOST_CHECK(MaxL+OneL == ZeroL);
for (unsigned int i = 1; i < 256; ++i) {
BOOST_CHECK( (MaxL >> i) + OneL == (HalfL >> (i-1)) );
BOOST_CHECK( OneL + (MaxL >> i) == (HalfL >> (i-1)) );
TmpL = (MaxL>>i); TmpL += OneL;
BOOST_CHECK( TmpL == (HalfL >> (i-1)) );
TmpL = (MaxL>>i); TmpL += 1;
BOOST_CHECK( TmpL == (HalfL >> (i-1)) );
TmpL = (MaxL>>i);
BOOST_CHECK( TmpL++ == (MaxL>>i) );
BOOST_CHECK( TmpL == (HalfL >> (i-1)));
}
BOOST_CHECK(arith_uint256(0xbedc77e27940a7ULL) + 0xee8d836fce66fbULL == arith_uint256(0xbedc77e27940a7ULL + 0xee8d836fce66fbULL));
TmpL = arith_uint256(0xbedc77e27940a7ULL); TmpL += 0xee8d836fce66fbULL;
BOOST_CHECK(TmpL == arith_uint256(0xbedc77e27940a7ULL+0xee8d836fce66fbULL));
TmpL -= 0xee8d836fce66fbULL; BOOST_CHECK(TmpL == 0xbedc77e27940a7ULL);
TmpL = R1L;
BOOST_CHECK(++TmpL == R1L+1);
BOOST_CHECK(R1L -(-R2L) == R1L+R2L);
BOOST_CHECK(R1L -(-OneL) == R1L+OneL);
BOOST_CHECK(R1L - OneL == R1L+(-OneL));
for (unsigned int i = 1; i < 256; ++i) {
BOOST_CHECK((MaxL>>i) - (-OneL) == (HalfL >> (i-1)));
BOOST_CHECK((HalfL >> (i-1)) - OneL == (MaxL>>i));
TmpL = (HalfL >> (i-1));
BOOST_CHECK(TmpL-- == (HalfL >> (i-1)));
BOOST_CHECK(TmpL == (MaxL >> i));
TmpL = (HalfL >> (i-1));
BOOST_CHECK(--TmpL == (MaxL >> i));
}
TmpL = R1L;
BOOST_CHECK(--TmpL == R1L-1);
}
BOOST_AUTO_TEST_CASE( multiply )
{
BOOST_CHECK((R1L * R1L).ToString() == "62a38c0486f01e45879d7910a7761bf30d5237e9873f9bff3642a732c4d84f10");
BOOST_CHECK((R1L * R2L).ToString() == "de37805e9986996cfba76ff6ba51c008df851987d9dd323f0e5de07760529c40");
BOOST_CHECK((R1L * ZeroL) == ZeroL);
BOOST_CHECK((R1L * OneL) == R1L);
BOOST_CHECK((R1L * MaxL) == -R1L);
BOOST_CHECK((R2L * R1L) == (R1L * R2L));
BOOST_CHECK((R2L * R2L).ToString() == "ac8c010096767d3cae5005dec28bb2b45a1d85ab7996ccd3e102a650f74ff100");
BOOST_CHECK((R2L * ZeroL) == ZeroL);
BOOST_CHECK((R2L * OneL) == R2L);
BOOST_CHECK((R2L * MaxL) == -R2L);
BOOST_CHECK(MaxL * MaxL == OneL);
BOOST_CHECK((R1L * 0) == 0);
BOOST_CHECK((R1L * 1) == R1L);
BOOST_CHECK((R1L * 3).ToString() == "7759b1c0ed14047f961ad09b20ff83687876a0181a367b813634046f91def7d4");
BOOST_CHECK((R2L * 0x87654321UL).ToString() == "23f7816e30c4ae2017257b7a0fa64d60402f5234d46e746b61c960d09a26d070");
}
BOOST_AUTO_TEST_CASE( divide )
{
arith_uint256 D1L("AD7133AC1977FA2B7");
arith_uint256 D2L("ECD751716");
BOOST_CHECK((R1L / D1L).ToString() == "00000000000000000b8ac01106981635d9ed112290f8895545a7654dde28fb3a");
BOOST_CHECK((R1L / D2L).ToString() == "000000000873ce8efec5b67150bad3aa8c5fcb70e947586153bf2cec7c37c57a");
BOOST_CHECK(R1L / OneL == R1L);
BOOST_CHECK(R1L / MaxL == ZeroL);
BOOST_CHECK(MaxL / R1L == 2);
BOOST_CHECK_THROW(R1L / ZeroL, uint_error);
BOOST_CHECK((R2L / D1L).ToString() == "000000000000000013e1665895a1cc981de6d93670105a6b3ec3b73141b3a3c5");
BOOST_CHECK((R2L / D2L).ToString() == "000000000e8f0abe753bb0afe2e9437ee85d280be60882cf0bd1aaf7fa3cc2c4");
BOOST_CHECK(R2L / OneL == R2L);
BOOST_CHECK(R2L / MaxL == ZeroL);
BOOST_CHECK(MaxL / R2L == 1);
BOOST_CHECK_THROW(R2L / ZeroL, uint_error);
}
bool almostEqual(double d1, double d2)
{
return fabs(d1-d2) <= 4*fabs(d1)*std::numeric_limits<double>::epsilon();
}
BOOST_AUTO_TEST_CASE( methods ) // GetHex SetHex size() GetLow64 GetSerializeSize, Serialize, Unserialize
{
BOOST_CHECK(R1L.GetHex() == R1L.ToString());
BOOST_CHECK(R2L.GetHex() == R2L.ToString());
BOOST_CHECK(OneL.GetHex() == OneL.ToString());
BOOST_CHECK(MaxL.GetHex() == MaxL.ToString());
arith_uint256 TmpL(R1L);
BOOST_CHECK(TmpL == R1L);
TmpL.SetHex(R2L.ToString()); BOOST_CHECK(TmpL == R2L);
TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == 0);
TmpL.SetHex(HalfL.ToString()); BOOST_CHECK(TmpL == HalfL);
TmpL.SetHex(R1L.ToString());
BOOST_CHECK(R1L.size() == 32);
BOOST_CHECK(R2L.size() == 32);
BOOST_CHECK(ZeroL.size() == 32);
BOOST_CHECK(MaxL.size() == 32);
BOOST_CHECK(R1L.GetLow64() == R1LLow64);
BOOST_CHECK(HalfL.GetLow64() ==0x0000000000000000ULL);
BOOST_CHECK(OneL.GetLow64() ==0x0000000000000001ULL);
for (unsigned int i = 0; i < 255; ++i)
{
BOOST_CHECK((OneL << i).getdouble() == ldexp(1.0,i));
}
BOOST_CHECK(ZeroL.getdouble() == 0.0);
for (int i = 256; i > 53; --i)
BOOST_CHECK(almostEqual((R1L>>(256-i)).getdouble(), ldexp(R1Ldouble,i)));
uint64_t R1L64part = (R1L>>192).GetLow64();
for (int i = 53; i > 0; --i) // doubles can store all integers in {0,...,2^54-1} exactly
{
BOOST_CHECK((R1L>>(256-i)).getdouble() == (double)(R1L64part >> (64-i)));
}
}
BOOST_AUTO_TEST_CASE(bignum_SetCompact)
{
arith_uint256 num;
bool fNegative;
bool fOverflow;
num.SetCompact(0, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x00123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x01003456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x02000056, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x03000000, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x04000000, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x00923456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x01803456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x02800056, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x03800000, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x04800000, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x01123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000000012");
BOOST_CHECK_EQUAL(num.GetCompact(), 0x01120000U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
// Make sure that we don't generate compacts with the 0x00800000 bit set
num = 0x80;
BOOST_CHECK_EQUAL(num.GetCompact(), 0x02008000U);
num.SetCompact(0x01fedcba, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "000000000000000000000000000000000000000000000000000000000000007e");
BOOST_CHECK_EQUAL(num.GetCompact(true), 0x01fe0000U);
BOOST_CHECK_EQUAL(fNegative, true);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x02123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000001234");
BOOST_CHECK_EQUAL(num.GetCompact(), 0x02123400U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x03123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000000123456");
BOOST_CHECK_EQUAL(num.GetCompact(), 0x03123456U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x04123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000012345600");
BOOST_CHECK_EQUAL(num.GetCompact(), 0x04123456U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x04923456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000012345600");
BOOST_CHECK_EQUAL(num.GetCompact(true), 0x04923456U);
BOOST_CHECK_EQUAL(fNegative, true);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x05009234, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "0000000000000000000000000000000000000000000000000000000092340000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0x05009234U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0x20123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(num.GetHex(), "1234560000000000000000000000000000000000000000000000000000000000");
BOOST_CHECK_EQUAL(num.GetCompact(), 0x20123456U);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, false);
num.SetCompact(0xff123456, &fNegative, &fOverflow);
BOOST_CHECK_EQUAL(fNegative, false);
BOOST_CHECK_EQUAL(fOverflow, true);
}
BOOST_AUTO_TEST_CASE( getmaxcoverage ) // some more tests just to get 100% coverage
{
// ~R1L give a base_uint<256>
BOOST_CHECK((~~R1L >> 10) == (R1L >> 10));
BOOST_CHECK((~~R1L << 10) == (R1L << 10));
BOOST_CHECK(!(~~R1L < R1L));
BOOST_CHECK(~~R1L <= R1L);
BOOST_CHECK(!(~~R1L > R1L));
BOOST_CHECK(~~R1L >= R1L);
BOOST_CHECK(!(R1L < ~~R1L));
BOOST_CHECK(R1L <= ~~R1L);
BOOST_CHECK(!(R1L > ~~R1L));
BOOST_CHECK(R1L >= ~~R1L);
BOOST_CHECK(~~R1L + R2L == R1L + ~~R2L);
BOOST_CHECK(~~R1L - R2L == R1L - ~~R2L);
BOOST_CHECK(~R1L != R1L); BOOST_CHECK(R1L != ~R1L);
unsigned char TmpArray[32];
CHECKBITWISEOPERATOR(~R1,R2,|)
CHECKBITWISEOPERATOR(~R1,R2,^)
CHECKBITWISEOPERATOR(~R1,R2,&)
CHECKBITWISEOPERATOR(R1,~R2,|)
CHECKBITWISEOPERATOR(R1,~R2,^)
CHECKBITWISEOPERATOR(R1,~R2,&)
}
BOOST_AUTO_TEST_SUITE_END()
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ==++==
//
//
// ==--==
#include "sos.h"
#include "disasm.h"
#include <dbghelp.h>
#include "corhdr.h"
#include "cor.h"
#include "dacprivate.h"
#include "sospriv.h"
#include "corerror.h"
#include "safemath.h"
#include <psapi.h>
#include <cordebug.h>
#include <xcordebug.h>
#include <metahost.h>
#include <mscoree.h>
#include <tchar.h>
#include "gcinfo.h"
#ifndef STRESS_LOG
#define STRESS_LOG
#endif // STRESS_LOG
#define STRESS_LOG_READONLY
#include "stresslog.h"
#ifdef FEATURE_PAL
#include <sys/stat.h>
#include <dlfcn.h>
#endif // !FEATURE_PAL
#include "coreclrhost.h"
#include <set>
#include <string>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
const char * const CorElementTypeName[ELEMENT_TYPE_MAX]=
{
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) c,
#include "cortypeinfo.h"
#undef TYPEINFO
};
const char * const CorElementTypeNamespace[ELEMENT_TYPE_MAX]=
{
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) ns,
#include "cortypeinfo.h"
#undef TYPEINFO
};
IXCLRDataProcess *g_clrData = NULL;
ISOSDacInterface *g_sos = NULL;
#ifndef IfFailRet
#define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { return (Status); } } while (0)
#endif
// Max number of reverted rejit versions that !dumpmd and !ip2md will print
const UINT kcMaxRevertedRejitData = 10;
const UINT kcMaxTieredVersions = 10;
#ifndef FEATURE_PAL
// ensure we always allocate on the process heap
void* __cdecl operator new(size_t size) throw()
{ return HeapAlloc(GetProcessHeap(), 0, size); }
void __cdecl operator delete(void* pObj) throw()
{ HeapFree(GetProcessHeap(), 0, pObj); }
void* __cdecl operator new[](size_t size) throw()
{ return HeapAlloc(GetProcessHeap(), 0, size); }
void __cdecl operator delete[](void* pObj) throw()
{ HeapFree(GetProcessHeap(), 0, pObj); }
/**********************************************************************\
* Routine Description: *
* *
* This function is called to get the memory address given a symbol *
* name. It handles difference in symbol name between ntsd and *
* windbg. *
* *
\**********************************************************************/
DWORD_PTR GetValueFromExpression(___in __in_z const char *const instr)
{
_ASSERTE(g_pRuntime != nullptr);
LoadRuntimeSymbols();
std::string symbol;
symbol.append(GetRuntimeModuleName());
symbol.append("!");
symbol.append(instr);
ULONG64 dwAddr;
const char* str = symbol.c_str();
char name[256];
dwAddr = 0;
HRESULT hr = g_ExtSymbols->GetOffsetByName (str, &dwAddr);
if (SUCCEEDED(hr))
return (DWORD_PTR)dwAddr;
else if (hr == S_FALSE && dwAddr)
return (DWORD_PTR)dwAddr;
strcpy_s (name, _countof(name), str);
char *ptr;
if ((ptr = strstr (name, "__")) != NULL)
{
ptr[0] = ':';
ptr[1] = ':';
ptr += 2;
while ((ptr = strstr(ptr, "__")) != NULL)
{
ptr[0] = ':';
ptr[1] = ':';
ptr += 2;
}
dwAddr = 0;
hr = g_ExtSymbols->GetOffsetByName (name, &dwAddr);
if (SUCCEEDED(hr))
return (DWORD_PTR)dwAddr;
else if (hr == S_FALSE && dwAddr)
return (DWORD_PTR)dwAddr;
}
else if ((ptr = strstr (name, "::")) != NULL)
{
ptr[0] = '_';
ptr[1] = '_';
ptr += 2;
while ((ptr = strstr(ptr, "::")) != NULL)
{
ptr[0] = '_';
ptr[1] = '_';
ptr += 2;
}
dwAddr = 0;
hr = g_ExtSymbols->GetOffsetByName (name, &dwAddr);
if (SUCCEEDED(hr))
return (DWORD_PTR)dwAddr;
else if (hr == S_FALSE && dwAddr)
return (DWORD_PTR)dwAddr;
}
return 0;
}
#endif // FEATURE_PAL
void ReportOOM()
{
ExtOut("SOS Error: Out of memory\n");
}
BOOL IsDumpFile()
{
static int g_fDumpFile = -1;
if (g_fDumpFile == -1) {
ULONG Class;
ULONG Qualifier;
g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
if (Qualifier >= DEBUG_DUMP_SMALL)
g_fDumpFile = 1;
else
g_fDumpFile = 0;
}
return g_fDumpFile != 0;
}
BOOL g_InMinidumpSafeMode = FALSE;
BOOL IsMiniDumpFileNODAC ()
{
#ifndef FEATURE_PAL
ULONG Class;
ULONG Qualifier;
g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
if (Qualifier == DEBUG_DUMP_SMALL)
{
g_ExtControl->GetDumpFormatFlags(&Qualifier);
if ((Qualifier & DEBUG_FORMAT_USER_SMALL_FULL_MEMORY) == 0)
{
return TRUE;
}
}
#endif // FEATURE_PAL
return FALSE;
}
// We use this predicate to mean the smallest, most restrictive kind of
// minidump file. There is no heap dump, only that set of information
// gathered to make !clrstack, !threads, !help, !eeversion and !pe work.
BOOL IsMiniDumpFile ()
{
#ifndef FEATURE_PAL
// It is okay for this to be static, because although the debugger may debug multiple
// managed processes at once, I don't believe multiple dumpfiles of different
// types is a scenario to worry about.
if (IsMiniDumpFileNODAC())
{
// Beyond recognizing the dump type above, all we can rely on for this
// is a flag set by the user indicating they want a safe mode minidump
// experience. This is primarily for testing.
return g_InMinidumpSafeMode;
}
#endif // FEATURE_PAL
return FALSE;
}
ULONG DebuggeeType()
{
static ULONG Class = DEBUG_CLASS_UNINITIALIZED;
if (Class == DEBUG_CLASS_UNINITIALIZED) {
ULONG Qualifier;
g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
}
return Class;
}
const WCHAR GetTargetDirectorySeparatorW()
{
if (IsWindowsTarget()) {
return W('\\');
}
else {
return W('/');
}
}
#ifndef FEATURE_PAL
// Check if a file exist
BOOL FileExist (const char *filename)
{
WIN32_FIND_DATAA FindFileData;
HANDLE handle = FindFirstFileA(filename, &FindFileData);
if (handle != INVALID_HANDLE_VALUE) {
FindClose (handle);
return TRUE;
}
else
return FALSE;
}
BOOL FileExist (const WCHAR *filename)
{
WIN32_FIND_DATAW FindFileData;
HANDLE handle = FindFirstFileW (filename, &FindFileData);
if (handle != INVALID_HANDLE_VALUE) {
FindClose (handle);
return TRUE;
}
else
return FALSE;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find out if a dll is bbt-ized *
* *
\**********************************************************************/
BOOL IsRetailBuild (size_t base)
{
IMAGE_DOS_HEADER DosHeader;
if (g_ExtData->ReadVirtual(TO_CDADDR(base), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
return FALSE;
IMAGE_NT_HEADERS32 Header32;
if (g_ExtData->ReadVirtual(TO_CDADDR(base + DosHeader.e_lfanew), &Header32, sizeof(Header32), NULL) != S_OK)
return FALSE;
// If there is no COMHeader, this can not be managed code.
if (Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress == 0)
return FALSE;
size_t debugDirAddr = base + Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
size_t nSize = Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
IMAGE_DEBUG_DIRECTORY debugDir;
size_t nbytes = 0;
while (nbytes < nSize) {
if (g_ExtData->ReadVirtual(TO_CDADDR(debugDirAddr+nbytes), &debugDir, sizeof(debugDir), NULL) != S_OK)
return FALSE;
if (debugDir.Type == 0xA) {
return TRUE;
}
nbytes += sizeof(debugDir);
}
return FALSE;
}
#endif // !FEATURE_PAL
/**********************************************************************\
* Routine Description: *
* *
* This function is called to read memory from the debugee's *
* address space. If the initial read fails, it attempts to read *
* only up to the edge of the page containing "offset". *
* *
\**********************************************************************/
BOOL SafeReadMemory (TADDR offset, PVOID lpBuffer, ULONG cb, PULONG lpcbBytesRead)
{
BOOL bRet = SUCCEEDED(g_ExtData->ReadVirtual(TO_CDADDR(offset), lpBuffer, cb, lpcbBytesRead));
if (!bRet)
{
cb = _min(cb, (ULONG)(NextOSPageAddress(offset) - offset));
bRet = SUCCEEDED(g_ExtData->ReadVirtual(TO_CDADDR(offset), lpBuffer, cb, lpcbBytesRead));
}
return bRet;
}
ULONG OSPageSize ()
{
static ULONG pageSize = 0;
if (pageSize == 0)
g_ExtControl->GetPageSize(&pageSize);
return pageSize;
}
size_t NextOSPageAddress (size_t addr)
{
size_t pageSize = OSPageSize();
return (addr+pageSize)&(~(pageSize-1));
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to get the address of MethodDesc *
* given an ip address *
* *
\**********************************************************************/
void IP2MethodDesc (DWORD_PTR IP, DWORD_PTR &methodDesc, JITTypes &jitType,
DWORD_PTR &gcinfoAddr)
{
CLRDATA_ADDRESS EIP = TO_CDADDR(IP);
DacpCodeHeaderData codeHeaderData;
methodDesc = NULL;
gcinfoAddr = NULL;
if (codeHeaderData.Request(g_sos, EIP) != S_OK)
{
return;
}
methodDesc = (DWORD_PTR) codeHeaderData.MethodDescPtr;
jitType = (JITTypes) codeHeaderData.JITType;
gcinfoAddr = (DWORD_PTR) codeHeaderData.GCInfo;
}
BOOL IsValueField (DacpFieldDescData *pFD)
{
return (pFD->Type == ELEMENT_TYPE_VALUETYPE);
}
static DWORD_PTR ResolveByRefField(DacpFieldDescData* pFD, DWORD_PTR dwAddr, CLRDATA_ADDRESS* methodTable)
{
if (dwAddr == 0)
return 0;
ToRelease<IMetaDataImport> pImport = MDImportForModule(TO_TADDR(pFD->ModuleOfType));
PCCOR_SIGNATURE pSignatureBlob = NULL;
ULONG sigBlobLength = 0;
if(FAILED(pImport->GetFieldProps(pFD->mb, NULL, NULL, 0, NULL, NULL, &pSignatureBlob, &sigBlobLength, NULL, NULL, NULL)))
return 0;
SigParser sigParser(pSignatureBlob, sigBlobLength);
sigParser.SkipExactlyOne();
// Move past and assert the ByRef
CorElementType etype;
if (FAILED(sigParser.GetElemType(&etype)))
return 0;
_ASSERTE(etype == ELEMENT_TYPE_BYREF);
// Get the byref's type. If this is also a byref we give up.
if (FAILED(sigParser.GetElemType(&etype)) || etype == ELEMENT_TYPE_BYREF)
return 0;
// If the type was determined to be a valuetype, we need the methodtable
// to be able to properly display it.
if (etype == ELEMENT_TYPE_VALUETYPE)
{
mdToken token = mdTokenNil;
if (FAILED(sigParser.GetToken(&token)))
return 0;
CLRDATA_ADDRESS methodTableMaybe = 0;
if (FAILED(g_sos->GetMethodDescFromToken(pFD->ModuleOfType, token, &methodTableMaybe)))
return 0;
*methodTable = methodTableMaybe;
}
// The byref has been confirmed and we now have a concrete type to read.
// Now get the target of the byref.
DWORD_PTR tgt;
CLRDATA_ADDRESS address = TO_CDADDR(dwAddr);
if (FAILED(g_ExtData->ReadVirtual(dwAddr, &tgt, sizeof(DWORD_PTR), NULL)))
return 0;
return tgt;
}
void DisplayDataMember (DacpFieldDescData* pFD, DWORD_PTR dwAddr, BOOL fAlign=TRUE)
{
if (dwAddr > 0)
{
// we must have called this function for a "real" (non-zero size) data type
PREFIX_ASSUME(gElementTypeInfo[pFD->Type] != 0);
DWORD_PTR dwTmp = dwAddr;
bool bVTStatic = (pFD->bIsStatic && pFD->Type == ELEMENT_TYPE_VALUETYPE);
if (gElementTypeInfo[pFD->Type] != NO_SIZE || bVTStatic)
{
union Value
{
char ch;
short Short;
DWORD_PTR ptr;
int Int;
unsigned int UInt;
__int64 Int64;
unsigned __int64 UInt64;
float Float;
double Double;
} value;
ZeroMemory(&value, sizeof(value));
if (bVTStatic)
{
// static VTypes are boxed
moveBlock (value, dwTmp, gElementTypeInfo[ELEMENT_TYPE_CLASS]);
}
else
{
moveBlock (value, dwTmp, gElementTypeInfo[pFD->Type]);
}
switch (pFD->Type)
{
case ELEMENT_TYPE_I1:
// there's no ANSI conformant type specifier for
// signed char, so use the next best thing,
// signed short (sign extending)
if (fAlign)
ExtOut("%" POINTERSIZE "hd", (short)value.ch);
else
ExtOut("%d", value.ch);
break;
case ELEMENT_TYPE_I2:
if (fAlign)
ExtOut("%" POINTERSIZE "hd", value.Short);
else
ExtOut("%d", value.Short);
break;
case ELEMENT_TYPE_I4:
if (fAlign)
ExtOut("%" POINTERSIZE "d", value.Int);
else
ExtOut("%d", value.Int);
break;
case ELEMENT_TYPE_I8:
if (fAlign)
ExtOut("%" POINTERSIZE "I64d", value.Int64);
else
ExtOut("%I64d", value.Int64);
break;
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_BOOLEAN:
if (fAlign)
// there's no ANSI conformant type specifier for
// unsigned char, so use the next best thing,
// unsigned short, not extending the sign
ExtOut("%" POINTERSIZE "hu", (USHORT)value.Short);
else
ExtOut("%u", value.ch);
break;
case ELEMENT_TYPE_U2:
if (fAlign)
ExtOut("%" POINTERSIZE "hu", value.Short);
else
ExtOut("%u", value.Short);
break;
case ELEMENT_TYPE_U4:
if (fAlign)
ExtOut("%" POINTERSIZE "u", value.UInt);
else
ExtOut("%u", value.UInt);
break;
case ELEMENT_TYPE_U8:
if (fAlign)
ExtOut("%" POINTERSIZE "I64u", value.UInt64);
else
ExtOut("%I64u", value.UInt64);
break;
case ELEMENT_TYPE_I:
case ELEMENT_TYPE_U:
if (fAlign)
ExtOut("%" POINTERSIZE "p", SOS_PTR(value.ptr));
else
ExtOut("%p", SOS_PTR(value.ptr));
break;
case ELEMENT_TYPE_R4:
ExtOut("%f", value.Float);
break;
case ELEMENT_TYPE_R8:
ExtOut("%f", value.Double);
break;
case ELEMENT_TYPE_CHAR:
if (fAlign)
ExtOut("%" POINTERSIZE "hx", value.Short);
else
ExtOut("%x", value.Short);
break;
case ELEMENT_TYPE_VALUETYPE:
if (value.ptr)
DMLOut(DMLValueClass(pFD->MTOfType, dwTmp));
else
ExtOut("%p", SOS_PTR(0));
break;
case ELEMENT_TYPE_BYREF:
{
CLRDATA_ADDRESS methodTable = 0;
DWORD_PTR tgt = ResolveByRefField(pFD, value.ptr, &methodTable);
if (tgt)
{
if (methodTable)
DMLOut(DMLByRefValueClass(value.ptr, methodTable, tgt));
else
DMLOut(DMLByRefObject(value.ptr, tgt));
}
else
{
// This will display zero if that is what the value was or the
// supplied value if ResolveByRefField() failed.
ExtOut("%p", SOS_PTR(value.ptr));
}
}
break;
default:
if (value.ptr)
DMLOut(DMLObject(value.ptr));
else
ExtOut("%p", SOS_PTR(0));
break;
}
}
else
{
if (pFD->Type == ELEMENT_TYPE_VALUETYPE)
DMLOut(DMLValueClass(pFD->MTOfType, dwTmp));
else
ExtOut("%p", SOS_PTR(0));
}
}
else
{
ExtOut("%" POINTERSIZE "s", " ");
}
}
void GetStaticFieldPTR(DWORD_PTR* pOutPtr, DacpDomainLocalModuleData* pDLMD, DacpMethodTableData* pMTD, DacpFieldDescData* pFDD, BYTE* pFlags = 0)
{
DWORD_PTR dwTmp;
if (pFDD->Type == ELEMENT_TYPE_VALUETYPE
|| pFDD->Type == ELEMENT_TYPE_CLASS)
{
dwTmp = (DWORD_PTR) pDLMD->pGCStaticDataStart + pFDD->dwOffset;
}
else
{
dwTmp = (DWORD_PTR) pDLMD->pNonGCStaticDataStart + pFDD->dwOffset;
}
*pOutPtr = 0;
if (pMTD->bIsDynamic)
{
ExtOut("dynamic statics NYI");
return;
}
else
{
if (pFlags && pMTD->bIsShared)
{
BYTE flags;
DWORD_PTR pTargetFlags = (DWORD_PTR) pDLMD->pClassData + RidFromToken(pMTD->cl) - 1;
move_xp (flags, pTargetFlags);
*pFlags = flags;
}
*pOutPtr = dwTmp;
}
return;
}
void GetDLMFlags(DacpDomainLocalModuleData* pDLMD, DacpMethodTableData* pMTD, BYTE* pFlags)
{
if (pMTD->bIsDynamic)
{
ExtOut("dynamic statics NYI");
return;
}
else
{
if (pFlags)
{
BYTE flags;
DWORD_PTR pTargetFlags = (DWORD_PTR) pDLMD->pClassData + RidFromToken(pMTD->cl) - 1;
move_xp (flags, pTargetFlags);
*pFlags = flags;
}
}
return;
}
void GetThreadStaticFieldPTR(DWORD_PTR* pOutPtr, DacpThreadLocalModuleData* pTLMD, DacpMethodTableData* pMTD, DacpFieldDescData* pFDD, BYTE* pFlags = 0)
{
DWORD_PTR dwTmp;
if (pFDD->Type == ELEMENT_TYPE_VALUETYPE
|| pFDD->Type == ELEMENT_TYPE_CLASS)
{
dwTmp = (DWORD_PTR) pTLMD->pGCStaticDataStart + pFDD->dwOffset;
}
else
{
dwTmp = (DWORD_PTR) pTLMD->pNonGCStaticDataStart + pFDD->dwOffset;
}
*pOutPtr = 0;
if (pMTD->bIsDynamic)
{
ExtOut("dynamic thread statics NYI");
return;
}
else
{
if (pFlags)
{
BYTE flags;
DWORD_PTR pTargetFlags = (DWORD_PTR) pTLMD->pClassData + RidFromToken(pMTD->cl) - 1;
move_xp (flags, pTargetFlags);
*pFlags = flags;
}
*pOutPtr = dwTmp;
}
return;
}
void DisplaySharedStatic(ULONG64 dwModuleDomainID, DacpMethodTableData* pMT, DacpFieldDescData *pFD)
{
DacpAppDomainStoreData adsData;
if (adsData.Request(g_sos)!=S_OK)
{
ExtOut("Unable to get AppDomain information\n");
}
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adsData.DomainCount];
if (pArray==NULL)
{
ReportOOM();
return;
}
if (g_sos->GetAppDomainList(adsData.DomainCount,pArray, NULL)!=S_OK)
{
ExtOut("Unable to get array of AppDomains\n");
return;
}
#if defined(_TARGET_WIN64_)
ExtOut(" >> Domain:Value ");
#else
ExtOut(" >> Domain:Value ");
#endif
// Skip the SystemDomain and SharedDomain
for (int i = 0; i < adsData.DomainCount ; i ++)
{
DacpAppDomainData appdomainData;
if (appdomainData.Request(g_sos,pArray[i])!=S_OK)
{
ExtOut("Unable to get AppDomain %lx\n",pArray[i]);
return;
}
DacpDomainLocalModuleData vDomainLocalModule;
if (g_sos->GetDomainLocalModuleDataFromAppDomain(appdomainData.AppDomainPtr, (int)dwModuleDomainID, &vDomainLocalModule) != S_OK)
{
// On .NET Core, dwModuleDomainID is the address of the DomainLocalModule.
if (vDomainLocalModule.Request(g_sos, dwModuleDomainID) != S_OK)
{
DMLOut(" %s:NotInit ", DMLDomain(pArray[i]));
continue;
}
}
DWORD_PTR dwTmp;
BYTE Flags = 0;
GetStaticFieldPTR(&dwTmp, &vDomainLocalModule , pMT, pFD, &Flags);
if ((Flags&1) == 0) {
// We have not initialized this yet.
DMLOut(" %s:NotInit ", DMLDomain(pArray[i]));
continue;
}
else if (Flags & 2) {
// We have not initialized this yet.
DMLOut(" %s:FailInit", DMLDomain(pArray[i]));
continue;
}
DMLOut(" %s:", DMLDomain(appdomainData.AppDomainPtr));
DisplayDataMember(pFD, dwTmp, FALSE);
}
ExtOut(" <<\n");
}
void DisplayThreadStatic (DacpModuleData* pModule, DacpMethodTableData* pMT, DacpFieldDescData *pFD, BOOL fIsShared)
{
SIZE_T dwModuleIndex = (SIZE_T)pModule->dwModuleIndex;
SIZE_T dwModuleDomainID = (SIZE_T)pModule->dwModuleID;
DacpThreadStoreData ThreadStore;
ThreadStore.Request(g_sos);
ExtOut(" >> Thread:Value");
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread)
{
DacpThreadData vThread;
if (vThread.Request(g_sos, CurThread) != S_OK)
{
ExtOut(" error getting thread %p, aborting this field\n", SOS_PTR(CurThread));
return;
}
if (vThread.osThreadId != 0)
{
CLRDATA_ADDRESS appDomainAddr = vThread.domain;
// Get the DLM (we need this to check the ClassInit flags).
// It's annoying that we have to issue one request for
// domain-neutral modules and domain-specific modules.
DacpDomainLocalModuleData vDomainLocalModule;
if (fIsShared)
{
if (g_sos->GetDomainLocalModuleDataFromAppDomain(appDomainAddr, (int)dwModuleDomainID, &vDomainLocalModule) != S_OK)
{
// On .NET Core, dwModuleDomainID is the address of the DomainLocalModule.
if (vDomainLocalModule.Request(g_sos, dwModuleDomainID) != S_OK)
{
// Not initialized, go to next thread and continue looping
CurThread = vThread.nextThread;
continue;
}
}
}
else
{
if (g_sos->GetDomainLocalModuleDataFromModule(pMT->Module, &vDomainLocalModule) != S_OK)
{
// Not initialized, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
}
// Get the TLM
DacpThreadLocalModuleData vThreadLocalModule;
if (g_sos->GetThreadLocalModuleData(CurThread, (int)dwModuleIndex, &vThreadLocalModule) != S_OK)
{
// Not initialized, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
DWORD_PTR dwTmp;
BYTE Flags = 0;
GetThreadStaticFieldPTR(&dwTmp, &vThreadLocalModule, pMT, pFD, &Flags);
if ((Flags&4) == 0)
{
// Not allocated, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
Flags = 0;
GetDLMFlags(&vDomainLocalModule, pMT, &Flags);
if ((Flags&1) == 0)
{
// Not initialized, go to next thread
// and continue looping
CurThread = vThread.nextThread;
continue;
}
ExtOut(" %x:", vThread.osThreadId);
DisplayDataMember(pFD, dwTmp, FALSE);
}
// Go to next thread
CurThread = vThread.nextThread;
}
ExtOut(" <<\n");
}
const char * ElementTypeName(unsigned type)
{
switch (type) {
case ELEMENT_TYPE_PTR:
return "PTR";
break;
case ELEMENT_TYPE_BYREF:
return "BYREF";
break;
case ELEMENT_TYPE_VALUETYPE:
return "VALUETYPE";
break;
case ELEMENT_TYPE_CLASS:
return "CLASS";
break;
case ELEMENT_TYPE_VAR:
return "VAR";
break;
case ELEMENT_TYPE_ARRAY:
return "ARRAY";
break;
case ELEMENT_TYPE_FNPTR:
return "FNPTR";
break;
case ELEMENT_TYPE_SZARRAY:
return "SZARRAY";
break;
case ELEMENT_TYPE_MVAR:
return "MVAR";
break;
default:
if ((type >= _countof(CorElementTypeName)) || (CorElementTypeName[type] == NULL))
{
return "";
}
return CorElementTypeName[type];
break;
}
} // ElementTypeName
const char * ElementTypeNamespace(unsigned type)
{
if ((type >= _countof(CorElementTypeName)) || (CorElementTypeNamespace[type] == NULL))
{
return "";
}
return CorElementTypeNamespace[type];
}
void ComposeName_s(CorElementType Type, __out_ecount(capacity_buffer) LPSTR buffer, size_t capacity_buffer)
{
const char *p = ElementTypeNamespace(Type);
if ((p) && (*p != '\0'))
{
strcpy_s(buffer,capacity_buffer,p);
strcat_s(buffer,capacity_buffer,".");
strcat_s(buffer,capacity_buffer,ElementTypeName(Type));
}
else
{
strcpy_s(buffer,capacity_buffer,ElementTypeName(Type));
}
}
// NOTE: pszName is changed
// INPUT MAXCHARS RETURN
// HelloThere 5 ...re
// HelloThere 8 ...There
LPWSTR FormatTypeName (__out_ecount (maxChars) LPWSTR pszName, UINT maxChars)
{
UINT iStart = 0;
UINT iLen = (int) _wcslen(pszName);
if (iLen > maxChars)
{
iStart = iLen - maxChars;
UINT numDots = (maxChars < 3) ? maxChars : 3;
for (UINT i=0; i < numDots; i++)
pszName[iStart+i] = '.';
}
return pszName + iStart;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to dump all fields of a managed object. *
* dwStartAddr specifies the beginning memory address. *
* bFirst is used to avoid printing header every time. *
* *
\**********************************************************************/
void DisplayFields(CLRDATA_ADDRESS cdaMT, DacpMethodTableData *pMTD, DacpMethodTableFieldData *pMTFD, DWORD_PTR dwStartAddr, BOOL bFirst, BOOL bValueClass)
{
static DWORD numInstanceFields = 0;
if (bFirst)
{
ExtOutIndent();
ExtOut("%" POINTERSIZE "s %8s %8s %20s %2s %8s %" POINTERSIZE "s %s\n",
"MT", "Field", "Offset", "Type", "VT", "Attr", "Value", "Name");
numInstanceFields = 0;
}
BOOL fIsShared = pMTD->bIsShared;
if (pMTD->ParentMethodTable)
{
DacpMethodTableData vParentMethTable;
if (vParentMethTable.Request(g_sos,pMTD->ParentMethodTable) != S_OK)
{
ExtOut("Invalid parent MethodTable\n");
return;
}
DacpMethodTableFieldData vParentMethTableFields;
if (vParentMethTableFields.Request(g_sos,pMTD->ParentMethodTable) != S_OK)
{
ExtOut("Invalid parent EEClass\n");
return;
}
DisplayFields(pMTD->ParentMethodTable, &vParentMethTable, &vParentMethTableFields, dwStartAddr, FALSE, bValueClass);
}
DWORD numStaticFields = 0;
CLRDATA_ADDRESS dwAddr = pMTFD->FirstField;
DacpFieldDescData vFieldDesc;
// Get the module name
DacpModuleData module;
if (module.Request(g_sos, pMTD->Module)!=S_OK)
return;
ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
while (numInstanceFields < pMTFD->wNumInstanceFields
|| numStaticFields < pMTFD->wNumStaticFields)
{
if (IsInterrupt())
return;
ExtOutIndent ();
if ((vFieldDesc.Request(g_sos, dwAddr)!=S_OK) ||
(vFieldDesc.Type >= ELEMENT_TYPE_MAX))
{
ExtOut("Unable to display fields\n");
return;
}
dwAddr = vFieldDesc.NextField;
DWORD offset = vFieldDesc.dwOffset;
if(!((vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal || fIsShared) && vFieldDesc.bIsStatic))
{
if (!bValueClass)
{
offset += sizeof(BaseObject);
}
}
DMLOut("%s %8x %8x ", DMLMethodTable(vFieldDesc.MTOfType),
TokenFromRid(vFieldDesc.mb, mdtFieldDef),
offset);
char ElementName[mdNameLen];
if ((vFieldDesc.Type == ELEMENT_TYPE_VALUETYPE ||
vFieldDesc.Type == ELEMENT_TYPE_CLASS) && vFieldDesc.MTOfType)
{
NameForMT_s((DWORD_PTR)vFieldDesc.MTOfType, g_mdName, mdNameLen);
ExtOut("%20.20S ", FormatTypeName(g_mdName, 20));
}
else
{
if (vFieldDesc.Type == ELEMENT_TYPE_CLASS && vFieldDesc.TokenOfType != mdTypeDefNil)
{
// Get the name from Metadata!!!
NameForToken_s(TokenFromRid(vFieldDesc.TokenOfType, mdtTypeDef), pImport, g_mdName, mdNameLen, false);
ExtOut("%20.20S ", FormatTypeName(g_mdName, 20));
}
else
{
// If ET type from signature is different from fielddesc, then the signature one is more descriptive.
// For example, E_T_STRING in field desc will be E_T_CLASS. In minidump's case, we won't have
// the method table for it.
ComposeName_s(vFieldDesc.Type != vFieldDesc.sigType ? vFieldDesc.sigType : vFieldDesc.Type, ElementName, sizeof(ElementName)/sizeof(ElementName[0]));
ExtOut("%20.20s ", ElementName);
}
}
ExtOut("%2s ", (IsElementValueType(vFieldDesc.Type)) ? "1" : "0");
if (vFieldDesc.bIsStatic && (vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal))
{
numStaticFields ++;
if (fIsShared)
ExtOut("%8s %" POINTERSIZE "s", "shared", vFieldDesc.bIsThreadLocal ? "TLstatic" : "CLstatic");
else
ExtOut("%8s ", vFieldDesc.bIsThreadLocal ? "TLstatic" : "CLstatic");
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
if (IsMiniDumpFile())
{
ExtOut(" <no information>\n");
}
else
{
if (vFieldDesc.bIsThreadLocal)
{
DacpModuleData vModule;
if (vModule.Request(g_sos,pMTD->Module) == S_OK)
{
DisplayThreadStatic(&vModule, pMTD, &vFieldDesc, fIsShared);
}
}
else if (vFieldDesc.bIsContextLocal)
{
ExtOut("\nDisplay of context static variables is not implemented\n");
}
}
}
else if (vFieldDesc.bIsStatic)
{
numStaticFields ++;
if (fIsShared)
{
ExtOut("%8s %" POINTERSIZE "s", "shared", "static");
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
if (IsMiniDumpFile())
{
ExtOut(" <no information>\n");
}
else
{
DacpModuleData vModule;
if (vModule.Request(g_sos,pMTD->Module) == S_OK)
{
DisplaySharedStatic(vModule.dwModuleID, pMTD, &vFieldDesc);
}
}
}
else
{
ExtOut("%8s ", "static");
DacpDomainLocalModuleData vDomainLocalModule;
// The MethodTable isn't shared, so the module must not be loaded domain neutral. We can
// get the specific DomainLocalModule instance without needing to know the AppDomain in advance.
if (g_sos->GetDomainLocalModuleDataFromModule(pMTD->Module, &vDomainLocalModule) != S_OK)
{
ExtOut(" <no information>\n");
}
else
{
DWORD_PTR dwTmp;
GetStaticFieldPTR(&dwTmp, &vDomainLocalModule, pMTD, &vFieldDesc);
DisplayDataMember(&vFieldDesc, dwTmp);
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
}
}
}
else
{
numInstanceFields ++;
ExtOut("%8s ", "instance");
if (dwStartAddr > 0)
{
DWORD_PTR dwTmp = dwStartAddr + vFieldDesc.dwOffset + (bValueClass ? 0 : sizeof(BaseObject));
DisplayDataMember(&vFieldDesc, dwTmp);
}
else
{
ExtOut(" %8s", " ");
}
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
ExtOut(" %S\n", g_mdName);
}
}
return;
}
HRESULT GetNonSharedStaticFieldValueFromName(
UINT64* pValue,
DWORD_PTR moduleAddr,
const char *typeName,
__in_z LPCWSTR wszFieldName,
CorElementType fieldType)
{
HRESULT hr = S_OK;
mdTypeDef mdType = 0;
GetInfoFromName(moduleAddr, typeName, &mdType);
if (mdType == 0)
{
return E_FAIL; // Failed to find type token
}
CLRDATA_ADDRESS cdaMethodTable = 0;
if (FAILED(hr = g_sos->GetMethodDescFromToken(moduleAddr, mdType, &cdaMethodTable)) ||
!IsValidToken(moduleAddr, mdType) ||
cdaMethodTable == 0)
{
return FAILED(hr) ? hr : E_FAIL; // Invalid type token or type is not loaded yet
}
DacpMethodTableData vMethodTable;
if ((hr = vMethodTable.Request(g_sos, cdaMethodTable)) != S_OK)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get method table data
}
if (vMethodTable.bIsShared)
{
ExtOut(" %s: %s\n", "Method table is shared (not implemented)", typeName);
return E_NOTIMPL;
}
DacpMethodTableFieldData vMethodTableFields;
if (FAILED(hr = vMethodTableFields.Request(g_sos, cdaMethodTable)))
{
return hr; // Failed to get field data
}
DacpModuleData vModule;
if ((hr = vModule.Request(g_sos, vMethodTable.Module)) != S_OK)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get module data
}
DacpDomainLocalModuleData vDomainLocalModule;
if ((hr = g_sos->GetDomainLocalModuleDataFromModule(vMethodTable.Module, &vDomainLocalModule)) != S_OK)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get domain local module data
}
ToRelease<IMetaDataImport> pImport = MDImportForModule(&vModule);
CLRDATA_ADDRESS cdaField = vMethodTableFields.FirstField;
DacpFieldDescData vFieldDesc;
bool found = false;
for (DWORD staticFieldIndex = 0; staticFieldIndex < vMethodTableFields.wNumStaticFields; )
{
if ((hr = vFieldDesc.Request(g_sos, cdaField)) != S_OK || vFieldDesc.Type >= ELEMENT_TYPE_MAX)
{
return FAILED(hr) ? hr : E_FAIL; // Failed to get member field desc
}
cdaField = vFieldDesc.NextField;
if (!vFieldDesc.bIsStatic)
{
continue;
}
++staticFieldIndex;
if (vFieldDesc.Type != fieldType)
{
continue;
}
if (FAILED(hr = NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false)))
{
return hr; // Failed to get member field name
}
if (_wcscmp(g_mdName, wszFieldName) != 0)
{
continue;
}
if (vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal)
{
ExtOut(" %s: %s.%S\n", "Static field is thread-local or context-local (not implemented)", typeName, wszFieldName);
return E_NOTIMPL;
}
found = true;
break;
}
if (!found)
{
return E_FAIL; // Static field not found
}
DWORD_PTR pValueAddr = 0;
GetStaticFieldPTR(&pValueAddr, &vDomainLocalModule, &vMethodTable, &vFieldDesc);
if (pValueAddr == 0)
{
return E_FAIL; // Failed to get static field address
}
UINT64 value = 0;
if (FAILED(MOVEBLOCK(value, pValueAddr, gElementTypeInfo[fieldType])))
{
return E_FAIL; // Failed to read static field
}
*pValue = value;
return S_OK;
}
// Return value: -1 = error,
// 0 = field not found,
// > 0 = offset to field from objAddr
int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, __in_z LPCWSTR wszFieldName, BOOL bFirst)
{
TADDR mt = NULL;
if FAILED(GetMTOfObject(TO_TADDR(cdaObj), &mt))
return -1;
return GetObjFieldOffset(cdaObj, TO_CDADDR(mt), wszFieldName, bFirst);
}
// Return value: -1 = error,
// 0 = field not found,
// > 0 = offset to field from objAddr
int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName,
BOOL bFirst/*=TRUE*/, DacpFieldDescData* pDacpFieldDescData/*=NULL*/)
{
#define EXITPOINT(EXPR) do { if(!(EXPR)) { return -1; } } while (0)
DacpObjectData objData;
DacpMethodTableData dmtd;
DacpMethodTableFieldData vMethodTableFields;
DacpFieldDescData vFieldDesc;
DacpModuleData module;
static DWORD numInstanceFields = 0; // Static due to recursion visiting parents
if (bFirst)
{
numInstanceFields = 0;
}
EXITPOINT(objData.Request(g_sos, cdaObj) == S_OK);
EXITPOINT(dmtd.Request(g_sos, cdaMT) == S_OK);
if (dmtd.ParentMethodTable)
{
DWORD retVal = GetObjFieldOffset (cdaObj, dmtd.ParentMethodTable,
wszFieldName, FALSE, pDacpFieldDescData);
if (retVal != 0)
{
// return in case of error or success.
// Fall through for field-not-found.
return retVal;
}
}
EXITPOINT (vMethodTableFields.Request(g_sos,cdaMT) == S_OK);
EXITPOINT (module.Request(g_sos,dmtd.Module) == S_OK);
CLRDATA_ADDRESS dwAddr = vMethodTableFields.FirstField;
ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
while (numInstanceFields < vMethodTableFields.wNumInstanceFields)
{
EXITPOINT (vFieldDesc.Request(g_sos, dwAddr) == S_OK);
if (!vFieldDesc.bIsStatic)
{
DWORD offset = vFieldDesc.dwOffset + sizeof(BaseObject);
NameForToken_s (TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
if (_wcscmp (wszFieldName, g_mdName) == 0)
{
if (pDacpFieldDescData != NULL)
{
*pDacpFieldDescData = vFieldDesc;
}
return offset;
}
numInstanceFields ++;
}
dwAddr = vFieldDesc.NextField;
}
// Field name not found...
return 0;
#undef EXITPOINT
}
// Return value: -1 = error
// -2 = not found
// >= 0 = offset to field from cdaValue
int GetValueFieldOffset(CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName, DacpFieldDescData* pDacpFieldDescData)
{
#define EXITPOINT(EXPR) do { if(!(EXPR)) { return -1; } } while (0)
const int NOT_FOUND = -2;
DacpMethodTableData dmtd;
DacpMethodTableFieldData vMethodTableFields;
DacpFieldDescData vFieldDesc;
DacpModuleData module;
static DWORD numInstanceFields = 0; // Static due to recursion visiting parents
numInstanceFields = 0;
EXITPOINT(vMethodTableFields.Request(g_sos, cdaMT) == S_OK);
EXITPOINT(dmtd.Request(g_sos, cdaMT) == S_OK);
EXITPOINT(module.Request(g_sos, dmtd.Module) == S_OK);
if (dmtd.ParentMethodTable)
{
DWORD retVal = GetValueFieldOffset(dmtd.ParentMethodTable, wszFieldName, pDacpFieldDescData);
if (retVal != (DWORD)NOT_FOUND)
{
// Return in case of error or success. Fall through for field-not-found.
return retVal;
}
}
CLRDATA_ADDRESS dwAddr = vMethodTableFields.FirstField;
ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
while (numInstanceFields < vMethodTableFields.wNumInstanceFields)
{
EXITPOINT(vFieldDesc.Request(g_sos, dwAddr) == S_OK);
if (!vFieldDesc.bIsStatic)
{
NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
if (_wcscmp(wszFieldName, g_mdName) == 0)
{
if (pDacpFieldDescData != NULL)
{
*pDacpFieldDescData = vFieldDesc;
}
return vFieldDesc.dwOffset;
}
numInstanceFields++;
}
dwAddr = vFieldDesc.NextField;
}
// Field name not found...
return NOT_FOUND;
#undef EXITPOINT
}
// Returns an AppDomain address if AssemblyPtr is loaded into that domain only. Otherwise
// returns NULL
CLRDATA_ADDRESS IsInOneDomainOnly(CLRDATA_ADDRESS AssemblyPtr)
{
CLRDATA_ADDRESS appDomain = NULL;
DacpAppDomainStoreData adstore;
if (adstore.Request(g_sos) != S_OK)
{
ExtOut("Unable to get appdomain store\n");
return NULL;
}
size_t AllocSize;
if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), adstore.DomainCount, AllocSize))
{
ReportOOM();
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adstore.DomainCount];
if (pArray==NULL)
{
ReportOOM();
return NULL;
}
if (g_sos->GetAppDomainList(adstore.DomainCount, pArray, NULL)!=S_OK)
{
ExtOut ("Failed to get appdomain list\n");
return NULL;
}
for (int i = 0; i < adstore.DomainCount; i++)
{
if (IsInterrupt())
return NULL;
DacpAppDomainData dadd;
if (dadd.Request(g_sos, pArray[i]) != S_OK)
{
ExtOut ("Unable to get AppDomain %p\n", SOS_PTR(pArray[i]));
return NULL;
}
if (dadd.AssemblyCount)
{
size_t AssemblyAllocSize;
if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), dadd.AssemblyCount, AssemblyAllocSize))
{
ReportOOM();
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pAsmArray = new CLRDATA_ADDRESS[dadd.AssemblyCount];
if (pAsmArray==NULL)
{
ReportOOM();
return NULL;
}
if (g_sos->GetAssemblyList(dadd.AppDomainPtr,dadd.AssemblyCount,pAsmArray, NULL)!=S_OK)
{
ExtOut("Unable to get array of Assemblies\n");
return NULL;
}
for (LONG n = 0; n < dadd.AssemblyCount; n ++)
{
if (IsInterrupt())
return NULL;
if (AssemblyPtr == pAsmArray[n])
{
if (appDomain != NULL)
{
// We have found more than one AppDomain that loaded this
// assembly, we must return NULL.
return NULL;
}
appDomain = dadd.AppDomainPtr;
}
}
}
}
return appDomain;
}
CLRDATA_ADDRESS GetAppDomainForMT(CLRDATA_ADDRESS mtPtr)
{
DacpMethodTableData mt;
if (mt.Request(g_sos, mtPtr) != S_OK)
{
return NULL;
}
DacpModuleData module;
if (module.Request(g_sos, mt.Module) != S_OK)
{
return NULL;
}
DacpAssemblyData assembly;
if (assembly.Request(g_sos, module.Assembly) != S_OK)
{
return NULL;
}
DacpAppDomainStoreData adstore;
if (adstore.Request(g_sos) != S_OK)
{
return NULL;
}
return (assembly.ParentDomain == adstore.sharedDomain) ?
IsInOneDomainOnly(assembly.AssemblyPtr) :
assembly.ParentDomain;
}
CLRDATA_ADDRESS GetAppDomain(CLRDATA_ADDRESS objPtr)
{
CLRDATA_ADDRESS appDomain = NULL;
DacpObjectData objData;
if (objData.Request(g_sos,objPtr) != S_OK)
{
return NULL;
}
// First check eeclass->module->assembly->domain.
// Then check the object flags word
// finally, search threads for a reference to the object, and look at the thread context.
DacpMethodTableData mt;
if (mt.Request(g_sos,objData.MethodTable) != S_OK)
{
return NULL;
}
DacpModuleData module;
if (module.Request(g_sos,mt.Module) != S_OK)
{
return NULL;
}
DacpAssemblyData assembly;
if (assembly.Request(g_sos,module.Assembly) != S_OK)
{
return NULL;
}
DacpAppDomainStoreData adstore;
if (adstore.Request(g_sos) != S_OK)
{
return NULL;
}
if (assembly.ParentDomain == adstore.sharedDomain)
{
sos::Object obj(TO_TADDR(objPtr));
ULONG value = 0;
if (!obj.TryGetHeader(value))
{
return NULL;
}
DWORD adIndex = (value >> SBLK_APPDOMAIN_SHIFT) & SBLK_MASK_APPDOMAININDEX;
if ( ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0) || adIndex==0)
{
// No AppDomainID information. We'll make use of a heuristic.
// If the assembly is in the shared domain, we can report it as
// being in domain X if the only other domain that has the assembly
// loaded is domain X.
appDomain = IsInOneDomainOnly(assembly.AssemblyPtr);
if (appDomain == NULL && ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0))
{
if ((value & BIT_SBLK_IS_HASHCODE) == 0)
{
UINT index = value & MASK_SYNCBLOCKINDEX;
// We have a syncblock, the appdomain ID may be in there.
DacpSyncBlockData syncBlockData;
if (syncBlockData.Request(g_sos,index) == S_OK)
{
appDomain = syncBlockData.appDomainPtr;
}
}
}
}
else if ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0)
{
size_t AllocSize;
if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), adstore.DomainCount, AllocSize))
{
return NULL;
}
// we know we have a non-zero adIndex. Find the appdomain.
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adstore.DomainCount];
if (pArray==NULL)
{
return NULL;
}
if (g_sos->GetAppDomainList(adstore.DomainCount, pArray, NULL)!=S_OK)
{
return NULL;
}
for (int i = 0; i < adstore.DomainCount; i++)
{
DacpAppDomainData dadd;
if (dadd.Request(g_sos, pArray[i]) != S_OK)
{
return NULL;
}
if (dadd.dwId == adIndex)
{
appDomain = pArray[i];
break;
}
}
}
}
else
{
appDomain = assembly.ParentDomain;
}
return appDomain;
}
HRESULT FileNameForModule (DWORD_PTR pModuleAddr, __out_ecount (MAX_LONGPATH) WCHAR *fileName)
{
DacpModuleData ModuleData;
fileName[0] = L'\0';
HRESULT hr = ModuleData.Request(g_sos, TO_CDADDR(pModuleAddr));
if (SUCCEEDED(hr))
{
hr = FileNameForModule(&ModuleData,fileName);
}
return hr;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find the file name given a Module. *
* *
\**********************************************************************/
// fileName should be at least MAX_LONGPATH
HRESULT FileNameForModule(const DacpModuleData* const pModuleData, __out_ecount(MAX_LONGPATH) WCHAR* fileName)
{
fileName[0] = W('\0');
HRESULT hr = S_OK;
CLRDATA_ADDRESS dwAddr = pModuleData->PEAssembly;
if (dwAddr == 0)
{
// TODO: We have dynamic module
return E_NOTIMPL;
}
CLRDATA_ADDRESS base = 0;
hr = g_sos->GetPEFileBase(dwAddr, &base);
if (SUCCEEDED(hr))
{
hr = g_sos->GetPEFileName(dwAddr, MAX_LONGPATH, fileName, NULL);
if (SUCCEEDED(hr) && fileName[0] != W('\0'))
return hr; // done
#ifndef FEATURE_PAL
// Try the base *
if (base)
{
hr = DllsName((ULONG_PTR)base, fileName);
if (SUCCEEDED(hr) && fileName[0] != W('\0'))
return hr; // done
}
#endif // !FEATURE_PAL
}
ToRelease<IXCLRDataModule> pModule;
if (SUCCEEDED(g_sos->GetModule(pModuleData->Address, &pModule)))
{
ULONG32 nameLen = 0;
hr = pModule->GetFileName(MAX_LONGPATH, &nameLen, fileName);
}
return hr;
}
void AssemblyInfo(DacpAssemblyData *pAssembly)
{
ExtOut("ClassLoader: %p\n", SOS_PTR(pAssembly->ClassLoader));
if ((ULONG64)pAssembly->AssemblySecDesc != NULL)
ExtOut("SecurityDescriptor: %p\n", SOS_PTR(pAssembly->AssemblySecDesc));
ExtOut(" Module\n");
ArrayHolder<CLRDATA_ADDRESS> Modules = new CLRDATA_ADDRESS[pAssembly->ModuleCount];
if (Modules == NULL
|| g_sos->GetAssemblyModuleList(pAssembly->AssemblyPtr, pAssembly->ModuleCount, Modules, NULL) != S_OK)
{
ReportOOM();
return;
}
for (UINT n = 0; n < pAssembly->ModuleCount; n++)
{
if (IsInterrupt())
{
return;
}
CLRDATA_ADDRESS ModuleAddr = Modules[n];
DMLOut(" %s " WIN86_8SPACES, DMLModule(ModuleAddr));
DacpModuleData moduleData;
if (moduleData.Request(g_sos, ModuleAddr) == S_OK)
{
WCHAR fileName[MAX_LONGPATH];
FileNameForModule (&moduleData, fileName);
if (fileName[0])
{
ExtOut("%S\n", fileName);
}
else
{
ExtOut("%S\n", (moduleData.bIsReflection) ? W("Dynamic Module") : W("Unknown Module"));
}
}
else
{
ExtOut("Request module data FAILED\n");
}
}
}
const char *GetStageText(DacpAppDomainDataStage stage)
{
switch(stage)
{
case STAGE_CREATING:
return "CREATING";
case STAGE_READYFORMANAGEDCODE:
return "READYFORMANAGEDCODE";
case STAGE_ACTIVE:
return "ACTIVE";
case STAGE_OPEN:
return "OPEN";
case STAGE_UNLOAD_REQUESTED:
return "UNLOAD_REQUESTED";
case STAGE_EXITING:
return "EXITING";
case STAGE_EXITED:
return "EXITED";
case STAGE_FINALIZING:
return "FINALIZING";
case STAGE_FINALIZED:
return "FINALIZED";
case STAGE_HANDLETABLE_NOACCESS:
return "HANDLETABLE_NOACCESS";
case STAGE_CLEARED:
return "CLEARED";
case STAGE_COLLECTED:
return "COLLECTED";
case STAGE_CLOSED:
return "CLOSED";
}
return "UNKNOWN";
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to dump the contents of a domain. *
* *
\**********************************************************************/
void DomainInfo (DacpAppDomainData *pDomain)
{
ExtOut("LowFrequencyHeap: %p\n", SOS_PTR(pDomain->pLowFrequencyHeap));
ExtOut("HighFrequencyHeap: %p\n", SOS_PTR(pDomain->pHighFrequencyHeap));
ExtOut("StubHeap: %p\n", SOS_PTR(pDomain->pStubHeap));
ExtOut("Stage: %s\n", GetStageText(pDomain->appDomainStage));
if ((ULONG64)pDomain->AppSecDesc != NULL)
ExtOut("SecurityDescriptor: %p\n", SOS_PTR(pDomain->AppSecDesc));
ExtOut("Name: ");
if (g_sos->GetAppDomainName(pDomain->AppDomainPtr, mdNameLen, g_mdName, NULL)!=S_OK)
{
ExtOut("Error getting AppDomain friendly name\n");
}
else
{
ExtOut("%S\n", (g_mdName[0] != L'\0') ? g_mdName : W("None"));
}
if (pDomain->AssemblyCount == 0)
return;
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[pDomain->AssemblyCount];
if (pArray==NULL)
{
ReportOOM();
return;
}
if (g_sos->GetAssemblyList(pDomain->AppDomainPtr,pDomain->AssemblyCount,pArray, NULL)!=S_OK)
{
ExtOut("Unable to get array of Assemblies\n");
return;
}
LONG n;
// Assembly vAssembly;
for (n = 0; n < pDomain->AssemblyCount; n ++)
{
if (IsInterrupt())
return;
if (n != 0)
ExtOut("\n");
DMLOut("Assembly: %s", DMLAssembly(pArray[n]));
DacpAssemblyData assemblyData;
if (assemblyData.Request(g_sos, pArray[n], pDomain->AppDomainPtr) == S_OK)
{
if (assemblyData.isDynamic)
ExtOut(" (Dynamic)");
ExtOut(" [");
if (g_sos->GetAssemblyName(pArray[n], mdNameLen, g_mdName, NULL) == S_OK)
ExtOut("%S", g_mdName);
ExtOut("]\n");
AssemblyInfo(&assemblyData);
}
}
ExtOut("\n");
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find the name of a MethodDesc using *
* metadata API. *
* *
\**********************************************************************/
BOOL NameForMD_s (DWORD_PTR pMD, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName)
{
mdName[0] = L'\0';
CLRDATA_ADDRESS StartAddr = TO_CDADDR(pMD);
DacpMethodDescData MethodDescData;
// don't need to check for minidump file as all commands are seals
// We also do not have EEJitManager to validate anyway.
//
if (!IsMiniDumpFile() && MethodDescData.Request(g_sos,StartAddr) != S_OK)
{
ExtOut("%p is not a MethodDesc\n", SOS_PTR(StartAddr));
return FALSE;
}
if (g_sos->GetMethodDescName(StartAddr, mdNameLen, mdName, NULL) != S_OK)
{
wcscpy_s(mdName, capacity_mdName, W("UNKNOWN"));
return FALSE;
}
return TRUE;
}
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find the name of a MethodTable using *
* metadata API. *
* *
\**********************************************************************/
BOOL NameForMT_s(DWORD_PTR MTAddr, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName)
{
HRESULT hr = g_sos->GetMethodTableName(TO_CDADDR(MTAddr), (ULONG32)capacity_mdName, mdName, NULL);
return SUCCEEDED(hr);
}
WCHAR *CreateMethodTableName(TADDR mt, TADDR cmt)
{
bool array = false;
WCHAR *res = NULL;
if (mt == sos::MethodTable::GetFreeMT())
{
res = new WCHAR[5];
wcscpy_s(res, 5, W("Free"));
return res;
}
if (mt == sos::MethodTable::GetArrayMT() && cmt != NULL)
{
mt = cmt;
array = true;
}
unsigned int needed = 0;
HRESULT hr = g_sos->GetMethodTableName(mt, 0, NULL, &needed);
// If failed, we will return null.
if (SUCCEEDED(hr))
{
// +2 for [], if we need it.
res = new WCHAR[needed+2];
hr = g_sos->GetMethodTableName(mt, needed, res, NULL);
if (FAILED(hr))
{
delete [] res;
res = NULL;
}
else if (array)
{
res[needed-1] = '[';
res[needed] = ']';
res[needed+1] = 0;
}
}
return res;
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if str2 is a substring of str1 and str1 and str2 *
* share the same file path.
* *
\**********************************************************************/
BOOL IsSameModuleName (const char *str1, const char *str2)
{
if (strlen (str1) < strlen (str2))
return FALSE;
const char *ptr1 = str1 + strlen(str1)-1;
const char *ptr2 = str2 + strlen(str2)-1;
while (ptr2 >= str2)
{
#ifndef FEATURE_PAL
if (tolower(*ptr1) != tolower(*ptr2))
#else
if (*ptr1 != *ptr2)
#endif
{
return FALSE;
}
ptr2--;
ptr1--;
}
if (ptr1 >= str1 && *ptr1 != GetTargetDirectorySeparatorW() && *ptr1 != ':')
{
return FALSE;
}
return TRUE;
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if moduleAddr is the address of a module. *
* *
\**********************************************************************/
BOOL IsModule (DWORD_PTR moduleAddr)
{
DacpModuleData module;
return (module.Request(g_sos, TO_CDADDR(moduleAddr))==S_OK);
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if value is the address of a MethodTable. *
* We verify that MethodTable and EEClass are right.
* *
\**********************************************************************/
BOOL IsMethodTable (DWORD_PTR value)
{
DacpMethodTableData mtabledata;
if (mtabledata.Request(g_sos, TO_CDADDR(value))!=S_OK)
{
return FALSE;
}
return TRUE;
}
/**********************************************************************\
* Routine Description: *
* *
* Return TRUE if value is the address of a MethodDesc. *
* We verify that MethodTable and EEClass are right.
* *
\**********************************************************************/
BOOL IsMethodDesc (DWORD_PTR value)
{
// Just by retrieving one successfully from the DAC, we know we have a MethodDesc.
DacpMethodDescData MethodDescData;
if (MethodDescData.Request(g_sos, TO_CDADDR(value)) != S_OK)
{
return FALSE;
}
return TRUE;
}
DacpUsefulGlobalsData g_special_usefulGlobals;
BOOL IsObjectArray (DacpObjectData *pData)
{
if (pData->ObjectType == OBJ_ARRAY)
return g_special_usefulGlobals.ArrayMethodTable == pData->MethodTable;
return FALSE;
}
BOOL IsObjectArray (DWORD_PTR obj)
{
DWORD_PTR mtAddr = NULL;
if (SUCCEEDED(GetMTOfObject(obj, &mtAddr)))
return TO_TADDR(g_special_usefulGlobals.ArrayMethodTable) == mtAddr;
return FALSE;
}
BOOL IsStringObject (size_t obj)
{
DWORD_PTR mtAddr = NULL;
if (SUCCEEDED(GetMTOfObject(obj, &mtAddr)))
return TO_TADDR(g_special_usefulGlobals.StringMethodTable) == mtAddr;
return FALSE;
}
BOOL IsDerivedFrom(CLRDATA_ADDRESS mtObj, __in_z LPCWSTR baseString)
{
DacpMethodTableData dmtd;
CLRDATA_ADDRESS walkMT = mtObj;
while (walkMT != NULL)
{
if (dmtd.Request(g_sos, walkMT) != S_OK)
{
break;
}
NameForMT_s(TO_TADDR(walkMT), g_mdName, mdNameLen);
if (_wcscmp(baseString, g_mdName) == 0)
{
return TRUE;
}
walkMT = dmtd.ParentMethodTable;
}
return FALSE;
}
BOOL IsDerivedFrom(CLRDATA_ADDRESS mtObj, DWORD_PTR modulePtr, mdTypeDef typeDef)
{
DacpMethodTableData dmtd;
for (CLRDATA_ADDRESS walkMT = mtObj;
walkMT != NULL && dmtd.Request(g_sos, walkMT) == S_OK;
walkMT = dmtd.ParentMethodTable)
{
if (dmtd.Module == modulePtr && dmtd.cl == typeDef)
{
return TRUE;
}
}
return FALSE;
}
BOOL TryGetMethodDescriptorForDelegate(CLRDATA_ADDRESS delegateAddr, CLRDATA_ADDRESS* pMD)
{
if (!sos::IsObject(delegateAddr, false))
{
return FALSE;
}
sos::Object delegateObj = TO_TADDR(delegateAddr);
for (int i = 0; i < 2; i++)
{
int offset;
if ((offset = GetObjFieldOffset(delegateObj.GetAddress(), delegateObj.GetMT(), i == 0 ? W("_methodPtrAux") : W("_methodPtr"))) != 0)
{
CLRDATA_ADDRESS methodPtr;
MOVE(methodPtr, delegateObj.GetAddress() + offset);
if (methodPtr != NULL)
{
if (g_sos->GetMethodDescPtrFromIP(methodPtr, pMD) == S_OK)
{
return TRUE;
}
DacpCodeHeaderData codeHeaderData;
if (codeHeaderData.Request(g_sos, methodPtr) == S_OK)
{
*pMD = codeHeaderData.MethodDescPtr;
return TRUE;
}
}
}
}
return FALSE;
}
void DumpStackObjectsOutput(const char *location, DWORD_PTR objAddr, BOOL verifyFields)
{
// rule out pointers that are outside of the gc heap.
if (g_snapshot.GetHeap(objAddr) == NULL)
return;
DacpObjectData objectData;
if (objectData.Request(g_sos, TO_CDADDR(objAddr)) != S_OK)
return;
if (sos::IsObject(objAddr, verifyFields != FALSE)
&& !sos::MethodTable::IsFreeMT(TO_TADDR(objectData.MethodTable)))
{
DMLOut("%-" POINTERSIZE "s %s ", location, DMLObject(objAddr));
if (g_sos->GetObjectClassName(TO_CDADDR(objAddr), mdNameLen, g_mdName, NULL)==S_OK)
{
ExtOut("%S", g_mdName);
if (IsStringObject(objAddr))
{
ExtOut(" ");
StringObjectContent(objAddr, FALSE, 40);
}
else if (IsObjectArray(objAddr) &&
(g_sos->GetMethodTableName(objectData.ElementTypeHandle, mdNameLen, g_mdName, NULL) == S_OK))
{
ExtOut(" ");
ExtOut("(%S[])", g_mdName);
}
}
else
{
ExtOut("<unknown type>");
}
ExtOut("\n");
}
}
void DumpStackObjectsOutput(DWORD_PTR ptr, DWORD_PTR objAddr, BOOL verifyFields)
{
char location[64];
sprintf_s(location, 64, "%p", (DWORD_PTR *)ptr);
DumpStackObjectsOutput(location, objAddr, verifyFields);
}
void DumpStackObjectsInternal(size_t StackTop, size_t StackBottom, BOOL verifyFields)
{
for (DWORD_PTR ptr = StackTop; ptr <= StackBottom; ptr += sizeof(DWORD_PTR))
{
if (IsInterrupt())
return;
DWORD_PTR objAddr;
move_xp(objAddr, ptr);
DumpStackObjectsOutput(ptr, objAddr, verifyFields);
}
}
void DumpRegObjectHelper(const char *regName, BOOL verifyFields)
{
DWORD_PTR reg;
#ifdef FEATURE_PAL
if (FAILED(g_ExtRegisters->GetValueByName(regName, ®)))
return;
#else
DEBUG_VALUE value;
ULONG IREG;
if (FAILED(g_ExtRegisters->GetIndexByName(regName, &IREG)) ||
FAILED(g_ExtRegisters->GetValue(IREG, &value)))
return;
#if defined(SOS_TARGET_X86) || defined(SOS_TARGET_ARM)
reg = (DWORD_PTR) value.I32;
#elif defined(SOS_TARGET_AMD64) || defined(SOS_TARGET_ARM64)
reg = (DWORD_PTR) value.I64;
#else
#error Unsupported target
#endif
#endif // FEATURE_PAL
DumpStackObjectsOutput(regName, reg, verifyFields);
}
void DumpStackObjectsHelper (
TADDR StackTop,
TADDR StackBottom,
BOOL verifyFields)
{
ExtOut(g_targetMachine->GetDumpStackObjectsHeading());
LPCSTR* regs;
unsigned int cnt;
g_targetMachine->GetGCRegisters(®s, &cnt);
for (size_t i = 0; i < cnt; ++i)
DumpRegObjectHelper(regs[i], verifyFields);
// Make certain StackTop is dword aligned:
DumpStackObjectsInternal(StackTop & ~ALIGNCONST, StackBottom, verifyFields);
}
void AddToModuleList(DWORD_PTR * &moduleList, int &numModule, int &maxList,
DWORD_PTR dwModuleAddr)
{
int i;
for (i = 0; i < numModule; i ++)
{
if (moduleList[i] == dwModuleAddr)
break;
}
if (i == numModule)
{
moduleList[numModule] = dwModuleAddr;
numModule ++;
if (numModule == maxList)
{
int listLength = 0;
if (!ClrSafeInt<int>::multiply(maxList, 2, listLength))
{
ExtOut("<integer overflow>\n");
numModule = 0;
ControlC = 1;
return;
}
DWORD_PTR *list = new DWORD_PTR [listLength];
if (list == NULL)
{
numModule = 0;
ControlC = 1;
return;
}
memcpy (list, moduleList, maxList * sizeof(PVOID));
delete[] moduleList;
moduleList = list;
maxList *= 2;
}
}
}
BOOL IsFusionLoadedModule (LPCSTR fusionName, LPCSTR mName)
{
// The fusion name will be in this format:
// <module name>, Version=<version>, Culture=<culture>, PublicKeyToken=<token>
// If fusionName up to the comma matches mName (case insensitive),
// we consider that a match was found.
LPCSTR commaPos = strchr (fusionName, ',');
if (commaPos)
{
// verify that fusionName and mName match up to a comma.
while (*fusionName != ',')
{
if (*mName == '\0')
{
return FALSE;
}
#ifndef FEATURE_PAL
if (tolower(*fusionName) != tolower(*mName))
#else
if (*fusionName != *mName)
#endif
{
return FALSE;
}
fusionName++;
mName++;
}
return TRUE;
}
return FALSE;
}
BOOL DebuggerModuleNamesMatch (CLRDATA_ADDRESS PEFileAddr, ___in __in_z LPSTR mName)
{
// Another way to see if a module is the same is
// to accept that mName may be the debugger's name for
// a loaded module. We can get the debugger's name for
// the module we are looking at right now, and compare
// it with mName, if they match exactly, we can add
// the module to the list.
if (PEFileAddr)
{
CLRDATA_ADDRESS pebase = 0;
if (g_sos->GetPEFileBase(PEFileAddr, &pebase) == S_OK)
{
if (pebase)
{
ULONG Index;
ULONG64 base;
if (g_ExtSymbols->GetModuleByOffset(pebase, 0, &Index, &base) == S_OK)
{
CHAR ModuleName[MAX_LONGPATH+1];
if (g_ExtSymbols->GetModuleNames(Index, base, NULL, 0, NULL, ModuleName,
MAX_LONGPATH, NULL, NULL, 0, NULL) == S_OK)
{
if (_stricmp (ModuleName, mName) == 0)
{
return TRUE;
}
}
}
}
}
}
return FALSE;
}
DWORD_PTR *ModuleFromName(__in_opt LPSTR mName, int *numModule)
{
if (numModule == NULL)
return NULL;
DWORD_PTR *moduleList = NULL;
*numModule = 0;
HRESULT hr;
DacpAppDomainStoreData adsData;
if ((hr = adsData.Request(g_sos)) != S_OK)
{
ExtDbgOut("DacpAppDomainStoreData.Request FAILED %08x\n", hr);
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pAssemblyArray = NULL;
ArrayHolder<CLRDATA_ADDRESS> pModules = NULL;
int arrayLength = 0;
int numSpecialDomains = (adsData.sharedDomain != NULL) ? 2 : 1;
if (!ClrSafeInt<int>::addition(adsData.DomainCount, numSpecialDomains, arrayLength))
{
ExtOut("<integer overflow>\n");
return NULL;
}
ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[arrayLength];
if (pArray == NULL)
{
ReportOOM();
return NULL;
}
pArray[0] = adsData.systemDomain;
if (adsData.sharedDomain != NULL)
{
pArray[1] = adsData.sharedDomain;
}
if ((hr = g_sos->GetAppDomainList(adsData.DomainCount, pArray.GetPtr() + numSpecialDomains, NULL)) != S_OK)
{
ExtOut("Unable to get array of AppDomains: %08x\n", hr);
return NULL;
}
// List all domain
size_t AllocSize;
int maxList = arrayLength; // account for system and shared domains
if (maxList <= 0 || !ClrSafeInt<size_t>::multiply(maxList, sizeof(PVOID), AllocSize))
{
ExtOut("<integer overflow>\n");
return NULL;
}
moduleList = new DWORD_PTR[maxList];
if (moduleList == NULL)
{
ReportOOM();
return NULL;
}
ArrayHolder<char> fileName = new char[MAX_LONGPATH];
// Search all domains to find a module
for (int n = 0; n < adsData.DomainCount+numSpecialDomains; n++)
{
if (IsInterrupt())
{
ExtOut("<interrupted>\n");
goto Failure;
}
DacpAppDomainData appDomain;
if (FAILED(hr = appDomain.Request(g_sos, pArray[n])))
{
// Don't print a failure message here, there is a very normal case when checking
// for modules after clr is loaded but before any AppDomains or assemblies are created
// for example:
// >sxe ld:clr
// >g
// ...
// ModLoad: runtime dll
// >!bpmd Foo.dll Foo.Bar
// we will correctly give the answer that whatever module you were looking for, it isn't loaded yet
ExtDbgOut("DacpAppDomainData.Request FAILED %08x\n", hr);
goto Failure;
}
if (appDomain.AssemblyCount)
{
pAssemblyArray = new CLRDATA_ADDRESS[appDomain.AssemblyCount];
if (pAssemblyArray==NULL)
{
ReportOOM();
goto Failure;
}
if (FAILED(hr = g_sos->GetAssemblyList(appDomain.AppDomainPtr, appDomain.AssemblyCount, pAssemblyArray, NULL)))
{
ExtOut("Unable to get array of Assemblies for the given AppDomain: %08x\n", hr);
goto Failure;
}
for (int nAssem = 0; nAssem < appDomain.AssemblyCount; nAssem ++)
{
if (IsInterrupt())
{
ExtOut("<interrupted>\n");
goto Failure;
}
DacpAssemblyData assemblyData;
if (FAILED(hr = assemblyData.Request(g_sos, pAssemblyArray[nAssem])))
{
ExtOut("Failed to request assembly: %08x\n", hr);
goto Failure;
}
pModules = new CLRDATA_ADDRESS[assemblyData.ModuleCount];
if (FAILED(hr = g_sos->GetAssemblyModuleList(assemblyData.AssemblyPtr, assemblyData.ModuleCount, pModules, NULL)))
{
ExtOut("Failed to get the modules for the given assembly: %08x\n", hr);
goto Failure;
}
for (UINT nModule = 0; nModule < assemblyData.ModuleCount; nModule++)
{
if (IsInterrupt())
{
ExtOut("<interrupted>\n");
goto Failure;
}
CLRDATA_ADDRESS ModuleAddr = pModules[nModule];
DacpModuleData ModuleData;
if (FAILED(hr = ModuleData.Request(g_sos, ModuleAddr)))
{
ExtDbgOut("Failed to request module data from assembly at %p %08x\n", ModuleAddr, hr);
continue;
}
if (mName != NULL)
{
ArrayHolder<WCHAR> moduleName = new WCHAR[MAX_LONGPATH];
FileNameForModule(&ModuleData, moduleName);
int bytesWritten = WideCharToMultiByte(CP_ACP, 0, moduleName, -1, fileName, MAX_LONGPATH, NULL, NULL);
_ASSERTE(bytesWritten > 0);
}
if ((mName == NULL) ||
IsSameModuleName(fileName, mName) ||
DebuggerModuleNamesMatch(ModuleData.PEAssembly, mName) ||
IsFusionLoadedModule(fileName, mName))
{
AddToModuleList(moduleList, *numModule, maxList, (DWORD_PTR)ModuleAddr);
}
}
pModules = NULL;
}
pAssemblyArray = NULL;
}
}
return moduleList;
// We do not want to return a half-constructed list. Instead, we return NULL on a failure.
Failure:
delete [] moduleList;
return NULL;
}
#ifndef FEATURE_PAL
/**********************************************************************\
* Routine Description: *
* *
* Retrieve module base associated with the IXCLRDataModule *
* instance passed in, and the extent type requested. *
* *
\**********************************************************************/
HRESULT GetClrModuleImages(__in IXCLRDataModule* module, __in CLRDataModuleExtentType desiredType, __out PULONG64 pBase, __out PULONG64 pSize)
{
CLRDATA_ENUM enumExtents;
HRESULT hr;
_ASSERTE(pBase != nullptr);
_ASSERTE(pSize != nullptr);
*pBase = 0;
*pSize = 0;
if (FAILED(hr = module->StartEnumExtents(&enumExtents)))
{
return hr;
}
CLRDATA_MODULE_EXTENT extent;
while (module->EnumExtent(&enumExtents, &extent) == S_OK)
{
if ((desiredType == CLRDATA_MODULE_OTHER) || (desiredType == extent.type))
{
ULONG64 moduleBase;
if (FAILED(hr = g_ExtSymbols->GetModuleByOffset(extent.base, 0, nullptr, &moduleBase)))
{
if (desiredType == CLRDATA_MODULE_PE_FILE)
{
*pBase = extent.base;
*pSize = extent.length;
hr = S_OK;
}
break;
}
DEBUG_MODULE_PARAMETERS params;
if (FAILED(hr = g_ExtSymbols->GetModuleParameters(1, &moduleBase, 0, ¶ms)))
{
break;
}
*pBase = moduleBase;
*pSize = params.Size;
hr = S_OK;
break;
}
}
module->EndEnumExtents(enumExtents);
return hr;
}
#endif // FEATURE_PAL
/**********************************************************************\
* Routine Description: *
* *
* Find the IXCLRDataModule instance for the base address. *
* *
\**********************************************************************/
HRESULT GetModuleFromAddress(___in CLRDATA_ADDRESS peAddress, ___out IXCLRDataModule** ppModule)
{
*ppModule = nullptr;
int numModule;
ArrayHolder<DWORD_PTR> moduleList = ModuleFromName(NULL, &numModule);
if (moduleList != nullptr)
{
for (int i = 0; i < numModule; i++)
{
ToRelease<IXCLRDataModule> module;
HRESULT hr = g_sos->GetModule(moduleList[i], &module);
if (FAILED(hr)) {
return hr;
}
ULONG32 flags;
if ((hr = module->GetFlags(&flags)) != S_OK) {
continue;
}
if ((flags & (CLRDATA_MODULE_IS_DYNAMIC | CLRDATA_MODULE_IS_MEMORY_STREAM)) != 0) {
continue;
}
DacpGetModuleData moduleData;
hr = moduleData.Request(module);
if (FAILED(hr)) {
#ifdef FEATURE_PAL
return hr;
#else
hr = GetClrModuleImages(module, CLRDATA_MODULE_PE_FILE, &moduleData.LoadedPEAddress, &moduleData.LoadedPESize);
if (FAILED(hr))
{
return hr;
}
#endif
}
if (peAddress == moduleData.LoadedPEAddress)
{
*ppModule = module.Detach();
return S_OK;
}
}
}
return E_INVALIDARG;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a name. *
* *
\**********************************************************************/
void GetInfoFromName(DWORD_PTR ModulePtr, const char* name, mdTypeDef* retMdTypeDef)
{
DWORD_PTR ignoredModuleInfoRet = NULL;
if (retMdTypeDef)
*retMdTypeDef = 0;
ToRelease<IMetaDataImport> pImport = MDImportForModule (ModulePtr);
if (pImport == 0)
return;
static WCHAR wszName[MAX_CLASSNAME_LENGTH];
size_t n;
size_t length = strlen (name);
for (n = 0; n <= length; n ++)
wszName[n] = name[n];
// First enumerate methods. We're taking advantage of the DAC's
// CLRDataModule::EnumMethodDefinitionByName which can parse
// method names (whether in nested classes, or explicit interface
// method implementations).
ToRelease<IXCLRDataModule> ModuleDefinition;
if (g_sos->GetModule(ModulePtr, &ModuleDefinition) == S_OK)
{
CLRDATA_ENUM h;
if (ModuleDefinition->StartEnumMethodDefinitionsByName(wszName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
BOOL fStatus = FALSE;
while (ModuleDefinition->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
if (fStatus && !retMdTypeDef)
ExtOut("-----------------------\n");
mdTypeDef token;
if (pMeth->GetTokenAndScope(&token, NULL) == S_OK)
{
GetInfoFromModule(ModulePtr, token, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
fStatus = TRUE;
}
pMeth->Release();
}
ModuleDefinition->EndEnumMethodDefinitionsByName(h);
if (fStatus)
return;
}
}
// Now look for types, type members and fields
mdTypeDef cl;
mdToken tkEnclose = mdTokenNil;
WCHAR *pName;
WCHAR *pHead = wszName;
while ( ((pName = _wcschr (pHead,L'+')) != NULL) ||
((pName = _wcschr (pHead,L'/')) != NULL)) {
pName[0] = L'\0';
if (FAILED(pImport->FindTypeDefByName(pHead,tkEnclose,&tkEnclose)))
return;
pHead = pName+1;
}
pName = pHead;
// @todo: Handle Nested classes correctly.
if (SUCCEEDED (pImport->FindTypeDefByName (pName, tkEnclose, &cl)))
{
if (retMdTypeDef)
*retMdTypeDef = cl;
GetInfoFromModule(ModulePtr, cl, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
return;
}
// See if it is a method
WCHAR *pwzMethod;
if ((pwzMethod = _wcsrchr(pName, L'.')) == NULL)
return;
if (pwzMethod[-1] == L'.')
pwzMethod --;
pwzMethod[0] = L'\0';
pwzMethod ++;
// @todo: Handle Nested classes correctly.
if (SUCCEEDED(pImport->FindTypeDefByName (pName, tkEnclose, &cl)))
{
if (retMdTypeDef)
*retMdTypeDef = cl;
mdMethodDef token;
ULONG cTokens;
HCORENUM henum = NULL;
// is Member?
henum = NULL;
if (SUCCEEDED (pImport->EnumMembersWithName (&henum, cl, pwzMethod,
&token, 1, &cTokens))
&& cTokens == 1)
{
if (!retMdTypeDef) ExtOut("Member (mdToken token) of\n");
GetInfoFromModule(ModulePtr, cl, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
return;
}
// is Field?
henum = NULL;
if (SUCCEEDED (pImport->EnumFieldsWithName (&henum, cl, pwzMethod,
&token, 1, &cTokens))
&& cTokens == 1)
{
if (!retMdTypeDef) ExtOut("Field (mdToken token) of\n");
GetInfoFromModule(ModulePtr, cl, retMdTypeDef ? &ignoredModuleInfoRet : NULL);
return;
}
}
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a token. *
* *
\**********************************************************************/
DWORD_PTR GetMethodDescFromModule(DWORD_PTR ModuleAddr, ULONG token)
{
if (TypeFromToken(token) != mdtMethodDef)
return NULL;
CLRDATA_ADDRESS md = 0;
if (FAILED(g_sos->GetMethodDescFromToken(ModuleAddr, token, &md)))
{
return NULL;
}
else if (0 == md)
{
// a NULL ReturnValue means the method desc is not loaded yet
return MD_NOT_YET_LOADED;
}
else if ( !IsMethodDesc((DWORD_PTR)md))
{
return NULL;
}
return (DWORD_PTR)md;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the MethodDefinitions given a name. *
* *
\**********************************************************************/
HRESULT GetMethodDefinitionsFromName(TADDR ModulePtr, IXCLRDataModule* mod, const char *name, IXCLRDataMethodDefinition **ppOut, int numMethods, int *numMethodsNeeded)
{
if (name == NULL)
return E_FAIL;
size_t n;
size_t length = strlen (name);
for (n = 0; n <= length; n ++)
g_mdName[n] = name[n];
CLRDATA_ENUM h;
int methodCount = 0;
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
methodCount++;
pMeth->Release();
}
mod->EndEnumMethodDefinitionsByName(h);
}
if(numMethodsNeeded != NULL)
*numMethodsNeeded = methodCount;
if(ppOut == NULL)
return S_OK;
if(numMethods > methodCount)
numMethods = methodCount;
if (methodCount > 0)
{
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
for (int i = 0; i < numMethods && mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK; i++)
{
ppOut[i] = pMeth;
}
mod->EndEnumMethodDefinitionsByName(h);
}
}
return S_OK;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a name. *
* *
\**********************************************************************/
HRESULT GetMethodDescsFromName(TADDR ModulePtr, IXCLRDataModule* mod, const char *name, DWORD_PTR **pOut,int *numMethods)
{
if (name == NULL || pOut == NULL || numMethods == NULL)
return E_FAIL;
*pOut = NULL;
*numMethods = 0;
size_t n;
size_t length = strlen (name);
for (n = 0; n <= length; n ++)
g_mdName[n] = name[n];
CLRDATA_ENUM h;
int methodCount = 0;
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
IXCLRDataMethodDefinition *pMeth = NULL;
while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
methodCount++;
pMeth->Release();
}
mod->EndEnumMethodDefinitionsByName(h);
}
if (methodCount > 0)
{
*pOut = new TADDR[methodCount];
if (*pOut==NULL)
{
ReportOOM();
return E_OUTOFMEMORY;
}
*numMethods = methodCount;
if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
{
int i = 0;
IXCLRDataMethodDefinition *pMeth = NULL;
while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
{
mdTypeDef token;
if (pMeth->GetTokenAndScope(&token, NULL) != S_OK)
(*pOut)[i] = NULL;
(*pOut)[i] = GetMethodDescFromModule(ModulePtr, token);
if ((*pOut)[i] == NULL)
{
*numMethods = 0;
return E_FAIL;
}
i++;
pMeth->Release();
}
mod->EndEnumMethodDefinitionsByName(h);
}
}
return S_OK;
}
/**********************************************************************\
* Routine Description: *
* *
* Find the EE data given a token. *
* *
\**********************************************************************/
void GetInfoFromModule (DWORD_PTR ModuleAddr, ULONG token, DWORD_PTR *ret)
{
switch (TypeFromToken(token))
{
case mdtMethodDef:
break;
case mdtTypeDef:
break;
case mdtTypeRef:
break;
case mdtFieldDef:
break;
default:
ExtOut("This token type is not supported\n");
return;
break;
}
CLRDATA_ADDRESS md = 0;
if (FAILED(g_sos->GetMethodDescFromToken(ModuleAddr, token, &md)) || !IsValidToken (ModuleAddr, token))
{
ExtOut("<invalid module token>\n");
return;
}
if (ret != NULL)
{
*ret = (DWORD_PTR)md;
return;
}
ExtOut("Token: %p\n", SOS_PTR(token));
switch (TypeFromToken(token))
{
case mdtFieldDef:
{
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
ExtOut("Field name: %S\n", g_mdName);
break;
}
case mdtMethodDef:
{
if (md)
{
DMLOut("MethodDesc: %s\n", DMLMethodDesc(md));
// Easiest to get full parameterized method name from ..::GetMethodName
if (g_sos->GetMethodDescName(md, mdNameLen, g_mdName, NULL) != S_OK)
{
// Fall back to just method name without parameters..
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
}
}
else
{
ExtOut("MethodDesc: <not loaded yet>\n");
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
}
ExtOut("Name: %S\n", g_mdName);
// Nice to have a little more data
if (md)
{
DacpMethodDescData MethodDescData;
if (MethodDescData.Request(g_sos, md) == S_OK)
{
if (MethodDescData.bHasNativeCode)
{
DMLOut("JITTED Code Address: %s\n", DMLIP(MethodDescData.NativeCodeAddr));
}
else
{
#ifndef FEATURE_PAL
if (IsDMLEnabled())
DMLOut("Not JITTED yet. Use <exec cmd=\"!bpmd -md %p\">!bpmd -md %p</exec> to break on run.\n",
SOS_PTR(md), SOS_PTR(md));
else
ExtOut("Not JITTED yet. Use !bpmd -md %p to break on run.\n", SOS_PTR(md));
#else
ExtOut("Not JITTED yet. Use 'bpmd -md %p' to break on run.\n", SOS_PTR(md));
#endif
}
}
else
{
ExtOut ("<Error getting MethodDesc information>\n");
}
}
else
{
ExtOut("Not JITTED yet.\n");
}
break;
}
case mdtTypeDef:
case mdtTypeRef:
{
if (md)
{
DMLOut("MethodTable: %s\n", DMLMethodTable(md));
DacpMethodTableData mtabledata;
if (mtabledata.Request(g_sos, md) == S_OK)
{
DMLOut("EEClass: %s\n", DMLClass(mtabledata.Class));
}
else
{
ExtOut("EEClass: <error getting EEClass>\n");
}
}
else
{
ExtOut("MethodTable: <not loaded yet>\n");
ExtOut("EEClass: <not loaded yet>\n");
}
NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
ExtOut("Name: %S\n", g_mdName);
break;
}
default:
break;
}
return;
}
BOOL IsMTForFreeObj(DWORD_PTR pMT)
{
return (pMT == g_special_usefulGlobals.FreeMethodTable);
}
const char *EHTypeName(EHClauseType et)
{
if (et == EHFault)
return "FAULT";
else if (et == EHFinally)
return "FINALLY";
else if (et == EHFilter)
return "FILTER";
else if (et == EHTyped)
return "TYPED";
else
return "UNKNOWN";
}
// 2.x version
void DumpTieredNativeCodeAddressInfo_2x(struct DacpTieredVersionData_2x * pTieredVersionData, const UINT cTieredVersionData)
{
ExtOut("Code Version History:\n");
for(int i = cTieredVersionData - 1; i >= 0; --i)
{
const char *descriptor = NULL;
switch(pTieredVersionData[i].TieredInfo)
{
case DacpTieredVersionData_2x::TIERED_UNKNOWN:
default:
descriptor = "Unknown Tier";
break;
case DacpTieredVersionData_2x::NON_TIERED:
descriptor = "Non-Tiered";
break;
case DacpTieredVersionData_2x::TIERED_0:
descriptor = "Tier 0";
break;
case DacpTieredVersionData_2x::TIERED_1:
descriptor = "Tier 1";
break;
}
DMLOut(" CodeAddr: %s (%s)\n", DMLIP(pTieredVersionData[i].NativeCodeAddr), descriptor);
ExtOut(" NativeCodeVersion: %p\n", SOS_PTR(pTieredVersionData[i].NativeCodeVersionNodePtr));
}
}
void DumpTieredNativeCodeAddressInfo(struct DacpTieredVersionData * pTieredVersionData, const UINT cTieredVersionData,
ULONG rejitID, CLRDATA_ADDRESS ilAddr, CLRDATA_ADDRESS ilNodeAddr)
{
ExtOut(" ILCodeVersion: %p\n", SOS_PTR(ilNodeAddr));
ExtOut(" ReJIT ID: %d\n", rejitID);
DMLOut(" IL Addr: %s\n", DMLIL(ilAddr));
if (IsRuntimeVersionAtLeast(3)) {
for(int i = cTieredVersionData - 1; i >= 0; --i)
{
const char *descriptor = NULL;
switch(pTieredVersionData[i].OptimizationTier)
{
case DacpTieredVersionData::OptimizationTier_Unknown:
default:
descriptor = "Unknown Tier";
break;
case DacpTieredVersionData::OptimizationTier_MinOptJitted:
descriptor = "MinOptJitted";
break;
case DacpTieredVersionData::OptimizationTier_Optimized:
descriptor = "Optimized";
break;
case DacpTieredVersionData::OptimizationTier_QuickJitted:
descriptor = "QuickJitted";
break;
case DacpTieredVersionData::OptimizationTier_OptimizedTier1:
descriptor = "OptimizedTier1";
break;
case DacpTieredVersionData::OptimizationTier_ReadyToRun:
descriptor = "ReadyToRun";
break;
}
DMLOut(" CodeAddr: %s (%s)\n", DMLIP(pTieredVersionData[i].NativeCodeAddr), descriptor);
ExtOut(" NativeCodeVersion: %p\n", SOS_PTR(pTieredVersionData[i].NativeCodeVersionNodePtr));
}
}
else {
DumpTieredNativeCodeAddressInfo_2x((DacpTieredVersionData_2x*)pTieredVersionData, cTieredVersionData);
}
}
void DumpRejitData(CLRDATA_ADDRESS pMethodDesc, DacpReJitData * pReJitData)
{
int rejitID = (int)pReJitData->rejitID;
CLRDATA_ADDRESS ilAddr = 0;
CLRDATA_ADDRESS ilNodeAddr = 0;
struct DacpReJitData2 rejitData;
ReleaseHolder<ISOSDacInterface7> sos7;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface7), &sos7)) &&
SUCCEEDED(sos7->GetReJITInformation(pMethodDesc,
rejitID,
&rejitData)))
{
ilAddr = rejitData.il;
ilNodeAddr = rejitData.ilCodeVersionNodePtr;
}
struct DacpTieredVersionData codeAddrs[kcMaxTieredVersions];
int cCodeAddrs;
ReleaseHolder<ISOSDacInterface5> sos5;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface5), &sos5)) &&
SUCCEEDED(sos5->GetTieredVersions(pMethodDesc,
rejitID,
codeAddrs,
kcMaxTieredVersions,
&cCodeAddrs)))
{
DumpTieredNativeCodeAddressInfo(codeAddrs, cCodeAddrs, rejitID, ilAddr, ilNodeAddr);
}
}
// For !ip2md requests, this function helps us ensure that rejitted version corresponding
// to the specified IP always gets dumped. It may have already been dumped if it was the
// current rejit version (which is always dumped) or one of the reverted versions that we
// happened to dump before we clipped their number down to kcRejitDataRevertedMax.
BOOL ShouldDumpRejitDataRequested(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData)
{
if (pMethodDescData->rejitDataRequested.rejitID == 0)
return FALSE;
if (pMethodDescData->rejitDataRequested.rejitID == pMethodDescData->rejitDataCurrent.rejitID)
return FALSE;
for (ULONG i=0; i < cRevertedRejitData; i++)
{
if (pMethodDescData->rejitDataRequested.rejitID == pRevertedRejitData[i].rejitID)
return FALSE;
}
return TRUE;
}
void DumpAllRejitDataIfNecessary(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData)
{
// If there's no rejit info to output, then skip
if ((pMethodDescData->rejitDataCurrent.rejitID == 0) &&
(pMethodDescData->rejitDataRequested.rejitID == 0) &&
(cRevertedRejitData == 0))
{
return;
}
// Dump reverted rejit infos
for (ULONG i=0; i < cRevertedRejitData; i++)
{
DumpRejitData(pMethodDescData->MethodDescPtr, &pRevertedRejitData[i]);
}
// For !ip2md, ensure we dump the rejit version corresponding to the specified IP
// (if not already dumped)
if (ShouldDumpRejitDataRequested(pMethodDescData, pRevertedRejitData, cRevertedRejitData))
DumpRejitData(pMethodDescData->MethodDescPtr, &pMethodDescData->rejitDataRequested);
// If we maxed out the reverted versions we dumped, let user know there may be more
if (cRevertedRejitData == kcMaxRevertedRejitData)
ExtOut(" (... possibly more reverted versions ...)\n");
}
void DumpMDInfoFromMethodDescData(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData, BOOL fStackTraceFormat)
{
static WCHAR wszNameBuffer[1024]; // should be large enough
BOOL bFailed = FALSE;
if (g_sos->GetMethodDescName(pMethodDescData->MethodDescPtr, 1024, wszNameBuffer, NULL) != S_OK)
{
wcscpy_s(wszNameBuffer, _countof(wszNameBuffer), W("UNKNOWN"));
bFailed = TRUE;
}
if (!fStackTraceFormat)
{
ExtOut("Method Name: %S\n", wszNameBuffer);
DacpMethodTableData mtdata;
if (SUCCEEDED(mtdata.Request(g_sos, pMethodDescData->MethodTablePtr)))
{
DMLOut("Class: %s\n", DMLClass(mtdata.Class));
}
DMLOut("MethodTable: %s\n", DMLMethodTable(pMethodDescData->MethodTablePtr));
ExtOut("mdToken: %p\n", SOS_PTR(pMethodDescData->MDToken));
DMLOut("Module: %s\n", DMLModule(pMethodDescData->ModulePtr));
ExtOut("IsJitted: %s\n", pMethodDescData->bHasNativeCode ? "yes" : "no");
DMLOut("Current CodeAddr: %s\n", DMLIP(pMethodDescData->NativeCodeAddr));
int rejitID = (int)pMethodDescData->rejitDataCurrent.rejitID;
CLRDATA_ADDRESS ilAddr = 0;
CLRDATA_ADDRESS ilNodeAddr = 0;
ExtOut("Version History:\n");
struct DacpReJitData2 rejitData;
ReleaseHolder<ISOSDacInterface7> sos7;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface7), &sos7)))
{
if SUCCEEDED(sos7->GetReJITInformation(pMethodDescData->MethodDescPtr,
rejitID,
&rejitData))
{
ilAddr = rejitData.il;
ilNodeAddr = rejitData.ilCodeVersionNodePtr;
}
int pendingRejitID;
struct DacpReJitData2 pendingRejitData;
if (sos7->GetPendingReJITID(pMethodDescData->MethodDescPtr, &pendingRejitID) == S_OK &&
SUCCEEDED(sos7->GetReJITInformation(pMethodDescData->MethodDescPtr, pendingRejitID, &pendingRejitData)))
{
// Special case, there is no jitted code yet but still need to output the IL information
ExtOut(" ILCodeVersion: %p (pending)\n", SOS_PTR(pendingRejitData.ilCodeVersionNodePtr));
ExtOut(" ReJIT ID: %d\n", pendingRejitID);
DMLOut(" IL Addr: %s\n", DMLIL(pendingRejitData.il));
}
}
struct DacpTieredVersionData codeAddrs[kcMaxTieredVersions];
int cCodeAddrs;
ReleaseHolder<ISOSDacInterface5> sos5;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface5), &sos5)) &&
SUCCEEDED(sos5->GetTieredVersions(pMethodDescData->MethodDescPtr,
rejitID,
codeAddrs,
kcMaxTieredVersions,
&cCodeAddrs)))
{
DumpTieredNativeCodeAddressInfo(codeAddrs, cCodeAddrs, rejitID, ilAddr, ilNodeAddr);
}
DumpAllRejitDataIfNecessary(pMethodDescData, pRevertedRejitData, cRevertedRejitData);
}
else
{
if (!bFailed)
{
ExtOut("%S", wszNameBuffer);
}
else
{
// Only clutter the display with module/token for cases where we
// can't get the MethodDesc name for some reason.
DMLOut("Unknown MethodDesc (Module %s, mdToken %08x)",
DMLModule(pMethodDescData->ModulePtr),
pMethodDescData->MDToken);
}
}
}
void DumpMDInfo(DWORD_PTR dwMethodDescAddr, CLRDATA_ADDRESS dwRequestedIP /* = 0 */, BOOL fStackTraceFormat /* = FALSE */)
{
DacpMethodDescData MethodDescData;
DacpReJitData revertedRejitData[kcMaxRevertedRejitData];
ULONG cNeededRevertedRejitData;
if (g_sos->GetMethodDescData(
TO_CDADDR(dwMethodDescAddr),
dwRequestedIP,
&MethodDescData,
_countof(revertedRejitData),
revertedRejitData,
&cNeededRevertedRejitData) != S_OK)
{
ExtOut("%p is not a MethodDesc\n", SOS_PTR(dwMethodDescAddr));
return;
}
DumpMDInfoFromMethodDescData(&MethodDescData, revertedRejitData, cNeededRevertedRejitData, fStackTraceFormat);
}
void GetDomainList (DWORD_PTR *&domainList, int &numDomain)
{
DacpAppDomainStoreData adsData;
numDomain = 0;
if (adsData.Request(g_sos)!=S_OK)
{
return;
}
// Do prefast integer checks before the malloc.
size_t AllocSize;
LONG DomainAllocCount;
LONG NumExtraDomains = (adsData.sharedDomain != NULL) ? 2 : 1;
if (!ClrSafeInt<LONG>::addition(adsData.DomainCount, NumExtraDomains, DomainAllocCount) ||
!ClrSafeInt<size_t>::multiply(DomainAllocCount, sizeof(PVOID), AllocSize) ||
(domainList = new DWORD_PTR[DomainAllocCount]) == NULL)
{
return;
}
domainList[numDomain++] = (DWORD_PTR) adsData.systemDomain;
if (adsData.sharedDomain != NULL)
{
domainList[numDomain++] = (DWORD_PTR) adsData.sharedDomain;
}
CLRDATA_ADDRESS *pArray = new CLRDATA_ADDRESS[adsData.DomainCount];
if (pArray==NULL)
{
return;
}
if (g_sos->GetAppDomainList(adsData.DomainCount, pArray, NULL)!=S_OK)
{
delete [] pArray;
return;
}
for (int n=0;n<adsData.DomainCount;n++)
{
if (IsInterrupt())
break;
domainList[numDomain++] = (DWORD_PTR) pArray[n];
}
delete [] pArray;
}
HRESULT GetThreadList(DWORD_PTR **threadList, int *numThread)
{
_ASSERTE(threadList != NULL);
_ASSERTE(numThread != NULL);
if (threadList == NULL || numThread == NULL)
{
return E_FAIL;
}
*numThread = 0;
DacpThreadStoreData ThreadStore;
if ( ThreadStore.Request(g_sos) != S_OK)
{
ExtOut("Failed to request threads from the thread store.");
return E_FAIL;
}
*threadList = new DWORD_PTR[ThreadStore.threadCount];
if (*threadList == NULL)
{
ReportOOM();
return E_OUTOFMEMORY;
}
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread != NULL)
{
if (IsInterrupt())
return S_FALSE;
DacpThreadData Thread;
if (Thread.Request(g_sos, CurThread) != S_OK)
{
ExtOut("Failed to request Thread at %p\n", SOS_PTR(CurThread));
return E_FAIL;
}
(*threadList)[(*numThread)++] = (DWORD_PTR)CurThread;
CurThread = Thread.nextThread;
}
return S_OK;
}
CLRDATA_ADDRESS GetCurrentManagedThread ()
{
DacpThreadStoreData ThreadStore;
ThreadStore.Request(g_sos);
ULONG Tid;
g_ExtSystem->GetCurrentThreadSystemId(&Tid);
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread)
{
DacpThreadData Thread;
if (Thread.Request(g_sos, CurThread) != S_OK)
{
return NULL;
}
if (Thread.osThreadId == Tid)
{
return CurThread;
}
CurThread = Thread.nextThread;
}
return NULL;
}
#define MSCOREE_SHIM_A "mscoree.dll"
void ReloadSymbolWithLineInfo()
{
_ASSERTE(g_pRuntime != nullptr);
#ifndef FEATURE_PAL
static BOOL bLoadSymbol = FALSE;
if (!bLoadSymbol)
{
ULONG Options;
g_ExtSymbols->GetSymbolOptions(&Options);
if (!(Options & SYMOPT_LOAD_LINES))
{
g_ExtSymbols->AddSymbolOptions(SYMOPT_LOAD_LINES);
if (SUCCEEDED(g_ExtSymbols->GetModuleByModuleName(MSCOREE_SHIM_A, 0, NULL, NULL)))
{
g_ExtSymbols->Reload("/f" MSCOREE_SHIM_A);
}
std::string reloadCommand;
reloadCommand.append("/f ");
reloadCommand.append(GetRuntimeDllName());
g_ExtSymbols->Reload(reloadCommand.c_str());
}
// reload mscoree.pdb and clrjit.pdb to get line info
bLoadSymbol = TRUE;
}
#endif
}
// Return 1 if the function is our stub
// Return MethodDesc if the function is managed
// Otherwise return 0
size_t FunctionType (size_t EIP)
{
ULONG64 base = 0;
ULONG ulLoaded, ulUnloaded, ulIndex;
// Get the number of loaded and unloaded modules
if (FAILED(g_ExtSymbols->GetNumberModules(&ulLoaded, &ulUnloaded)))
return 0;
if (SUCCEEDED(g_ExtSymbols->GetModuleByOffset(TO_CDADDR(EIP), 0, &ulIndex, &base)) && base != 0)
{
if (ulIndex < ulLoaded)
{
IMAGE_DOS_HEADER DosHeader;
if (g_ExtData->ReadVirtual(TO_CDADDR(base), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
return 0;
IMAGE_NT_HEADERS Header;
if (g_ExtData->ReadVirtual(TO_CDADDR(base + DosHeader.e_lfanew), &Header, sizeof(Header), NULL) != S_OK)
return 0;
// If there is no COMHeader, this can not be managed code.
if (Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress == 0)
return 0;
IMAGE_COR20_HEADER ComPlusHeader;
if (g_ExtData->ReadVirtual(TO_CDADDR(base + Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress),
&ComPlusHeader, sizeof(ComPlusHeader), NULL) != S_OK)
return 0;
// If there is no Precompiled image info, it can not be prejit code
if (ComPlusHeader.ManagedNativeHeader.VirtualAddress == 0) {
return 0;
}
}
}
CLRDATA_ADDRESS dwStartAddr = TO_CDADDR(EIP);
CLRDATA_ADDRESS pMD;
if (g_sos->GetMethodDescPtrFromIP(dwStartAddr, &pMD) != S_OK)
{
return 1;
}
return (size_t) pMD;
}
//
// Return true if major runtime version (logical product version like 2.1,
// 3.0 or 5.x). Currently only major versions of 3 or 5 are supported.
//
bool IsRuntimeVersion(DWORD major)
{
VS_FIXEDFILEINFO fileInfo;
if (SUCCEEDED(g_pRuntime->GetEEVersion(&fileInfo, nullptr, 0)))
{
return IsRuntimeVersion(fileInfo, major);
}
return false;
}
bool IsRuntimeVersion(VS_FIXEDFILEINFO& fileInfo, DWORD major)
{
switch (major)
{
case 5:
return HIWORD(fileInfo.dwFileVersionMS) == 5;
case 3:
return HIWORD(fileInfo.dwFileVersionMS) == 4 && LOWORD(fileInfo.dwFileVersionMS) == 700;
default:
_ASSERTE(FALSE);
break;
}
return false;
}
bool IsRuntimeVersionAtLeast(DWORD major)
{
VS_FIXEDFILEINFO fileInfo;
if (SUCCEEDED(g_pRuntime->GetEEVersion(&fileInfo, nullptr, 0)))
{
return IsRuntimeVersionAtLeast(fileInfo, major);
}
return false;
}
bool IsRuntimeVersionAtLeast(VS_FIXEDFILEINFO& fileInfo, DWORD major)
{
switch (major)
{
case 3:
if (HIWORD(fileInfo.dwFileVersionMS) == 4 && LOWORD(fileInfo.dwFileVersionMS) == 700)
{
return true;
}
// fall through
case 5:
if (HIWORD(fileInfo.dwFileVersionMS) >= 5)
{
return true;
}
// fall through
break;
default:
_ASSERTE(FALSE);
break;
}
return false;
}
// Returns true if there is a change in the data structures that SOS depends on like
// stress log structs (StressMsg, StressLogChunck, ThreadStressLog, etc), exception
// stack traces (StackTraceElement), the PredefinedTlsSlots enums, etc.
bool CheckBreakingRuntimeChange(int* pVersion)
{
bool result = false;
// Assume version 1 if no ISOSDacInterface9 (runtimes < 5.0)
int version = 1;
if (g_sos != nullptr)
{
ReleaseHolder<ISOSDacInterface9> sos9;
if (SUCCEEDED(g_sos->QueryInterface(__uuidof(ISOSDacInterface9), &sos9)))
{
if (SUCCEEDED(sos9->GetBreakingChangeVersion(&version)))
{
if (version > SOS_BREAKING_CHANGE_VERSION)
{
ExtWarn("WARNING: SOS needs to be upgraded for this version of the runtime. Some commands may not work correctly.\n");
ExtWarn("For more information see https://go.microsoft.com/fwlink/?linkid=2135652\n");
ExtWarn("\n");
result = true;
}
}
}
}
if (pVersion != nullptr)
{
*pVersion = version;
}
return result;
}
#ifndef FEATURE_PAL
BOOL GetSOSVersion(VS_FIXEDFILEINFO *pFileInfo)
{
_ASSERTE(pFileInfo);
WCHAR wszFullPath[MAX_LONGPATH];
DWORD cchFullPath = GetModuleFileNameW(g_hInstance, wszFullPath, _countof(wszFullPath));
DWORD dwHandle = 0;
DWORD infoSize = GetFileVersionInfoSizeW(wszFullPath, &dwHandle);
if (infoSize)
{
ArrayHolder<BYTE> pVersionInfo = new BYTE[infoSize];
if (pVersionInfo)
{
if (GetFileVersionInfoW(wszFullPath, NULL, infoSize, pVersionInfo))
{
VS_FIXEDFILEINFO *pTmpFileInfo = NULL;
UINT uLen = 0;
if (VerQueryValueA(pVersionInfo, "\\", (LPVOID *) &pTmpFileInfo, &uLen))
{
if (pFileInfo->dwFileVersionMS == (DWORD)-1) {
return FALSE;
}
*pFileInfo = *pTmpFileInfo; // Copy the info
return TRUE;
}
}
}
}
return FALSE;
}
#endif // !FEATURE_PAL
size_t ObjectSize(DWORD_PTR obj,BOOL fIsLargeObject)
{
DWORD_PTR dwMT;
MOVE(dwMT, obj);
return ObjectSize(obj, dwMT, FALSE, fIsLargeObject);
}
size_t ObjectSize(DWORD_PTR obj, DWORD_PTR mt, BOOL fIsValueClass, BOOL fIsLargeObject)
{
BOOL bContainsPointers;
size_t size = 0;
if (!GetSizeEfficient(obj, mt, fIsLargeObject, size, bContainsPointers))
{
return 0;
}
return size;
}
// This takes an array of values and sets every non-printable character
// to be a period.
void Flatten(__out_ecount(len) char *data, unsigned int len)
{
for (unsigned int i = 0; i < len; ++i)
if (data[i] < 32 || data[i] > 126)
data[i] = '.';
data[len] = 0;
}
void CharArrayContent(TADDR pos, ULONG num, bool widechar)
{
if (!pos || num <= 0)
return;
if (widechar)
{
ArrayHolder<WCHAR> data = new WCHAR[num+1];
if (!data)
{
ReportOOM();
return;
}
ULONG readLen = 0;
if (!SafeReadMemory(pos, data, num<<1, &readLen))
return;
Flatten(data.GetPtr(), readLen >> 1);
ExtOut("%S", data.GetPtr());
}
else
{
ArrayHolder<char> data = new char[num+1];
if (!data)
{
ReportOOM();
return;
}
ULONG readLen = 0;
if (!SafeReadMemory(pos, data, num, &readLen))
return;
_ASSERTE(readLen <= num);
Flatten(data, readLen);
ExtOut("%s", data.GetPtr());
}
}
void StringObjectContent(size_t obj, BOOL fLiteral, const int length)
{
DacpObjectData objData;
if (objData.Request(g_sos, TO_CDADDR(obj))!=S_OK)
{
ExtOut("<Invalid Object>");
return;
}
strobjInfo stInfo { 0, 0 };
if (MOVE(stInfo, obj) != S_OK)
{
ExtOut ("Error getting string data\n");
return;
}
if (objData.Size > 0x200000 || stInfo.m_StringLength > 0x200000)
{
ExtOut ("<String is invalid or too large to print>\n");
return;
}
ArrayHolder<WCHAR> pwszBuf = new WCHAR[stInfo.m_StringLength+1];
if (pwszBuf == NULL)
{
return;
}
DWORD_PTR dwAddr = (DWORD_PTR)pwszBuf.GetPtr();
if (g_sos->GetObjectStringData(TO_CDADDR(obj), stInfo.m_StringLength+1, pwszBuf, NULL)!=S_OK)
{
ExtOut("<Invalid Object>");
return;
}
if (!fLiteral)
{
pwszBuf[stInfo.m_StringLength] = L'\0';
ExtOut ("%S", pwszBuf.GetPtr());
}
else
{
ULONG32 count = stInfo.m_StringLength;
WCHAR buffer[256];
WCHAR out[512];
while (count)
{
DWORD toRead = 255;
if (count < toRead)
toRead = count;
ULONG bytesRead;
wcsncpy_s(buffer,_countof(buffer),(LPWSTR) dwAddr, toRead);
bytesRead = toRead*sizeof(WCHAR);
DWORD wcharsRead = bytesRead/2;
buffer[wcharsRead] = L'\0';
ULONG j,k=0;
for (j = 0; j < wcharsRead; j ++)
{
if (_iswprint (buffer[j])) {
out[k] = buffer[j];
k ++;
}
else
{
out[k++] = L'\\';
switch (buffer[j]) {
case L'\n':
out[k++] = L'n';
break;
case L'\0':
out[k++] = L'0';
break;
case L'\t':
out[k++] = L't';
break;
case L'\v':
out[k++] = L'v';
break;
case L'\b':
out[k++] = L'b';
break;
case L'\r':
out[k++] = L'r';
break;
case L'\f':
out[k++] = L'f';
break;
case L'\a':
out[k++] = L'a';
break;
case L'\\':
break;
case L'\?':
out[k++] = L'?';
break;
default:
out[k++] = L'?';
break;
}
}
}
out[k] = L'\0';
ExtOut ("%S", out);
count -= wcharsRead;
dwAddr += bytesRead;
}
}
}
#ifdef _TARGET_WIN64_
#include <limits.h>
__int64 str64hex(const char *ptr)
{
__int64 value = 0;
unsigned char nCount = 0;
if(ptr==NULL)
return 0;
// Ignore leading 0x if present
if (*ptr=='0' && toupper(*(ptr+1))=='X') {
ptr = ptr + 2;
}
while (1) {
char digit;
if (isdigit(*ptr)) {
digit = *ptr - '0';
} else if (isalpha(*ptr)) {
digit = (((char)toupper(*ptr)) - 'A') + 10;
if (digit >= 16) {
break; // terminate
}
} else {
break;
}
if (nCount>15) {
return _UI64_MAX; // would be an overflow
}
value = value << 4;
value |= digit;
ptr++;
nCount++;
}
return value;
}
#endif // _TARGET_WIN64_
BOOL GetValueForCMD (const char *ptr, const char *end, ARGTYPE type, size_t *value)
{
if (type == COSTRING) {
// Allocate memory for the length of the string. Whitespace terminates
// User must free the string data.
char *pszValue = NULL;
size_t dwSize = (end - ptr);
pszValue= new char[dwSize+1];
if (pszValue == NULL)
{
return FALSE;
}
strncpy_s(pszValue,dwSize+1,ptr,dwSize); // _TRUNCATE
*value = (size_t) pszValue;
} else {
char *last;
if (type == COHEX) {
#ifdef _TARGET_WIN64_
*value = str64hex(ptr);
#else
*value = strtoul(ptr,&last,16);
#endif
}
else {
#ifdef _TARGET_WIN64_
*value = _atoi64(ptr);
#else
*value = strtoul(ptr,&last,10);
#endif
}
#ifdef _TARGET_WIN64_
last = (char *) ptr;
// Ignore leading 0x if present
if (*last=='0' && toupper(*(last+1))=='X') {
last = last + 2;
}
while (isdigit(*last) || (toupper(*last)>='A' && toupper(*last)<='F')) {
last++;
}
#endif
if (last != end) {
return FALSE;
}
}
return TRUE;
}
void SetValueForCMD (void *vptr, ARGTYPE type, size_t value)
{
switch (type) {
case COBOOL:
*(BOOL*)vptr = (BOOL) value;
break;
case COSIZE_T:
case COSTRING:
case COHEX:
*(SIZE_T*)vptr = value;
break;
}
}
BOOL GetCMDOption(const char *string, CMDOption *option, size_t nOption,
CMDValue *arg, size_t maxArg, size_t *nArg)
{
const char *end;
const char *ptr = string;
BOOL endofOption = FALSE;
for (size_t n = 0; n < nOption; n ++)
{
if (IsInterrupt())
return FALSE;
option[n].hasSeen = FALSE;
}
if (nArg) {
*nArg = 0;
}
while (ptr[0] != '\0')
{
if (IsInterrupt())
return FALSE;
// skip any space
if (isspace (ptr[0])) {
while (isspace (ptr[0]))
{
if (IsInterrupt())
return FALSE;
ptr ++;
}
continue;
}
end = ptr;
// Arguments can be quoted with ". We'll remove the quotes and
// allow spaces to exist in the string.
BOOL bQuotedArg = FALSE;
if (ptr[0] == '\'' && ptr[1] != '-')
{
bQuotedArg = TRUE;
// skip quote
ptr++;
end++;
while (end[0] != '\'' && end[0] != '\0')
{
if (IsInterrupt())
return FALSE;
end ++;
}
if (end[0] != '\'')
{
// Error, th ere was a start quote but no end quote
ExtOut ("Missing quote in %s\n", ptr);
return FALSE;
}
}
else // whitespace terminates
{
while (!isspace(end[0]) && end[0] != '\0')
{
if (IsInterrupt())
return FALSE;
end ++;
}
}
#ifndef FEATURE_PAL
if (ptr[0] != '-' && ptr[0] != '/') {
#else
if (ptr[0] != '-') {
#endif
if (maxArg == 0) {
ExtOut ("Incorrect argument: %s\n", ptr);
return FALSE;
}
endofOption = TRUE;
if (*nArg >= maxArg) {
ExtOut ("Incorrect argument: %s\n", ptr);
return FALSE;
}
size_t value;
if (!GetValueForCMD (ptr,end,arg[*nArg].type,&value)) {
char oldChar = *end;
*(char *)end = '\0';
value = (size_t)GetExpression (ptr);
*(char *)end = oldChar;
/*
It is silly to do this, what if 0 is a valid expression for
the command?
if (value == 0) {
ExtOut ("Invalid argument: %s\n", ptr);
return FALSE;
}
*/
}
SetValueForCMD (arg[*nArg].vptr, arg[*nArg].type, value);
(*nArg) ++;
}
else if (endofOption) {
ExtOut ("Wrong option: %s\n", ptr);
return FALSE;
}
else {
char buffer[80];
if (end-ptr > 79) {
ExtOut ("Invalid option %s\n", ptr);
return FALSE;
}
strncpy_s (buffer,_countof(buffer), ptr, end-ptr);
size_t n;
for (n = 0; n < nOption; n ++)
{
if (IsInterrupt())
return FALSE;
if (_stricmp (buffer, option[n].name) == 0) {
if (option[n].hasSeen) {
ExtOut ("Invalid option: option specified multiple times: %s\n", buffer);
return FALSE;
}
option[n].hasSeen = TRUE;
if (option[n].hasValue) {
// skip any space
ptr = end;
if (isspace (ptr[0])) {
while (isspace (ptr[0]))
{
if (IsInterrupt())
return FALSE;
ptr ++;
}
}
if (ptr[0] == '\0') {
ExtOut ("Missing value for option %s\n", buffer);
return FALSE;
}
end = ptr;
while (!isspace(end[0]) && end[0] != '\0')
{
if (IsInterrupt())
return FALSE;
end ++;
}
size_t value;
if (!GetValueForCMD (ptr,end,option[n].type,&value)) {
char oldChar = *end;
*(char *)end = '\0';
value = (size_t)GetExpression (ptr);
*(char *)end = oldChar;
}
SetValueForCMD (option[n].vptr,option[n].type,value);
}
else {
SetValueForCMD (option[n].vptr,option[n].type,TRUE);
}
break;
}
}
if (n == nOption) {
ExtOut ("Unknown option: %s\n", buffer);
return FALSE;
}
}
ptr = end;
if (bQuotedArg)
{
ptr++;
}
}
return TRUE;
}
ReadVirtualCache g_special_rvCacheSpace;
ReadVirtualCache *rvCache = &g_special_rvCacheSpace;
void ResetGlobals(void)
{
// There are some globals used in SOS that exist for efficiency in one command,
// but should be reset because the next execution of an SOS command could be on
// another managed process. Reset them to a default state here, as this command
// is called on every SOS entry point.
g_sos->GetUsefulGlobals(&g_special_usefulGlobals);
g_special_mtCache.Clear();
g_special_rvCacheSpace.Clear();
Output::ResetIndent();
}
//---------------------------------------------------------------------------------------
//
// Loads private DAC interface, and points g_clrData to it.
//
// Return Value:
// HRESULT indicating success or failure
//
HRESULT LoadClrDebugDll(void)
{
_ASSERTE(g_pRuntime != nullptr);
HRESULT hr = g_pRuntime->GetClrDataProcess(&g_clrData);
if (FAILED(hr))
{
#ifdef FEATURE_PAL
return hr;
#else
// Fail if ExtensionApis wasn't initialized because we are hosted under dotnet-dump
if (Ioctl == nullptr) {
return hr;
}
// Try getting the DAC interface from dbgeng if the above fails on Windows
WDBGEXTS_CLR_DATA_INTERFACE Query;
Query.Iid = &__uuidof(IXCLRDataProcess);
if (!Ioctl(IG_GET_CLR_DATA_INTERFACE, &Query, sizeof(Query))) {
return hr;
}
g_clrData = (IXCLRDataProcess*)Query.Iface;
g_clrData->Flush();
#endif
}
else
{
g_clrData->AddRef();
g_clrData->Flush();
}
hr = g_clrData->QueryInterface(__uuidof(ISOSDacInterface), (void**)&g_sos);
if (FAILED(hr))
{
g_sos = NULL;
return hr;
}
return S_OK;
}
/// <summary>
/// Loads the runtime module symbols for the commands like dumplog that
/// lookup runtime symbols. This is done on-demand because it takes a
/// long time under windbg/cdb and not needed for most commands.
/// </summary>
void LoadRuntimeSymbols()
{
_ASSERTE(g_pRuntime != nullptr);
#ifndef FEATURE_PAL
ULONG64 moduleAddress = g_pRuntime->GetModuleAddress();
DEBUG_MODULE_PARAMETERS params;
HRESULT hr = g_ExtSymbols->GetModuleParameters(1, &moduleAddress, 0, ¶ms);
if (SUCCEEDED(hr))
{
if (params.SymbolType == SymDeferred)
{
PCSTR runtimeDllName = ::GetRuntimeDllName();
std::string reloadCommand;
reloadCommand.append("/f ");
reloadCommand.append(runtimeDllName);
g_ExtSymbols->Reload(reloadCommand.c_str());
g_ExtSymbols->GetModuleParameters(1, &moduleAddress, 0, ¶ms);
if (params.SymbolType != SymPdb && params.SymbolType != SymDia)
{
ExtOut("Symbols for %s not loaded. Some SOS commands may not work.\n", runtimeDllName);
}
}
}
#endif
}
typedef enum
{
GC_HEAP_INVALID = 0,
GC_HEAP_WKS = 1,
GC_HEAP_SVR = 2
} GC_HEAP_TYPE;
/**********************************************************************\
* Routine Description: *
* *
* This function is called to find out if runtime is server build *
* *
\**********************************************************************/
DacpGcHeapData *g_pHeapData = NULL;
DacpGcHeapData g_HeapData;
BOOL InitializeHeapData()
{
if (g_pHeapData == NULL)
{
if (g_HeapData.Request(g_sos) != S_OK)
{
return FALSE;
}
g_pHeapData = &g_HeapData;
}
return TRUE;
}
BOOL IsServerBuild()
{
return InitializeHeapData() ? g_pHeapData->bServerMode : FALSE;
}
UINT GetMaxGeneration()
{
return InitializeHeapData() ? g_pHeapData->g_max_generation : 0;
}
UINT GetGcHeapCount()
{
return InitializeHeapData() ? g_pHeapData->HeapCount : 0;
}
BOOL GetGcStructuresValid()
{
// We don't want to use the cached HeapData, because this can change
// each time the program runs for a while.
DacpGcHeapData heapData;
HRESULT hr;
if ((hr = heapData.Request(g_sos)) != S_OK)
{
ExtOut("GetGcStructuresValid: request heap data FAILED %08x\n", hr);
return FALSE;
}
return heapData.bGcStructuresValid;
}
void GetAllocContextPtrs(AllocInfo *pallocInfo)
{
// gets the allocation contexts for all threads. This provides information about how much of
// the current allocation quantum has been allocated and the heap to which the quantum belongs.
// The allocation quantum is a fixed size chunk of zeroed memory from which allocations will come
// until it's filled. Each managed thread has its own allocation context.
pallocInfo->num = 0;
pallocInfo->array = NULL;
// get the thread store (See code:ClrDataAccess::RequestThreadStoreData for details)
DacpThreadStoreData ThreadStore;
if ( ThreadStore.Request(g_sos) != S_OK)
{
return;
}
int numThread = ThreadStore.threadCount;
if (numThread)
{
pallocInfo->array = new needed_alloc_context[numThread];
if (pallocInfo->array == NULL)
{
return;
}
}
// get details for each thread in the thread store
CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
while (CurThread != NULL)
{
if (IsInterrupt())
return;
DacpThreadData Thread;
// Get information about the thread (we're getting the values of several of the
// fields of the Thread instance from the target) See code:ClrDataAccess::RequestThreadData for
// details
if (Thread.Request(g_sos, CurThread) != S_OK)
{
return;
}
if (Thread.allocContextPtr != 0)
{
// get a list of all the allocation contexts
int j;
for (j = 0; j < pallocInfo->num; j ++)
{
if (pallocInfo->array[j].alloc_ptr == (BYTE *) Thread.allocContextPtr)
break;
}
if (j == pallocInfo->num)
{
pallocInfo->num ++;
pallocInfo->array[j].alloc_ptr = (BYTE *) Thread.allocContextPtr;
pallocInfo->array[j].alloc_limit = (BYTE *) Thread.allocContextLimit;
}
}
CurThread = Thread.nextThread;
}
}
HRESULT ReadVirtualCache::Read(TADDR address, PVOID buffer, ULONG bufferSize, PULONG lpcbBytesRead)
{
// address can be any random ULONG64, as it can come from VerifyObjectMember(), and this
// can pass random pointer values in case of GC heap corruption
if (bufferSize == 0)
return S_OK;
if (bufferSize > CACHE_SIZE)
{
// Don't even try with the cache
return g_ExtData->ReadVirtual(TO_CDADDR(address), buffer, bufferSize, lpcbBytesRead);
}
if (!m_cacheValid || (address < m_startCache) || (address > (m_startCache + m_cacheSize - bufferSize)))
{
ULONG cbBytesRead = 0;
m_cacheValid = FALSE;
m_startCache = address;
// Avoid an int overflow
if (m_startCache + CACHE_SIZE < m_startCache)
m_startCache = (TADDR)(-CACHE_SIZE);
HRESULT hr = g_ExtData->ReadVirtual(TO_CDADDR(m_startCache), m_cache, CACHE_SIZE, &cbBytesRead);
if (hr != S_OK)
{
return hr;
}
m_cacheSize = cbBytesRead;
m_cacheValid = TRUE;
}
// If the address is within the cache, copy the cached memory to the input buffer
LONG_PTR cacheOffset = address - m_startCache;
if (cacheOffset >= 0 && cacheOffset < CACHE_SIZE)
{
int size = _min(bufferSize, m_cacheSize);
memcpy(buffer, (LPVOID)(m_cache + cacheOffset), size);
if (lpcbBytesRead != NULL)
{
*lpcbBytesRead = size;
}
}
else
{
return E_FAIL;
}
return S_OK;
}
HRESULT GetMTOfObject(TADDR obj, TADDR *mt)
{
if (!mt)
return E_POINTER;
// Read the MethodTable and if we succeed, get rid of the mark bits.
HRESULT hr = rvCache->Read(obj, mt, sizeof(TADDR), NULL);
if (SUCCEEDED(hr))
*mt &= ~3;
return hr;
}
#ifndef FEATURE_PAL
StressLogMem::~StressLogMem ()
{
MemRange * range = list;
while (range)
{
MemRange * temp = range->next;
delete range;
range = temp;
}
}
bool StressLogMem::Init (ULONG64 stressLogAddr, IDebugDataSpaces* memCallBack)
{
size_t ThreadStressLogAddr = NULL;
HRESULT hr = memCallBack->ReadVirtual(UL64_TO_CDA(stressLogAddr + offsetof (StressLog, logs)),
&ThreadStressLogAddr, sizeof (ThreadStressLogAddr), 0);
if (hr != S_OK)
{
return false;
}
while(ThreadStressLogAddr != NULL)
{
size_t ChunkListHeadAddr = NULL;
hr = memCallBack->ReadVirtual(TO_CDADDR(ThreadStressLogAddr + ThreadStressLog::OffsetOfListHead ()),
&ChunkListHeadAddr, sizeof (ChunkListHeadAddr), 0);
if (hr != S_OK || ChunkListHeadAddr == NULL)
{
return false;
}
size_t StressLogChunkAddr = ChunkListHeadAddr;
do
{
AddRange (StressLogChunkAddr, sizeof (StressLogChunk));
hr = memCallBack->ReadVirtual(TO_CDADDR(StressLogChunkAddr + offsetof (StressLogChunk, next)),
&StressLogChunkAddr, sizeof (StressLogChunkAddr), 0);
if (hr != S_OK)
{
return false;
}
if (StressLogChunkAddr == NULL)
{
return true;
}
} while (StressLogChunkAddr != ChunkListHeadAddr);
hr = memCallBack->ReadVirtual(TO_CDADDR(ThreadStressLogAddr + ThreadStressLog::OffsetOfNext ()),
&ThreadStressLogAddr, sizeof (ThreadStressLogAddr), 0);
if (hr != S_OK)
{
return false;
}
}
return true;
}
bool StressLogMem::IsInStressLog (ULONG64 addr)
{
MemRange * range = list;
while (range)
{
if (range->InRange (addr))
return true;
range = range->next;
}
return false;
}
#endif // !FEATURE_PAL
unsigned int Output::g_bSuppressOutput = 0;
unsigned int Output::g_Indent = 0;
bool Output::g_bDbgOutput = false;
bool Output::g_bDMLExposed = false;
unsigned int Output::g_DMLEnable = 0;
template <class T, int count, int size> const int StaticData<T, count, size>::Count = count;
template <class T, int count, int size> const int StaticData<T, count, size>::Size = size;
StaticData<char, 4, 1024> CachedString::cache;
CachedString::CachedString()
: mPtr(0), mRefCount(0), mIndex(~0), mSize(cache.Size)
{
Create();
}
CachedString::CachedString(const CachedString &rhs)
: mPtr(0), mRefCount(0), mIndex(~0), mSize(cache.Size)
{
Copy(rhs);
}
CachedString::~CachedString()
{
Clear();
}
const CachedString &CachedString::operator=(const CachedString &rhs)
{
Clear();
Copy(rhs);
return *this;
}
void CachedString::Copy(const CachedString &rhs)
{
if (rhs.IsOOM())
{
SetOOM();
}
else
{
mPtr = rhs.mPtr;
mIndex = rhs.mIndex;
mSize = rhs.mSize;
if (rhs.mRefCount)
{
mRefCount = rhs.mRefCount;
(*mRefCount)++;
}
else
{
// We only create count the first time we copy it, so
// we initialize it to 2.
mRefCount = rhs.mRefCount = new unsigned int(2);
if (!mRefCount)
SetOOM();
}
}
}
void CachedString::Clear()
{
if (!mRefCount || --*mRefCount == 0)
{
if (mIndex == -1)
{
if (mPtr)
delete [] mPtr;
}
else if (mIndex >= 0 && mIndex < cache.Count)
{
cache.InUse[mIndex] = false;
}
if (mRefCount)
delete mRefCount;
}
mPtr = 0;
mIndex = ~0;
mRefCount = 0;
mSize = cache.Size;
}
void CachedString::Create()
{
mIndex = -1;
mRefCount = 0;
// First try to find a string in the cache to use.
for (int i = 0; i < cache.Count; ++i)
if (!cache.InUse[i])
{
cache.InUse[i] = true;
mPtr = cache.Data[i];
mIndex = i;
break;
}
// We did not find a string to use, so we'll create a new one.
if (mIndex == -1)
{
mPtr = new char[cache.Size];
if (!mPtr)
SetOOM();
}
}
void CachedString::SetOOM()
{
Clear();
mIndex = -2;
}
void CachedString::Allocate(int size)
{
Clear();
mPtr = new char[size];
if (mPtr)
{
mSize = size;
mIndex = -1;
}
else
{
SetOOM();
}
}
size_t CountHexCharacters(CLRDATA_ADDRESS val)
{
size_t ret = 0;
while (val)
{
val >>= 4;
ret++;
}
return ret;
}
// SOS is single threaded so a global buffer doesn't need any locking
char g_printBuffer[8192];
//---------------------------------------------------------------------
// Because debuggers and hosts SOS runs on now output formatting always
// happens with the C++ runtime functions and not dbgeng. This means
// the special dbgeng formatting charaters are not supported: %N, %I,
// %ma, %mu, %msa, %msu, %y, %ly and %p takes an architecture size
// pointer (size_t) instead of always a 64bit one.
//---------------------------------------------------------------------
HRESULT
OutputVaList(
ULONG mask,
PCSTR format,
va_list args)
{
int length = _vsnprintf_s((char* const)&g_printBuffer, sizeof(g_printBuffer), _TRUNCATE, format, args);
if (length > 0)
{
return g_ExtControl->OutputVaList(mask, (char* const)&g_printBuffer, args);
}
return E_FAIL;
}
HRESULT
ControlledOutputVaList(
ULONG outputControl,
ULONG mask,
PCSTR format,
va_list args)
{
int length = _vsnprintf_s((char* const)&g_printBuffer, sizeof(g_printBuffer), _TRUNCATE, format, args);
if (length > 0)
{
return g_ExtControl->ControlledOutputVaList(outputControl, mask, (char* const)&g_printBuffer, args);
}
return E_FAIL;
}
HRESULT
OutputText(
ULONG mask,
PCSTR format,
...)
{
va_list args;
va_start (args, format);
HRESULT result = OutputVaList(mask, format, args);
va_end (args);
return result;
}
void WhitespaceOut(int count)
{
static const int FixedIndentWidth = 0x40;
static const char FixedIndentString[FixedIndentWidth+1] =
" ";
if (count <= 0)
return;
int mod = count & 0x3F;
count &= ~0x3F;
if (mod > 0)
OutputText(DEBUG_OUTPUT_NORMAL, "%.*s", mod, FixedIndentString);
for ( ; count > 0; count -= FixedIndentWidth)
OutputText(DEBUG_OUTPUT_NORMAL, FixedIndentString);
}
void DMLOut(PCSTR format, ...)
{
if (Output::IsOutputSuppressed())
return;
va_list args;
va_start(args, format);
ExtOutIndent();
if (IsDMLEnabled() && !Output::IsDMLExposed())
{
ControlledOutputVaList(DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL, format, args);
}
else
{
OutputVaList(DEBUG_OUTPUT_NORMAL, format, args);
}
va_end(args);
}
void IfDMLOut(PCSTR format, ...)
{
if (Output::IsOutputSuppressed() || !IsDMLEnabled())
return;
va_list args;
va_start(args, format);
ExtOutIndent();
g_ExtControl->ControlledOutputVaList(DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL, format, args);
va_end(args);
}
void ExtOut(PCSTR Format, ...)
{
if (Output::IsOutputSuppressed())
return;
va_list Args;
va_start(Args, Format);
ExtOutIndent();
OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
va_end(Args);
}
void ExtWarn(PCSTR Format, ...)
{
if (Output::IsOutputSuppressed())
return;
va_list Args;
va_start(Args, Format);
OutputVaList(DEBUG_OUTPUT_WARNING, Format, Args);
va_end(Args);
}
void ExtErr(PCSTR Format, ...)
{
va_list Args;
va_start(Args, Format);
OutputVaList(DEBUG_OUTPUT_ERROR, Format, Args);
va_end(Args);
}
/// <summary>
/// Internal trace output for extensions library
/// </summary>
void TraceError(PCSTR format, ...)
{
if (Output::g_bDbgOutput)
{
va_list args;
va_start(args, format);
OutputVaList(DEBUG_OUTPUT_ERROR, format, args);
va_end(args);
}
}
void ExtDbgOut(PCSTR Format, ...)
{
if (Output::g_bDbgOutput)
{
va_list Args;
va_start(Args, Format);
ExtOutIndent();
OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
va_end(Args);
}
}
const char * const DMLFormats[] =
{
NULL, // DML_None (do not use)
"<exec cmd=\"!DumpMT /d %s\">%s</exec>", // DML_MethodTable
"<exec cmd=\"!DumpMD /d %s\">%s</exec>", // DML_MethodDesc
"<exec cmd=\"!DumpClass /d %s\">%s</exec>", // DML_EEClass
"<exec cmd=\"!DumpModule /d %s\">%s</exec>", // DML_Module
"<exec cmd=\"!U /d %s\">%s</exec>", // DML_IP
"<exec cmd=\"!DumpObj /d %s\">%s</exec>", // DML_Object
"<exec cmd=\"!DumpDomain /d %s\">%s</exec>", // DML_Domain
"<exec cmd=\"!DumpAssembly /d %s\">%s</exec>", // DML_Assembly
"<exec cmd=\"~~[%s]s\">%s</exec>", // DML_ThreadID
"<exec cmd=\"!DumpVC /d %s %s\">%s</exec>", // DML_ValueClass
"<exec cmd=\"!DumpHeap /d -mt %s\">%s</exec>", // DML_DumpHeapMT
"<exec cmd=\"!ListNearObj /d %s\">%s</exec>", // DML_ListNearObj
"<exec cmd=\"!ThreadState %s\">%s</exec>", // DML_ThreadState
"<exec cmd=\"!PrintException /d %s\">%s</exec>",// DML_PrintException
"<exec cmd=\"!DumpRCW /d %s\">%s</exec>", // DML_RCWrapper
"<exec cmd=\"!DumpCCW /d %s\">%s</exec>", // DML_CCWrapper
"<exec cmd=\"!ClrStack -i %S %d\">%S</exec>", // DML_ManagedVar
"<exec cmd=\"!DumpAsync -addr %s -tasks -completed -fields -stacks -roots\">%s</exec>", // DML_Async
"<exec cmd=\"!DumpIL /i %s\">%s</exec>", // DML_IL
"<exec cmd=\"!DumpRCW -cw /d %s\">%s</exec>", // DML_ComWrapperRCW
"<exec cmd=\"!DumpCCW -cw /d %s\">%s</exec>", // DML_ComWrapperCCW
"<exec cmd=\"dps %s L%d\">%s</exec>", // DML_TaggedMemory
};
void ConvertToLower(__out_ecount(len) char *buffer, size_t len)
{
for (size_t i = 0; i < len && buffer[i]; ++i)
buffer[i] = (char)tolower(buffer[i]);
}
/* Build a hex display of addr.
*/
int GetHex(CLRDATA_ADDRESS addr, __out_ecount(len) char *out, size_t len, bool fill)
{
int count = sprintf_s(out, len, fill ? "%p" : "%x", (size_t)addr);
ConvertToLower(out, len);
return count;
}
CachedString Output::BuildHexValue(CLRDATA_ADDRESS disp, CLRDATA_ADDRESS addr, FormatType type, bool fill)
{
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
if (IsDMLEnabled())
{
char hex1[POINTERSIZE_BYTES*2 + 1];
char hex2[POINTERSIZE_BYTES*2 + 1];
char* d = hex1;
char* a = hex1;
GetHex(addr, hex1, _countof(hex1), fill);
if (disp != addr)
{
GetHex(disp, hex2, _countof(hex2), fill);
d = hex2;
}
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], a, d);
}
else
{
GetHex(disp, ret, ret.GetStrLen(), fill);
}
return ret;
}
CachedString Output::BuildHexValueWithLength(CLRDATA_ADDRESS addr, size_t len, FormatType type, bool fill)
{
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
if (IsDMLEnabled())
{
char hex[POINTERSIZE_BYTES*2 + 1];
GetHex(addr, hex, _countof(hex), fill);
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hex, len, hex);
}
else
{
GetHex(addr, ret, ret.GetStrLen(), fill);
}
return ret;
}
CachedString Output::BuildVCValue(CLRDATA_ADDRESS disp, CLRDATA_ADDRESS mt, CLRDATA_ADDRESS addr, FormatType type, bool fill)
{
_ASSERTE(type == DML_ValueClass);
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
if (IsDMLEnabled())
{
char hexaddr1[POINTERSIZE_BYTES*2 + 1];
char hexaddr2[POINTERSIZE_BYTES*2 + 1];
char hexmt[POINTERSIZE_BYTES*2 + 1];
char* d = hexaddr1;
char* a = hexaddr1;
GetHex(addr, hexaddr1, _countof(hexaddr1), fill);
if (disp != addr)
{
GetHex(disp, hexaddr2, _countof(hexaddr2), fill);
d = hexaddr2;
}
GetHex(mt, hexmt, _countof(hexmt), fill);
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hexmt, a, d);
}
else
{
GetHex(addr, ret, ret.GetStrLen(), fill);
}
return ret;
}
CachedString Output::BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, __in_z LPCWSTR simpleName, FormatType type)
{
_ASSERTE(type == DML_ManagedVar);
CachedString ret;
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
// calculate the number of digits in frame (this assumes base-10 display of frames)
int numFrameDigits = 0;
if (frame > 0)
{
ULONG tempFrame = frame;
while (tempFrame > 0)
{
++numFrameDigits;
tempFrame /= 10;
}
}
else
{
numFrameDigits = 1;
}
size_t totalStringLength = strlen(DMLFormats[type]) + _wcslen(expansionName) + numFrameDigits + _wcslen(simpleName) + 1;
if (totalStringLength > ret.GetStrLen())
{
ret.Allocate(static_cast<int>(totalStringLength));
if (ret.IsOOM())
{
ReportOOM();
return ret;
}
}
if (IsDMLEnabled())
{
sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], expansionName, frame, simpleName);
}
else
{
sprintf_s(ret, ret.GetStrLen(), "%S", simpleName);
}
return ret;
}
CachedString Output::BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, int indexInArray, FormatType type)
{
WCHAR indexString[24];
swprintf_s(indexString, _countof(indexString), W("[%d]"), indexInArray);
return BuildManagedVarValue(expansionName, frame, indexString, type);
}
EnableDMLHolder::EnableDMLHolder(BOOL enable)
: mEnable(enable)
{
#ifndef FEATURE_PAL
// If the user has not requested that we use DML, it's still possible that
// they have instead specified ".prefer_dml 1". If enable is false,
// we will check here for .prefer_dml. Since this class is only used once
// per command issued to SOS, this should only check the setting once per
// sos command issued.
if (!mEnable && Output::g_DMLEnable <= 0)
{
ULONG opts;
HRESULT hr = g_ExtControl->GetEngineOptions(&opts);
mEnable = SUCCEEDED(hr) && (opts & DEBUG_ENGOPT_PREFER_DML) == DEBUG_ENGOPT_PREFER_DML;
}
if (mEnable)
{
Output::g_DMLEnable++;
}
#endif // FEATURE_PAL
}
EnableDMLHolder::~EnableDMLHolder()
{
#ifndef FEATURE_PAL
if (mEnable)
Output::g_DMLEnable--;
#endif
}
bool IsDMLEnabled()
{
return IsInitializedByDbgEng() && Output::g_DMLEnable > 0;
}
NoOutputHolder::NoOutputHolder(BOOL bSuppress)
: mSuppress(bSuppress)
{
if (mSuppress)
Output::g_bSuppressOutput++;
}
NoOutputHolder::~NoOutputHolder()
{
if (mSuppress)
Output::g_bSuppressOutput--;
}
//
// Code to support mapping RVAs to managed code line numbers.
//
//
// Retrieves the IXCLRDataMethodInstance* instance associated with the
// passed in native offset.
HRESULT
GetClrMethodInstance(
___in ULONG64 NativeOffset,
___out IXCLRDataMethodInstance** Method)
{
HRESULT Status;
CLRDATA_ENUM MethEnum;
Status = g_clrData->StartEnumMethodInstancesByAddress(NativeOffset, NULL, &MethEnum);
if (Status == S_OK)
{
Status = g_clrData->EnumMethodInstanceByAddress(&MethEnum, Method);
g_clrData->EndEnumMethodInstancesByAddress(MethEnum);
}
// Any alternate success is a true failure here.
return (Status == S_OK || FAILED(Status)) ? Status : E_NOINTERFACE;
}
//
// Enumerates over the IL address map associated with the passed in
// managed method, and returns the highest non-epilog offset.
HRESULT
GetLastMethodIlOffset(
___in IXCLRDataMethodInstance* Method,
___out PULONG32 MethodOffs)
{
HRESULT Status;
CLRDATA_IL_ADDRESS_MAP MapLocal[16];
CLRDATA_IL_ADDRESS_MAP* Map = MapLocal;
ULONG32 MapCount = _countof(MapLocal);
ULONG32 MapNeeded;
ULONG32 HighestOffset;
for (;;)
{
if ((Status = Method->GetILAddressMap(MapCount, &MapNeeded, Map)) != S_OK)
{
return Status;
}
if (MapNeeded <= MapCount)
{
break;
}
// Need more map entries.
if (Map != MapLocal)
{
// Already went around and the answer changed,
// which should not be possible.
delete[] Map;
return E_UNEXPECTED;
}
Map = new CLRDATA_IL_ADDRESS_MAP[MapNeeded];
if (!Map)
{
return E_OUTOFMEMORY;
}
MapCount = MapNeeded;
}
HighestOffset = 0;
for (size_t i = 0; i < MapNeeded; i++)
{
if (Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_NO_MAPPING &&
Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_PROLOG &&
Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_EPILOG &&
Map[i].ilOffset > HighestOffset)
{
HighestOffset = Map[i].ilOffset;
}
}
if (Map != MapLocal)
{
delete[] Map;
}
*MethodOffs = HighestOffset;
return S_OK;
}
//
// Convert a native offset (possibly already associated with a managed
// method identified by the passed in IXCLRDataMethodInstance) to a
// triplet (ImageInfo, MethodToken, MethodOffset) that can be used to
// represent an "IL offset".
HRESULT
ConvertNativeToIlOffset(
___in ULONG64 nativeOffset,
___in BOOL bAdjustOffsetForLineNumber,
___out IXCLRDataModule** ppModule,
___out mdMethodDef* methodToken,
___out PULONG32 methodOffs)
{
ToRelease<IXCLRDataMethodInstance> pMethodInst(NULL);
HRESULT Status;
if ((Status = GetClrMethodInstance(nativeOffset, &pMethodInst)) != S_OK)
{
ExtDbgOut("ConvertNativeToIlOffset(%p): GetClrMethodInstance FAILED %08x\n", nativeOffset, Status);
return Status;
}
if (bAdjustOffsetForLineNumber)
{
CLRDATA_ADDRESS startAddr;
if (pMethodInst->GetRepresentativeEntryAddress(&startAddr) == S_OK)
{
if (nativeOffset >= (startAddr + g_targetMachine->StackWalkIPAdjustOffset()))
{
nativeOffset -= g_targetMachine->StackWalkIPAdjustOffset();
}
}
}
if ((Status = pMethodInst->GetILOffsetsByAddress(nativeOffset, 1, NULL, methodOffs)) != S_OK)
{
ExtDbgOut("ConvertNativeToIlOffset(%p): GetILOffsetsByAddress FAILED %08x\n", nativeOffset, Status);
*methodOffs = 0;
}
else
{
switch((LONG)*methodOffs)
{
case CLRDATA_IL_OFFSET_NO_MAPPING:
return E_NOINTERFACE;
case CLRDATA_IL_OFFSET_PROLOG:
// Treat all of the prologue as part of
// the first source line.
*methodOffs = 0;
break;
case CLRDATA_IL_OFFSET_EPILOG:
// Back up until we find the last real
// IL offset.
if ((Status = GetLastMethodIlOffset(pMethodInst, methodOffs)) != S_OK)
{
return Status;
}
break;
}
}
return pMethodInst->GetTokenAndScope(methodToken, ppModule);
}
// Based on a native offset, passed in the first argument this function
// identifies the corresponding source file name and line number.
HRESULT
GetLineByOffset(
___in ULONG64 nativeOffset,
___out ULONG *pLinenum,
__out_ecount(cchFileName) WCHAR* pwszFileName,
___in ULONG cchFileName,
___in BOOL bAdjustOffsetForLineNumber /* = FALSE */)
{
HRESULT status = S_OK;
ULONG32 methodToken;
ULONG32 methodOffs;
// Find the image, method token and IL offset that correspond to "nativeOffset"
ToRelease<IXCLRDataModule> pModule(NULL);
status = ConvertNativeToIlOffset(nativeOffset, bAdjustOffsetForLineNumber, &pModule, &methodToken, &methodOffs);
if (FAILED(status))
{
ExtDbgOut("GetLineByOffset(%p): ConvertNativeToIlOffset FAILED %08x\n", nativeOffset, status);
return status;
}
ToRelease<IMetaDataImport> pMDImport(NULL);
status = pModule->QueryInterface(IID_IMetaDataImport, (LPVOID *) &pMDImport);
if (FAILED(status))
{
ExtDbgOut("GetLineByOffset(%p): QueryInterface(IID_IMetaDataImport) FAILED %08x\n", nativeOffset, status);
}
SymbolReader symbolReader;
status = symbolReader.LoadSymbols(pMDImport, pModule);
if (FAILED(status))
{
return status;
}
return symbolReader.GetLineByILOffset(methodToken, methodOffs, pLinenum, pwszFileName, cchFileName);
}
void TableOutput::ReInit(int numColumns, int defaultColumnWidth, Alignment alignmentDefault, int indent, int padding)
{
Clear();
mColumns = numColumns;
mDefaultWidth = defaultColumnWidth;
mIndent = indent;
mPadding = padding;
mCurrCol = 0;
mDefaultAlign = alignmentDefault;
}
void TableOutput::SetWidths(int columns, ...)
{
SOS_Assert(columns > 0);
SOS_Assert(columns <= mColumns);
AllocWidths();
va_list list;
va_start(list, columns);
for (int i = 0; i < columns; ++i)
mWidths[i] = va_arg(list, int);
va_end(list);
}
void TableOutput::SetColWidth(int col, int width)
{
SOS_Assert(col >= 0 && col < mColumns);
SOS_Assert(width >= 0);
AllocWidths();
mWidths[col] = width;
}
void TableOutput::SetColAlignment(int col, Alignment align)
{
SOS_Assert(col >= 0 && col < mColumns);
if (!mAlignments)
{
mAlignments = new Alignment[mColumns];
for (int i = 0; i < mColumns; ++i)
mAlignments[i] = mDefaultAlign;
}
mAlignments[col] = align;
}
void TableOutput::Clear()
{
if (mAlignments)
{
delete [] mAlignments;
mAlignments = 0;
}
if (mWidths)
{
delete [] mWidths;
mWidths = 0;
}
}
void TableOutput::AllocWidths()
{
if (!mWidths)
{
mWidths = new int[mColumns];
for (int i = 0; i < mColumns; ++i)
mWidths[i] = mDefaultWidth;
}
}
int TableOutput::GetColumnWidth(int col)
{
SOS_Assert(col < mColumns);
if (mWidths)
return mWidths[col];
return mDefaultWidth;
}
Alignment TableOutput::GetColAlign(int col)
{
SOS_Assert(col < mColumns);
if (mAlignments)
return mAlignments[col];
return mDefaultAlign;
}
const char *TableOutput::GetWhitespace(int amount)
{
static char WhiteSpace[256] = "";
static int count = 0;
if (count == 0)
{
count = _countof(WhiteSpace);
for (int i = 0; i < count-1; ++i)
WhiteSpace[i] = ' ';
WhiteSpace[count-1] = 0;
}
SOS_Assert(amount < count);
return &WhiteSpace[count-amount-1];
}
void TableOutput::OutputBlankColumns(int col)
{
if (col < mCurrCol)
{
ExtOut("\n");
mCurrCol = 0;
}
int whitespace = 0;
for (int i = mCurrCol; i < col; ++i)
whitespace += GetColumnWidth(i) + mPadding;
ExtOut(GetWhitespace(whitespace));
}
void TableOutput::OutputIndent()
{
if (mIndent)
ExtOut(GetWhitespace(mIndent));
}
#ifndef FEATURE_PAL
PEOffsetMemoryReader::PEOffsetMemoryReader(TADDR moduleBaseAddress) :
m_moduleBaseAddress(moduleBaseAddress),
m_refCount(1)
{}
HRESULT __stdcall PEOffsetMemoryReader::QueryInterface(REFIID riid, VOID** ppInterface)
{
if(riid == __uuidof(IDiaReadExeAtOffsetCallback))
{
*ppInterface = static_cast<IDiaReadExeAtOffsetCallback*>(this);
AddRef();
return S_OK;
}
else if(riid == __uuidof(IUnknown))
{
*ppInterface = static_cast<IUnknown*>(this);
AddRef();
return S_OK;
}
else
{
return E_NOINTERFACE;
}
}
ULONG __stdcall PEOffsetMemoryReader::AddRef()
{
return InterlockedIncrement((volatile LONG *) &m_refCount);
}
ULONG __stdcall PEOffsetMemoryReader::Release()
{
ULONG count = InterlockedDecrement((volatile LONG *) &m_refCount);
if(count == 0)
{
delete this;
}
return count;
}
// IDiaReadExeAtOffsetCallback implementation
HRESULT __stdcall PEOffsetMemoryReader::ReadExecutableAt(DWORDLONG fileOffset, DWORD cbData, DWORD* pcbData, BYTE data[])
{
return SafeReadMemory(m_moduleBaseAddress + fileOffset, data, cbData, pcbData) ? S_OK : E_FAIL;
}
PERvaMemoryReader::PERvaMemoryReader(TADDR moduleBaseAddress) :
m_moduleBaseAddress(moduleBaseAddress),
m_refCount(1)
{}
HRESULT __stdcall PERvaMemoryReader::QueryInterface(REFIID riid, VOID** ppInterface)
{
if(riid == __uuidof(IDiaReadExeAtRVACallback))
{
*ppInterface = static_cast<IDiaReadExeAtRVACallback*>(this);
AddRef();
return S_OK;
}
else if(riid == __uuidof(IUnknown))
{
*ppInterface = static_cast<IUnknown*>(this);
AddRef();
return S_OK;
}
else
{
return E_NOINTERFACE;
}
}
ULONG __stdcall PERvaMemoryReader::AddRef()
{
return InterlockedIncrement((volatile LONG *) &m_refCount);
}
ULONG __stdcall PERvaMemoryReader::Release()
{
ULONG count = InterlockedDecrement((volatile LONG *) &m_refCount);
if(count == 0)
{
delete this;
}
return count;
}
// IDiaReadExeAtOffsetCallback implementation
HRESULT __stdcall PERvaMemoryReader::ReadExecutableAtRVA(DWORD relativeVirtualAddress, DWORD cbData, DWORD* pcbData, BYTE data[])
{
return SafeReadMemory(m_moduleBaseAddress + relativeVirtualAddress, data, cbData, pcbData) ? S_OK : E_FAIL;
}
#endif // FEATURE_PAL
static void AddAssemblyName(WString& methodOutput, CLRDATA_ADDRESS mdesc)
{
DacpMethodDescData mdescData;
if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
{
DacpModuleData dmd;
if (SUCCEEDED(dmd.Request(g_sos, mdescData.ModulePtr)))
{
ToRelease<IXCLRDataModule> pModule;
if (SUCCEEDED(g_sos->GetModule(mdescData.ModulePtr, &pModule)))
{
ArrayHolder<WCHAR> wszFileName = new WCHAR[MAX_LONGPATH + 1];
ULONG32 nameLen = 0;
if (SUCCEEDED(pModule->GetFileName(MAX_LONGPATH, &nameLen, wszFileName)))
{
if (wszFileName[0] != W('\0'))
{
WCHAR *pJustName = _wcsrchr(wszFileName, GetTargetDirectorySeparatorW());
if (pJustName == NULL)
pJustName = wszFileName - 1;
methodOutput += (pJustName + 1);
methodOutput += W("!");
}
}
}
}
}
}
WString GetFrameFromAddress(TADDR frameAddr, IXCLRDataStackWalk *pStackWalk, BOOL bAssemblyName)
{
TADDR vtAddr;
MOVE(vtAddr, frameAddr);
WString frameOutput;
frameOutput += W("[");
if (SUCCEEDED(g_sos->GetFrameName(TO_CDADDR(vtAddr), mdNameLen, g_mdName, NULL)))
frameOutput += g_mdName;
else
frameOutput += W("Frame");
frameOutput += WString(W(": ")) + Pointer(frameAddr) + W("] ");
// Print the frame's associated function info, if it has any.
CLRDATA_ADDRESS mdesc = 0;
if (SUCCEEDED(g_sos->GetMethodDescPtrFromFrame(frameAddr, &mdesc)))
{
if (SUCCEEDED(g_sos->GetMethodDescName(mdesc, mdNameLen, g_mdName, NULL)))
{
if (bAssemblyName)
{
AddAssemblyName(frameOutput, mdesc);
}
frameOutput += g_mdName;
}
else
{
frameOutput += W("<unknown method>");
}
}
else if (pStackWalk)
{
// The Frame did not have direct function info, so try to get the method instance
// (in this case a MethodDesc), and read the name from it.
ToRelease<IXCLRDataFrame> frame;
if (SUCCEEDED(pStackWalk->GetFrame(&frame)))
{
ToRelease<IXCLRDataMethodInstance> methodInstance;
if (SUCCEEDED(frame->GetMethodInstance(&methodInstance)))
{
// GetName can return S_FALSE if mdNameLen is not large enough. However we are already
// passing a pretty big buffer in. If this returns S_FALSE (meaning the buffer is too
// small) then we should not output it anyway.
if (methodInstance->GetName(0, mdNameLen, NULL, g_mdName) == S_OK)
frameOutput += g_mdName;
}
}
}
return frameOutput;
}
WString MethodNameFromIP(CLRDATA_ADDRESS ip, BOOL bSuppressLines, BOOL bAssemblyName, BOOL bDisplacement, BOOL bAdjustIPForLineNumber)
{
ULONG linenum;
WString methodOutput;
CLRDATA_ADDRESS mdesc = 0;
if (FAILED(g_sos->GetMethodDescPtrFromIP(ip, &mdesc)))
{
methodOutput = W("<unknown>");
}
else
{
DacpMethodDescData mdescData;
if (SUCCEEDED(g_sos->GetMethodDescName(mdesc, mdNameLen, g_mdName, NULL)))
{
if (bAssemblyName)
{
AddAssemblyName(methodOutput, mdesc);
}
methodOutput += g_mdName;
if (bDisplacement)
{
if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
{
ULONG64 disp = (ip - mdescData.NativeCodeAddr);
if (disp)
{
methodOutput += W(" + ");
methodOutput += Decimal(disp);
}
}
}
}
else if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
{
DacpModuleData dmd;
BOOL bModuleNameWorked = FALSE;
ULONG64 addrInModule = ip;
if (SUCCEEDED(dmd.Request(g_sos, mdescData.ModulePtr)))
{
CLRDATA_ADDRESS peFileBase = 0;
if (SUCCEEDED(g_sos->GetPEFileBase(dmd.PEAssembly, &peFileBase)))
{
if (peFileBase)
{
addrInModule = peFileBase;
}
}
}
ULONG Index;
ULONG64 moduleBase;
if (SUCCEEDED(g_ExtSymbols->GetModuleByOffset(UL64_TO_CDA(addrInModule), 0, &Index, &moduleBase)))
{
ArrayHolder<char> szModuleName = new char[MAX_LONGPATH+1];
if (SUCCEEDED(g_ExtSymbols->GetModuleNames(Index, moduleBase, NULL, 0, NULL, szModuleName, MAX_LONGPATH, NULL, NULL, 0, NULL)))
{
MultiByteToWideChar (CP_ACP, 0, szModuleName, MAX_LONGPATH, g_mdName, _countof(g_mdName));
methodOutput += g_mdName;
methodOutput += W("!");
}
}
methodOutput += W("<unknown method>");
}
else
{
methodOutput = W("<unknown>");
}
ArrayHolder<WCHAR> wszFileName = new WCHAR[MAX_LONGPATH];
if (!bSuppressLines &&
SUCCEEDED(GetLineByOffset(TO_CDADDR(ip), &linenum, wszFileName, MAX_LONGPATH, bAdjustIPForLineNumber)))
{
methodOutput += WString(W(" [")) + wszFileName + W(" @ ") + Decimal(linenum) + W("]");
}
}
return methodOutput;
}
HRESULT GetGCRefs(ULONG osID, SOSStackRefData **ppRefs, unsigned int *pRefCnt, SOSStackRefError **ppErrors, unsigned int *pErrCount)
{
if (ppRefs == NULL || pRefCnt == NULL)
return E_POINTER;
if (pErrCount)
*pErrCount = 0;
*pRefCnt = 0;
unsigned int count = 0;
ToRelease<ISOSStackRefEnum> pEnum;
if (FAILED(g_sos->GetStackReferences(osID, &pEnum)) || FAILED(pEnum->GetCount(&count)))
{
ExtOut("Failed to enumerate GC references.\n");
return E_FAIL;
}
*ppRefs = new SOSStackRefData[count];
if (FAILED(pEnum->Next(count, *ppRefs, pRefCnt)))
{
ExtOut("Failed to enumerate GC references.\n");
return E_FAIL;
}
SOS_Assert(count == *pRefCnt);
// Enumerate errors found. Any bad HRESULT recieved while enumerating errors is NOT a fatal error.
// Hence we return S_FALSE if we encounter one.
if (ppErrors && pErrCount)
{
ToRelease<ISOSStackRefErrorEnum> pErrors;
if (FAILED(pEnum->EnumerateErrors(&pErrors)))
{
ExtOut("Failed to enumerate GC reference errors.\n");
return S_FALSE;
}
if (FAILED(pErrors->GetCount(&count)))
{
ExtOut("Failed to enumerate GC reference errors.\n");
return S_FALSE;
}
*ppErrors = new SOSStackRefError[count];
if (FAILED(pErrors->Next(count, *ppErrors, pErrCount)))
{
ExtOut("Failed to enumerate GC reference errors.\n");
*pErrCount = 0;
return S_FALSE;
}
SOS_Assert(count == *pErrCount);
}
return S_OK;
}
InternalFrameManager::InternalFrameManager() : m_cInternalFramesActual(0), m_iInternalFrameCur(0) {}
HRESULT InternalFrameManager::Init(ICorDebugThread3 * pThread3)
{
_ASSERTE(pThread3 != NULL);
return pThread3->GetActiveInternalFrames(
_countof(m_rgpInternalFrame2),
&m_cInternalFramesActual,
&(m_rgpInternalFrame2[0]));
}
HRESULT InternalFrameManager::PrintPrecedingInternalFrames(ICorDebugFrame * pFrame)
{
HRESULT Status;
for (; m_iInternalFrameCur < m_cInternalFramesActual; m_iInternalFrameCur++)
{
BOOL bIsCloser = FALSE;
IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->IsCloserToLeaf(pFrame, &bIsCloser));
if (!bIsCloser)
{
// Current internal frame is now past pFrame, so we're done
return S_OK;
}
IfFailRet(PrintCurrentInternalFrame());
}
// Exhausted list of internal frames. Done!
return S_OK;
}
HRESULT InternalFrameManager::PrintCurrentInternalFrame()
{
_ASSERTE(m_iInternalFrameCur < m_cInternalFramesActual);
HRESULT Status;
CORDB_ADDRESS address;
IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->GetAddress(&address));
ToRelease<ICorDebugInternalFrame> pInternalFrame;
IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->QueryInterface(IID_ICorDebugInternalFrame, (LPVOID *) &pInternalFrame));
CorDebugInternalFrameType type;
IfFailRet(pInternalFrame->GetFrameType(&type));
LPCSTR szFrameType = NULL;
switch(type)
{
default:
szFrameType = "Unknown internal frame.";
break;
case STUBFRAME_M2U:
szFrameType = "Managed to Unmanaged transition";
break;
case STUBFRAME_U2M:
szFrameType = "Unmanaged to Managed transition";
break;
case STUBFRAME_APPDOMAIN_TRANSITION:
szFrameType = "AppDomain transition";
break;
case STUBFRAME_LIGHTWEIGHT_FUNCTION:
szFrameType = "Lightweight function";
break;
case STUBFRAME_FUNC_EVAL:
szFrameType = "Function evaluation";
break;
case STUBFRAME_INTERNALCALL:
szFrameType = "Internal call";
break;
case STUBFRAME_CLASS_INIT:
szFrameType = "Class initialization";
break;
case STUBFRAME_EXCEPTION:
szFrameType = "Exception";
break;
case STUBFRAME_SECURITY:
szFrameType = "Security";
break;
case STUBFRAME_JIT_COMPILATION:
szFrameType = "JIT Compilation";
break;
}
DMLOut("%p %s ", SOS_PTR(address), SOS_PTR(0));
ExtOut("[%s: %p]\n", szFrameType, SOS_PTR(address));
return S_OK;
}
#ifdef FEATURE_PAL
struct MemoryRegion
{
private:
uint64_t m_startAddress;
uint64_t m_endAddress;
CLRDATA_ADDRESS m_peFile;
BYTE* m_metadataMemory;
volatile LONG m_busy;
HRESULT CacheMetadata()
{
if (m_metadataMemory == nullptr)
{
HRESULT hr;
CLRDATA_ADDRESS baseAddress;
if (FAILED(hr = g_sos->GetPEFileBase(m_peFile, &baseAddress))) {
return hr;
}
ArrayHolder<WCHAR> imagePath = new WCHAR[MAX_LONGPATH];
if (FAILED(hr = g_sos->GetPEFileName(m_peFile, MAX_LONGPATH, imagePath.GetPtr(), NULL))) {
return hr;
}
IMAGE_DOS_HEADER DosHeader;
if (FAILED(hr = g_ExtData->ReadVirtual(baseAddress, &DosHeader, sizeof(DosHeader), NULL))) {
return hr;
}
IMAGE_NT_HEADERS Header;
if (FAILED(hr = g_ExtData->ReadVirtual(baseAddress + DosHeader.e_lfanew, &Header, sizeof(Header), NULL))) {
return hr;
}
// If there is no COMHeader, this can not be managed code.
if (Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress == 0) {
return E_ACCESSDENIED;
}
ULONG32 imageSize = Header.OptionalHeader.SizeOfImage;
ULONG32 timeStamp = Header.FileHeader.TimeDateStamp;
ULONG32 bufferSize = (ULONG32)Size();
ArrayHolder<BYTE> buffer = new NOTHROW BYTE[bufferSize];
if (buffer == nullptr) {
return E_OUTOFMEMORY;
}
ULONG32 actualSize = 0;
if (FAILED(hr = GetMetadataLocator(imagePath, timeStamp, imageSize, nullptr, 0, 0, bufferSize, buffer, &actualSize))) {
return hr;
}
m_metadataMemory = buffer.Detach();
}
return S_OK;
}
public:
MemoryRegion(uint64_t start, uint64_t end, CLRDATA_ADDRESS peFile) :
m_startAddress(start),
m_endAddress(end),
m_peFile(peFile),
m_metadataMemory(nullptr),
m_busy(0)
{
}
uint64_t StartAddress() const { return m_startAddress; }
uint64_t EndAddress() const { return m_endAddress; }
uint64_t Size() const { return m_endAddress - m_startAddress; }
CLRDATA_ADDRESS const PEFile() { return m_peFile; }
bool operator<(const MemoryRegion& rhs) const
{
return (m_startAddress < rhs.m_startAddress) && (m_endAddress <= rhs.m_startAddress);
}
// Returns true if "rhs" is wholly contained in this one
bool Contains(const MemoryRegion& rhs) const
{
return (m_startAddress <= rhs.m_startAddress) && (m_endAddress >= rhs.m_endAddress);
}
HRESULT ReadMetadata(CLRDATA_ADDRESS address, ULONG32 bufferSize, BYTE* buffer)
{
_ASSERTE((m_startAddress <= address) && (m_endAddress >= (address + bufferSize)));
HRESULT hr = E_ACCESSDENIED;
// Skip in-memory and dynamic modules or if CacheMetadata failed
if (m_peFile != 0)
{
if (InterlockedIncrement(&m_busy) == 1)
{
// Attempt to get the assembly metadata from local file or by downloading from a symbol server
hr = CacheMetadata();
if (FAILED(hr)) {
// If we can get the metadata from the assembly, mark this region to always fail.
m_peFile = 0;
}
}
InterlockedDecrement(&m_busy);
}
if (FAILED(hr)) {
return hr;
}
// Read the memory from the cached metadata blob
_ASSERTE(m_metadataMemory != nullptr);
uint64_t offset = address - m_startAddress;
memcpy(buffer, m_metadataMemory + offset, bufferSize);
return S_OK;
}
void Dispose()
{
if (m_metadataMemory != nullptr)
{
delete[] m_metadataMemory;
m_metadataMemory = nullptr;
}
}
};
std::set<MemoryRegion> g_metadataRegions;
bool g_metadataRegionsPopulated = false;
void FlushMetadataRegions()
{
for (const MemoryRegion& region : g_metadataRegions)
{
const_cast<MemoryRegion&>(region).Dispose();
}
g_metadataRegions.clear();
g_metadataRegionsPopulated = false;
}
void PopulateMetadataRegions()
{
g_metadataRegions.clear();
// Only populate the metadata regions if core dump
if (IsDumpFile())
{
int numModule;
ArrayHolder<DWORD_PTR> moduleList = ModuleFromName(NULL, &numModule);
if (moduleList != nullptr)
{
for (int i = 0; i < numModule; i++)
{
DacpModuleData moduleData;
if (SUCCEEDED(moduleData.Request(g_sos, moduleList[i])))
{
if (moduleData.metadataStart != 0)
{
MemoryRegion region(moduleData.metadataStart, moduleData.metadataStart + moduleData.metadataSize, moduleData.PEAssembly);
g_metadataRegions.insert(region);
#ifdef DUMP_METADATA_INFO
ArrayHolder<WCHAR> name = new WCHAR[MAX_LONGPATH];
name[0] = '\0';
if (moduleData.File != 0)
{
g_sos->GetPEFileName(moduleData.File, MAX_LONGPATH, name.GetPtr(), NULL);
}
ExtOut("%016x %016x %016x %S\n", moduleData.metadataStart, moduleData.metadataStart + moduleData.metadataSize, moduleData.metadataSize, name.GetPtr());
#endif
}
}
}
}
else
{
ExtDbgOut("PopulateMetadataRegions ModuleFromName returns null\n");
}
}
}
HRESULT GetMetadataMemory(CLRDATA_ADDRESS address, ULONG32 bufferSize, BYTE* buffer)
{
// Populate the metadata memory region map
if (!g_metadataRegionsPopulated)
{
g_metadataRegionsPopulated = true;
PopulateMetadataRegions();
}
// Check if the memory address is in a metadata memory region
MemoryRegion region(address, address + bufferSize, 0);
const auto& found = g_metadataRegions.find(region);
if (found != g_metadataRegions.end() && found->Contains(region)) {
return const_cast<MemoryRegion&>(*found).ReadMetadata(address, bufferSize, buffer);
}
return E_ACCESSDENIED;
}
#endif // FEATURE_PAL
|
#include "bits/stdc++.h"
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#define ll long long
#define ull unsigned long long
#define F first
#define S second
#define PB push_back
#define POB pop_back
using namespace std;
int main(){
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie();
int n;
cin>>n;
ll mx = 0;
ll sum = 0;
for(int i = 0; i < n; i++) {
ll t;
cin>>t;
mx = max(mx, t);
sum += t;
}
if(mx >= sum - mx) {
cout<<mx * 2<<endl;
} else {
cout<<sum<<endl;
}
return 0;
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2018, EAIBOT, 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.
*********************************************************************/
#include "CYdLidar.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
using namespace ydlidar;
#if defined(_MSC_VER)
#pragma comment(lib, "ydlidar_sdk.lib")
#endif
/**
* @brief tof Lidar test
* @param argc
* @param argv
* @return
* @par Flow chart
* Step1: instance CYdLidar.\n
* Step2: set paramters.\n
* Step3: initialize SDK and LiDAR.(::CYdLidar::initialize)\n
* Step4: Start the device scanning routine which runs on a separate thread and enable motor.(::CYdLidar::turnOn)\n
* Step5: Get the LiDAR Scan Data.(::CYdLidar::doProcessSimple)\n
* Step6: Stop the device scanning thread and disable motor.(::CYdLidar::turnOff)\n
* Step7: Uninitialize the SDK and Disconnect the LiDAR.(::CYdLidar::disconnecting)\n
*/
int main(int argc, char *argv[]) {
printf("__ ______ _ ___ ____ _ ____ \n");
printf("\\ \\ / / _ \\| | |_ _| _ \\ / \\ | _ \\ \n");
printf(" \\ V /| | | | | | || | | |/ _ \\ | |_) | \n");
printf(" | | | |_| | |___ | || |_| / ___ \\| _ < \n");
printf(" |_| |____/|_____|___|____/_/ \\_\\_| \\_\\ \n");
printf("\n");
fflush(stdout);
std::string port;
ydlidar::os_init();
std::map<std::string, std::string> ports = ydlidar::lidarPortList();
std::map<std::string, std::string>::iterator it;
if (ports.size() == 1) {
port = ports.begin()->second;
} else {
int id = 0;
for (it = ports.begin(); it != ports.end(); it++) {
printf("%d. %s\n", id, it->first.c_str());
id++;
}
if (ports.empty()) {
printf("Not Lidar was detected. Please enter the lidar serial port:");
std::cin >> port;
} else {
while (ydlidar::os_isOk()) {
printf("Please select the lidar port:");
std::string number;
std::cin >> number;
if ((size_t)atoi(number.c_str()) >= ports.size()) {
continue;
}
it = ports.begin();
id = atoi(number.c_str());
while (id) {
id--;
it++;
}
port = it->second;
break;
}
}
}
int baudrate = 230400;
std::map<int, int> baudrateList;
baudrateList[0] = 115200;
baudrateList[1] = 230400;
baudrateList[2] = 512000;
printf("Baudrate:\n");
for (std::map<int, int>::iterator it = baudrateList.begin();
it != baudrateList.end(); it++) {
printf("%d. %d\n", it->first, it->second);
}
while (ydlidar::os_isOk()) {
printf("Please select the lidar baudrate:");
std::string number;
std::cin >> number;
if ((size_t)atoi(number.c_str()) > baudrateList.size()) {
continue;
}
baudrate = baudrateList[atoi(number.c_str())];
break;
}
if (!ydlidar::os_isOk()) {
return 0;
}
bool isSingleChannel = false;
std::string input_channel;
printf("Whether the Lidar is one-way communication[yes/no]:");
std::cin >> input_channel;
std::transform(input_channel.begin(), input_channel.end(),
input_channel.begin(),
[](unsigned char c) {
return std::tolower(c); // correct
});
if (input_channel.find("y") != std::string::npos) {
isSingleChannel = true;
}
if (!ydlidar::os_isOk()) {
return 0;
}
std::string input_frequency;
float frequency = 8.0f;
while (ydlidar::os_isOk() && !isSingleChannel) {
printf("Please enter the lidar scan frequency[3-15.7]:");
std::cin >> input_frequency;
frequency = atof(input_frequency.c_str());
if (frequency <= 15.7 && frequency >= 3.0) {
break;
}
fprintf(stderr,
"Invalid scan frequency,The scanning frequency range is 3 to 15.7 HZ, Please re-enter.\n");
}
if (!ydlidar::os_isOk()) {
return 0;
}
/// instance
CYdLidar laser;
//////////////////////string property/////////////////
/// lidar port
laser.setlidaropt(LidarPropSerialPort, port.c_str(), port.size());
/// ignore array
std::string ignore_array;
ignore_array.clear();
laser.setlidaropt(LidarPropIgnoreArray, ignore_array.c_str(),
ignore_array.size());
//////////////////////int property/////////////////
/// lidar baudrate
laser.setlidaropt(LidarPropSerialBaudrate, &baudrate, sizeof(int));
/// tof lidar
int optval = TYPE_TOF;
laser.setlidaropt(LidarPropLidarType, &optval, sizeof(int));
/// device type
optval = YDLIDAR_TYPE_SERIAL;
laser.setlidaropt(LidarPropDeviceType, &optval, sizeof(int));
/// sample rate
optval = isSingleChannel ? 4 : 20;
laser.setlidaropt(LidarPropSampleRate, &optval, sizeof(int));
/// abnormal count
optval = 4;
laser.setlidaropt(LidarPropAbnormalCheckCount, &optval, sizeof(int));
//////////////////////bool property/////////////////
/// fixed angle resolution
bool b_optvalue = false;
laser.setlidaropt(LidarPropFixedResolution, &b_optvalue, sizeof(bool));
/// rotate 180
laser.setlidaropt(LidarPropReversion, &b_optvalue, sizeof(bool));
/// Counterclockwise
laser.setlidaropt(LidarPropInverted, &b_optvalue, sizeof(bool));
b_optvalue = true;
laser.setlidaropt(LidarPropAutoReconnect, &b_optvalue, sizeof(bool));
/// one-way communication
b_optvalue = isSingleChannel;
laser.setlidaropt(LidarPropSingleChannel, &b_optvalue, sizeof(bool));
/// intensity
b_optvalue = false;
laser.setlidaropt(LidarPropIntenstiy, &b_optvalue, sizeof(bool));
/// Motor DTR
laser.setlidaropt(LidarPropSupportMotorDtrCtrl, &b_optvalue, sizeof(bool));
//////////////////////float property/////////////////
/// unit: °
float f_optvalue = 180.0f;
laser.setlidaropt(LidarPropMaxAngle, &f_optvalue, sizeof(float));
f_optvalue = -180.0f;
laser.setlidaropt(LidarPropMinAngle, &f_optvalue, sizeof(float));
/// unit: m
f_optvalue = 64.f;
laser.setlidaropt(LidarPropMaxRange, &f_optvalue, sizeof(float));
f_optvalue = 0.05f;
laser.setlidaropt(LidarPropMinRange, &f_optvalue, sizeof(float));
/// unit: Hz
laser.setlidaropt(LidarPropScanFrequency, &frequency, sizeof(float));
/// initialize SDK and LiDAR.
bool ret = laser.initialize();
if (ret) {//success
/// Start the device scanning routine which runs on a separate thread and enable motor.
ret = laser.turnOn();
} else {//failed
fprintf(stderr, "%s\n", laser.DescribeError());
fflush(stderr);
}
LaserScan scan;
while (ret && ydlidar::os_isOk()) {/// Turn On success and loop
if (laser.doProcessSimple(scan)) {
fprintf(stdout, "Scan received[%llu]: %u ranges is [%f]Hz\n",
scan.stamp,
(unsigned int)scan.points.size(), 1.0 / scan.config.scan_time);
fflush(stdout);
} else {
fprintf(stderr, "Failed to get Lidar Data\n");
fflush(stderr);
}
}
/// Stop the device scanning thread and disable motor.
laser.turnOff();
/// Uninitialize the SDK and Disconnect the LiDAR.
laser.disconnecting();
return 0;
}
|
/**
* @file monstdat.cpp
*
* Implementation of all monster data.
*/
#include "monstdat.h"
#include "items.h"
#include "monster.h"
#include "textdat.h"
#include "utils/language.h"
namespace devilution {
/** Contains the data related to each monster ID. */
const MonsterData MonstersData[] = {
// clang-format off
//_monster_id mName, GraphicType, sndfile, TransFile, availability, width, mImage, has_special, snd_special, has_trans, Frames[6], Rate[6], mMinDLvl, mMaxDLvl, mLevel, mMinHP, mMaxHP, mAi, mFlags , mInt, mHit, mAFNum, mMinDamage, mMaxDamage, mHit2, mAFNum2, mMinDamage2, mMaxDamage2, mArmorClass, mMonstClass , mMagicRes , mMagicRes2 , mSelFlag, mTreasure, mExp
// TRANSLATORS: Monster Block start
/* MT_NZOMBIE */ { P_("monster", "Zombie"), "Zombie\\Zombie", "Monsters\\Zombie\\Zombie%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 799, false, false, false, { 11, 24, 12, 6, 16, 0 }, { 4, 1, 1, 1, 1, 1 }, 1, 2, 1, 4, 7, AI_ZOMBIE, 0 , 0, 10, 8, 2, 5, 0, 0, 0, 0, 5, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 54 },
/* MT_BZOMBIE */ { P_("monster", "Ghoul"), "Zombie\\Zombie", "Monsters\\Zombie\\Zombie%c%i.WAV", "Monsters\\Zombie\\Bluered.TRN", MonsterAvailability::Always, 128, 799, false, false, true, { 11, 24, 12, 6, 16, 0 }, { 4, 1, 1, 1, 1, 1 }, 2, 3, 2, 7, 11, AI_ZOMBIE, 0 , 1, 10, 8, 3, 10, 0, 0, 0, 0, 10, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 58 },
/* MT_GZOMBIE */ { P_("monster", "Rotting Carcass"), "Zombie\\Zombie", "Monsters\\Zombie\\Zombie%c%i.WAV", "Monsters\\Zombie\\Grey.TRN", MonsterAvailability::Always, 128, 799, false, false, true, { 11, 24, 12, 6, 16, 0 }, { 4, 1, 1, 1, 1, 1 }, 2, 4, 4, 15, 25, AI_ZOMBIE, 0 , 2, 25, 8, 5, 15, 0, 0, 0, 0, 15, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , 3, 0, 136 },
/* MT_YZOMBIE */ { P_("monster", "Black Death"), "Zombie\\Zombie", "Monsters\\Zombie\\Zombie%c%i.WAV", "Monsters\\Zombie\\Yellow.TRN", MonsterAvailability::Always, 128, 799, false, false, true, { 11, 24, 12, 6, 16, 0 }, { 4, 1, 1, 1, 1, 1 }, 3, 5, 6, 25, 40, AI_ZOMBIE, 0 , 3, 30, 8, 6, 22, 0, 0, 0, 0, 20, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 240 },
/* MT_RFALLSP */ { P_("monster", "Fallen One"), "FalSpear\\Phall", "Monsters\\FalSpear\\Phall%c%i.WAV", "Monsters\\FalSpear\\FallenT.TRN", MonsterAvailability::Always, 128, 543, true, true, true, { 11, 11, 13, 11, 18, 13 }, { 3, 1, 1, 1, 1, 1 }, 1, 2, 1, 1, 4, AI_FALLEN, 0 , 0, 15, 7, 1, 3, 0, 5, 0, 0, 0, MonsterClass::Animal, 0 , 0 , 3, 0, 46 },
/* MT_DFALLSP */ { P_("monster", "Carver"), "FalSpear\\Phall", "Monsters\\FalSpear\\Phall%c%i.WAV", "Monsters\\FalSpear\\Dark.TRN", MonsterAvailability::Always, 128, 543, true, true, true, { 11, 11, 13, 11, 18, 13 }, { 3, 1, 1, 1, 1, 1 }, 2, 3, 3, 4, 8, AI_FALLEN, 0 , 2, 20, 7, 2, 5, 0, 5, 0, 0, 5, MonsterClass::Animal, 0 , 0 , 3, 0, 80 },
/* MT_YFALLSP */ { P_("monster", "Devil Kin"), "FalSpear\\Phall", "Monsters\\FalSpear\\Phall%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 543, true, true, false, { 11, 11, 13, 11, 18, 13 }, { 3, 1, 1, 1, 1, 1 }, 2, 4, 5, 12, 24, AI_FALLEN, 0 , 2, 25, 7, 3, 7, 0, 5, 0, 0, 10, MonsterClass::Animal, 0 , RESIST_FIRE , 3, 0, 155 },
/* MT_BFALLSP */ { P_("monster", "Dark One"), "FalSpear\\Phall", "Monsters\\FalSpear\\Phall%c%i.WAV", "Monsters\\FalSpear\\Blue.TRN", MonsterAvailability::Always, 128, 543, true, true, true, { 11, 11, 13, 11, 18, 13 }, { 3, 1, 1, 1, 1, 1 }, 3, 5, 7, 20, 36, AI_FALLEN, 0 , 3, 30, 7, 4, 8, 0, 5, 0, 0, 15, MonsterClass::Animal, IMMUNE_NULL_40 , RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 255 },
/* MT_WSKELAX */ { P_("monster", "Skeleton"), "SkelAxe\\SklAx", "Monsters\\SkelAxe\\SklAx%c%i.WAV", "Monsters\\SkelAxe\\White.TRN", MonsterAvailability::Always, 128, 553, true, false, true, { 12, 8, 13, 6, 17, 16 }, { 5, 1, 1, 1, 1, 1 }, 1, 2, 1, 2, 4, AI_SKELSD, 0 , 0, 20, 8, 1, 4, 0, 0, 0, 0, 0, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 64 },
/* MT_TSKELAX */ { P_("monster", "Corpse Axe"), "SkelAxe\\SklAx", "Monsters\\SkelAxe\\SklAx%c%i.WAV", "Monsters\\SkelAxe\\Skelt.TRN", MonsterAvailability::Always, 128, 553, true, false, true, { 12, 8, 13, 6, 17, 16 }, { 4, 1, 1, 1, 1, 1 }, 2, 3, 2, 4, 7, AI_SKELSD, 0 , 1, 25, 8, 3, 5, 0, 0, 0, 0, 0, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 68 },
/* MT_RSKELAX */ { P_("monster", "Burning Dead"), "SkelAxe\\SklAx", "Monsters\\SkelAxe\\SklAx%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 553, true, false, false, { 12, 8, 13, 6, 17, 16 }, { 2, 1, 1, 1, 1, 1 }, 2, 4, 4, 8, 12, AI_SKELSD, 0 , 2, 30, 8, 3, 7, 0, 0, 0, 0, 5, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , 3, 0, 154 },
/* MT_XSKELAX */ { P_("monster", "Horror"), "SkelAxe\\SklAx", "Monsters\\SkelAxe\\SklAx%c%i.WAV", "Monsters\\SkelAxe\\Black.TRN", MonsterAvailability::Always, 128, 553, true, false, true, { 12, 8, 13, 6, 17, 16 }, { 3, 1, 1, 1, 1, 1 }, 3, 5, 6, 12, 20, AI_SKELSD, 0 , 3, 35, 8, 4, 9, 0, 0, 0, 0, 15, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 264 },
/* MT_RFALLSD */ { P_("monster", "Fallen One"), "FalSword\\Fall", "Monsters\\FalSword\\Fall%c%i.WAV", "Monsters\\FalSword\\FallenT.TRN", MonsterAvailability::Always, 128, 623, true, true, true, { 12, 12, 13, 11, 14, 15 }, { 3, 1, 1, 1, 1, 1 }, 1, 2, 1, 2, 5, AI_FALLEN, 0 , 0, 15, 8, 1, 4, 0, 5, 0, 0, 10, MonsterClass::Animal, 0 , 0 , 3, 0, 52 },
/* MT_DFALLSD */ { P_("monster", "Carver"), "FalSword\\Fall", "Monsters\\FalSword\\Fall%c%i.WAV", "Monsters\\FalSword\\Dark.TRN", MonsterAvailability::Always, 128, 623, true, true, true, { 12, 12, 13, 11, 14, 15 }, { 3, 1, 1, 1, 1, 1 }, 2, 3, 3, 5, 9, AI_FALLEN, 0 , 1, 20, 8, 2, 7, 0, 5, 0, 0, 15, MonsterClass::Animal, 0 , 0 , 3, 0, 90 },
/* MT_YFALLSD */ { P_("monster", "Devil Kin"), "FalSword\\Fall", "Monsters\\FalSword\\Fall%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 623, true, true, false, { 12, 12, 13, 11, 14, 15 }, { 3, 1, 1, 1, 1, 1 }, 2, 4, 5, 16, 24, AI_FALLEN, 0 , 2, 25, 8, 4, 10, 0, 5, 0, 0, 20, MonsterClass::Animal, 0 , RESIST_FIRE , 3, 0, 180 },
/* MT_BFALLSD */ { P_("monster", "Dark One"), "FalSword\\Fall", "Monsters\\FalSword\\Fall%c%i.WAV", "Monsters\\FalSword\\Blue.TRN", MonsterAvailability::Always, 128, 623, true, true, true, { 12, 12, 13, 11, 14, 15 }, { 3, 1, 1, 1, 1, 1 }, 3, 5, 7, 24, 36, AI_FALLEN, 0 , 3, 30, 8, 4, 12, 0, 5, 0, 0, 25, MonsterClass::Animal, IMMUNE_NULL_40 , RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 280 },
/* MT_NSCAV */ { P_("monster", "Scavenger"), "Scav\\Scav", "Monsters\\Scav\\Scav%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 410, true, false, false, { 12, 8, 12, 6, 20, 11 }, { 2, 1, 1, 1, 1, 1 }, 1, 3, 2, 3, 6, AI_SCAV, 0 , 0, 20, 7, 1, 5, 0, 0, 0, 0, 10, MonsterClass::Animal, 0 , RESIST_FIRE , 3, 0, 80 },
/* MT_BSCAV */ { P_("monster", "Plague Eater"), "Scav\\Scav", "Monsters\\Scav\\Scav%c%i.WAV", "Monsters\\Scav\\ScavBr.TRN", MonsterAvailability::Always, 128, 410, true, false, true, { 12, 8, 12, 6, 20, 11 }, { 2, 1, 1, 1, 1, 1 }, 2, 4, 4, 12, 24, AI_SCAV, 0 , 1, 30, 7, 1, 8, 0, 0, 0, 0, 20, MonsterClass::Animal, 0 , RESIST_LIGHTNING , 3, 0, 188 },
/* MT_WSCAV */ { P_("monster", "Shadow Beast"), "Scav\\Scav", "Monsters\\Scav\\Scav%c%i.WAV", "Monsters\\Scav\\ScavBe.TRN", MonsterAvailability::Always, 128, 410, true, false, true, { 12, 8, 12, 6, 20, 11 }, { 2, 1, 1, 1, 1, 1 }, 3, 5, 6, 24, 36, AI_SCAV, 0 , 2, 35, 7, 3, 12, 0, 0, 0, 0, 25, MonsterClass::Animal, IMMUNE_NULL_40 , RESIST_FIRE | IMMUNE_NULL_40 , 3, 0, 375 },
/* MT_YSCAV */ { P_("monster", "Bone Gasher"), "Scav\\Scav", "Monsters\\Scav\\Scav%c%i.WAV", "Monsters\\Scav\\ScavW.TRN", MonsterAvailability::Always, 128, 410, true, false, true, { 12, 8, 12, 6, 20, 11 }, { 2, 1, 1, 1, 1, 1 }, 4, 6, 8, 28, 40, AI_SCAV, 0 , 3, 35, 7, 5, 15, 0, 0, 0, 0, 30, MonsterClass::Animal, RESIST_MAGIC | IMMUNE_NULL_40 , RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 552 },
/* MT_WSKELBW */ { P_("monster", "Skeleton"), "SkelBow\\SklBw", "Monsters\\SkelBow\\SklBw%c%i.WAV", "Monsters\\SkelBow\\White.TRN", MonsterAvailability::Always, 128, 567, true, false, true, { 9, 8, 16, 5, 16, 16 }, { 4, 1, 1, 1, 1, 1 }, 2, 3, 3, 2, 4, AI_SKELBOW, 0 , 0, 15, 12, 1, 2, 0, 0, 0, 0, 0, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 110 },
/* MT_TSKELBW */ { P_("monster", "Corpse Bow"), "SkelBow\\SklBw", "Monsters\\SkelBow\\SklBw%c%i.WAV", "Monsters\\SkelBow\\Skelt.TRN", MonsterAvailability::Always, 128, 567, true, false, true, { 9, 8, 16, 5, 16, 16 }, { 4, 1, 1, 1, 1, 1 }, 2, 4, 5, 8, 16, AI_SKELBOW, 0 , 1, 25, 12, 1, 4, 0, 0, 0, 0, 0, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 210 },
/* MT_RSKELBW */ { P_("monster", "Burning Dead"), "SkelBow\\SklBw", "Monsters\\SkelBow\\SklBw%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 567, true, false, false, { 9, 8, 16, 5, 16, 16 }, { 2, 1, 1, 1, 1, 1 }, 3, 5, 7, 10, 24, AI_SKELBOW, 0 , 2, 30, 12, 1, 6, 0, 0, 0, 0, 5, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , 3, 0, 364 },
/* MT_XSKELBW */ { P_("monster", "Horror"), "SkelBow\\SklBw", "Monsters\\SkelBow\\SklBw%c%i.WAV", "Monsters\\SkelBow\\Black.TRN", MonsterAvailability::Always, 128, 567, true, false, true, { 9, 8, 16, 5, 16, 16 }, { 3, 1, 1, 1, 1, 1 }, 4, 6, 9, 15, 45, AI_SKELBOW, 0 , 3, 35, 12, 2, 9, 0, 0, 0, 0, 15, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 594 },
/* MT_WSKELSD */ { P_("monster", "Skeleton Captain"), "SkelSd\\SklSr", "Monsters\\SkelSd\\SklSr%c%i.WAV", "Monsters\\SkelSd\\White.TRN", MonsterAvailability::Always, 128, 575, true, true, true, { 13, 8, 12, 7, 15, 16 }, { 4, 1, 1, 1, 1, 1 }, 1, 3, 2, 3, 6, AI_SKELSD, 0 , 0, 20, 8, 2, 7, 0, 0, 0, 0, 10, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 90 },
/* MT_TSKELSD */ { P_("monster", "Corpse Captain"), "SkelSd\\SklSr", "Monsters\\SkelSd\\SklSr%c%i.WAV", "Monsters\\SkelSd\\Skelt.TRN", MonsterAvailability::Always, 128, 575, true, false, true, { 13, 8, 12, 7, 15, 16 }, { 4, 1, 1, 1, 1, 1 }, 2, 4, 4, 12, 20, AI_SKELSD, 0 , 1, 30, 8, 3, 9, 0, 0, 0, 0, 5, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 200 },
/* MT_RSKELSD */ { P_("monster", "Burning Dead Captain"), "SkelSd\\SklSr", "Monsters\\SkelSd\\SklSr%c%i.WAV", nullptr, MonsterAvailability::Always, 128, 575, true, false, false, { 13, 8, 12, 7, 15, 16 }, { 4, 1, 1, 1, 1, 1 }, 3, 5, 6, 16, 30, AI_SKELSD, 0 , 2, 35, 8, 4, 10, 0, 0, 0, 0, 15, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , 3, 0, 393 },
/* MT_XSKELSD */ { P_("monster", "Horror Captain"), "SkelSd\\SklSr", "Monsters\\SkelSd\\SklSr%c%i.WAV", "Monsters\\SkelSd\\Black.TRN", MonsterAvailability::Always, 128, 575, true, false, true, { 13, 8, 12, 7, 15, 16 }, { 4, 1, 1, 1, 1, 1 }, 4, 6, 8, 35, 50, AI_SKELSD, MFLAG_SEARCH , 3, 40, 8, 5, 14, 0, 0, 0, 0, 30, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 604 },
/* MT_INVILORD*/ { P_("monster", "Invisible Lord"), "TSneak\\TSneak", "Monsters\\TSneak\\Sneakl%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 800, false, false, false, { 13, 13, 15, 11, 16, 0 }, { 2, 1, 1, 1, 1, 1 }, 19, 20, 14, 278, 278, AI_SKELSD, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 65, 8, 16, 30, 0, 0, 0, 0, 60, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 2000 },
/* MT_SNEAK */ { P_("monster", "Hidden"), "Sneak\\Sneak", "Monsters\\Sneak\\Sneak%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 992, true, false, false, { 16, 8, 12, 8, 24, 15 }, { 2, 1, 1, 1, 1, 1 }, 2, 5, 5, 8, 24, AI_SNEAK, MFLAG_HIDDEN , 0, 35, 8, 3, 6, 0, 0, 0, 0, 25, MonsterClass::Demon, 0 , IMMUNE_NULL_40 , 3, 0, 278 },
/* MT_STALKER */ { P_("monster", "Stalker"), "Sneak\\Sneak", "Monsters\\Sneak\\Sneak%c%i.WAV", "Monsters\\Sneak\\Sneakv2.TRN", MonsterAvailability::Retail, 128, 992, true, false, true, { 16, 8, 12, 8, 24, 15 }, { 2, 1, 1, 1, 1, 1 }, 5, 7, 9, 30, 45, AI_SNEAK, MFLAG_HIDDEN | MFLAG_SEARCH , 1, 40, 8, 8, 16, 0, 0, 0, 0, 30, MonsterClass::Demon, 0 , IMMUNE_NULL_40 , 3, 0, 630 },
/* MT_UNSEEN */ { P_("monster", "Unseen"), "Sneak\\Sneak", "Monsters\\Sneak\\Sneak%c%i.WAV", "Monsters\\Sneak\\Sneakv3.TRN", MonsterAvailability::Retail, 128, 992, true, false, true, { 16, 8, 12, 8, 24, 15 }, { 2, 1, 1, 1, 1, 1 }, 6, 8, 11, 35, 50, AI_SNEAK, MFLAG_HIDDEN | MFLAG_SEARCH , 2, 45, 8, 12, 20, 0, 0, 0, 0, 30, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 935 },
/* MT_ILLWEAV */ { P_("monster", "Illusion Weaver"), "Sneak\\Sneak", "Monsters\\Sneak\\Sneak%c%i.WAV", "Monsters\\Sneak\\Sneakv1.TRN", MonsterAvailability::Retail, 128, 992, true, false, true, { 16, 8, 12, 8, 24, 15 }, { 2, 1, 1, 1, 1, 1 }, 8, 10, 13, 40, 60, AI_SNEAK, MFLAG_HIDDEN | MFLAG_SEARCH , 3, 60, 8, 16, 24, 0, 0, 0, 0, 30, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE , IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , 3, 0, 1500 },
/* MT_LRDSAYTR*/ { P_("monster", "Satyr Lord"), "GoatLord\\GoatL", "Monsters\\newsfx\\Satyr%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 800, false, false, false, { 13, 13, 14, 9, 16, 0 }, { 2, 1, 1, 1, 1, 1 }, 21, 22, 28, 160, 200, AI_SKELSD, MFLAG_SEARCH , 3, 90, 8, 20, 30, 0, 0, 0, 0, 70, MonsterClass::Animal, RESIST_FIRE | RESIST_LIGHTNING , RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 3, 0, 2800 },
/* MT_NGOATMC */ { P_("monster", "Flesh Clan"), "GoatMace\\Goat", "Monsters\\GoatMace\\Goat%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 1030, true, false, false, { 12, 8, 12, 6, 20, 12 }, { 2, 1, 1, 1, 1, 1 }, 4, 6, 8, 30, 45, AI_GOATMC, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 0, 50, 8, 4, 10, 0, 0, 0, 0, 40, MonsterClass::Demon, 0 , 0 , 3, 0, 460 },
/* MT_BGOATMC */ { P_("monster", "Stone Clan"), "GoatMace\\Goat", "Monsters\\GoatMace\\Goat%c%i.WAV", "Monsters\\GoatMace\\Beige.TRN", MonsterAvailability::Retail, 128, 1030, true, false, true, { 12, 8, 12, 6, 20, 12 }, { 2, 1, 1, 1, 1, 1 }, 5, 7, 10, 40, 55, AI_GOATMC, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 1, 60, 8, 6, 12, 0, 0, 0, 0, 40, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 685 },
/* MT_RGOATMC */ { P_("monster", "Fire Clan"), "GoatMace\\Goat", "Monsters\\GoatMace\\Goat%c%i.WAV", "Monsters\\GoatMace\\Red.TRN", MonsterAvailability::Retail, 128, 1030, true, false, true, { 12, 8, 12, 6, 20, 12 }, { 2, 1, 1, 1, 1, 1 }, 6, 8, 12, 50, 65, AI_GOATMC, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 70, 8, 8, 16, 0, 0, 0, 0, 45, MonsterClass::Demon, RESIST_FIRE , IMMUNE_FIRE , 3, 0, 906 },
/* MT_GGOATMC */ { P_("monster", "Night Clan"), "GoatMace\\Goat", "Monsters\\GoatMace\\Goat%c%i.WAV", "Monsters\\GoatMace\\Gray.TRN", MonsterAvailability::Retail, 128, 1030, true, false, true, { 12, 8, 12, 6, 20, 12 }, { 2, 1, 1, 1, 1, 1 }, 7, 9, 14, 55, 70, AI_GOATMC, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 80, 8, 10, 20, 15, 0, 30, 30, 50, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 1190 },
/* MT_FIEND */ { P_("monster", "Fiend"), "Bat\\Bat", "Monsters\\Bat\\Bat%c%i.WAV", "Monsters\\Bat\\red.trn", MonsterAvailability::Always, 96, 364, false, false, true, { 9, 13, 10, 9, 13, 0 }, { 1, 1, 1, 1, 1, 1 }, 2, 3, 3, 3, 6, AI_BAT, 0 , 0, 35, 5, 1, 6, 0, 0, 0, 0, 0, MonsterClass::Animal, 0 , 0 , 6, T_NODROP, 102 },
/* MT_BLINK */ { P_("monster", "Blink"), "Bat\\Bat", "Monsters\\Bat\\Bat%c%i.WAV", nullptr, MonsterAvailability::Always, 96, 364, false, false, false, { 9, 13, 10, 9, 13, 0 }, { 1, 1, 1, 1, 1, 1 }, 3, 5, 7, 12, 28, AI_BAT, 0 , 1, 45, 5, 1, 8, 0, 0, 0, 0, 15, MonsterClass::Animal, 0 , 0 , 6, T_NODROP, 340 },
/* MT_GLOOM */ { P_("monster", "Gloom"), "Bat\\Bat", "Monsters\\Bat\\Bat%c%i.WAV", "Monsters\\Bat\\grey.trn", MonsterAvailability::Always, 96, 364, false, false, true, { 9, 13, 10, 9, 13, 0 }, { 1, 1, 1, 1, 1, 1 }, 4, 6, 9, 28, 36, AI_BAT, MFLAG_SEARCH , 2, 70, 5, 4, 12, 0, 0, 0, 0, 35, MonsterClass::Animal, RESIST_MAGIC , RESIST_MAGIC | IMMUNE_NULL_40 , 6, T_NODROP, 509 },
/* MT_FAMILIAR*/ { P_("monster", "Familiar"), "Bat\\Bat", "Monsters\\Bat\\Bat%c%i.WAV", "Monsters\\Bat\\orange.trn", MonsterAvailability::Always, 96, 364, false, false, true, { 9, 13, 10, 9, 13, 0 }, { 1, 1, 1, 1, 1, 1 }, 6, 8, 13, 20, 35, AI_BAT, MFLAG_SEARCH , 3, 50, 5, 4, 16, 0, 0, 0, 0, 35, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_LIGHTNING , RESIST_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 6, T_NODROP, 448 },
/* MT_NGOATBW */ { P_("monster", "Flesh Clan"), "GoatBow\\GoatB", "Monsters\\GoatBow\\GoatB%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 1040, false, false, false, { 12, 8, 16, 6, 20, 0 }, { 3, 1, 1, 1, 1, 1 }, 4, 6, 8, 20, 35, AI_GOATBOW, MFLAG_CAN_OPEN_DOOR, 0, 35, 13, 1, 7, 0, 0, 0, 0, 35, MonsterClass::Demon, 0 , 0 , 3, 0, 448 },
/* MT_BGOATBW */ { P_("monster", "Stone Clan"), "GoatBow\\GoatB", "Monsters\\GoatBow\\GoatB%c%i.WAV", "Monsters\\GoatBow\\Beige.TRN", MonsterAvailability::Retail, 128, 1040, false, false, true, { 12, 8, 16, 6, 20, 0 }, { 3, 1, 1, 1, 1, 1 }, 5, 7, 10, 30, 40, AI_GOATBOW, MFLAG_CAN_OPEN_DOOR, 1, 40, 13, 2, 9, 0, 0, 0, 0, 35, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 645 },
/* MT_RGOATBW */ { P_("monster", "Fire Clan"), "GoatBow\\GoatB", "Monsters\\GoatBow\\GoatB%c%i.WAV", "Monsters\\GoatBow\\Red.TRN", MonsterAvailability::Retail, 128, 1040, false, false, true, { 12, 8, 16, 6, 20, 0 }, { 3, 1, 1, 1, 1, 1 }, 6, 8, 12, 40, 50, AI_GOATBOW, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 45, 13, 3, 11, 0, 0, 0, 0, 35, MonsterClass::Demon, RESIST_FIRE , IMMUNE_FIRE , 3, 0, 822 },
/* MT_GGOATBW */ { P_("monster", "Night Clan"), "GoatBow\\GoatB", "Monsters\\GoatBow\\GoatB%c%i.WAV", "Monsters\\GoatBow\\Gray.TRN", MonsterAvailability::Retail, 128, 1040, false, false, true, { 12, 8, 16, 6, 20, 0 }, { 3, 1, 1, 1, 1, 1 }, 7, 9, 14, 50, 65, AI_GOATBOW, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 50, 13, 4, 13, 15, 0, 0, 0, 40, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 3, 0, 1092 },
/* MT_NACID */ { P_("monster", "Acid Beast"), "Acid\\Acid", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 716, true, true, false, { 13, 8, 12, 8, 16, 12 }, { 1, 1, 1, 1, 1, 1 }, 6, 8, 11, 40, 66, AI_ACID, 0 , 0, 40, 8, 4, 12, 25, 8, 0, 0, 30, MonsterClass::Animal, IMMUNE_ACID , IMMUNE_MAGIC | IMMUNE_ACID , 3, 0, 846 },
/* MT_RACID */ { P_("monster", "Poison Spitter"), "Acid\\Acid", "Monsters\\Acid\\Acid%c%i.WAV", "Monsters\\Acid\\AcidBlk.TRN", MonsterAvailability::Retail, 128, 716, true, true, true, { 13, 8, 12, 8, 16, 12 }, { 1, 1, 1, 1, 1, 1 }, 8, 10, 15, 60, 85, AI_ACID, 0 , 1, 45, 8, 4, 16, 25, 8, 0, 0, 30, MonsterClass::Animal, IMMUNE_ACID , IMMUNE_MAGIC | IMMUNE_ACID , 3, 0, 1248 },
/* MT_BACID */ { P_("monster", "Pit Beast"), "Acid\\Acid", "Monsters\\Acid\\Acid%c%i.WAV", "Monsters\\Acid\\AcidB.TRN", MonsterAvailability::Retail, 128, 716, true, true, true, { 13, 8, 12, 8, 16, 12 }, { 1, 1, 1, 1, 1, 1 }, 10, 12, 21, 80, 110, AI_ACID, 0 , 2, 55, 8, 8, 18, 35, 8, 0, 0, 35, MonsterClass::Animal, RESIST_MAGIC | IMMUNE_ACID , IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_ACID , 3, 0, 2060 },
/* MT_XACID */ { P_("monster", "Lava Maw"), "Acid\\Acid", "Monsters\\Acid\\Acid%c%i.WAV", "Monsters\\Acid\\AcidR.TRN", MonsterAvailability::Retail, 128, 716, true, true, true, { 13, 8, 12, 8, 16, 12 }, { 1, 1, 1, 1, 1, 1 }, 12, 14, 25, 100, 150, AI_ACID, 0 , 3, 65, 8, 10, 20, 40, 8, 0, 0, 35, MonsterClass::Animal, RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_ACID , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_ACID , 3, 0, 2940 },
/* MT_SKING */ { P_("monster", "Skeleton King"), "SKing\\SKing", "Monsters\\SKing\\SKing%c%i.WAV", "Monsters\\SkelAxe\\White.TRN", MonsterAvailability::Never, 160, 1010, true, true, true, { 8, 6, 16, 6, 16, 6 }, { 2, 1, 1, 1, 1, 2 }, 4, 4, 9, 140, 140, AI_SKELKING, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 60, 8, 6, 16, 0, 0, 0, 0, 70, MonsterClass::Undead, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7,T_UNIQ+UITEM_SKCROWN, 570 },
/* MT_CLEAVER */ { P_("monster", "The Butcher"), "FatC\\FatC", "Monsters\\FatC\\FatC%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 980, false, false, false, { 10, 8, 12, 6, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 1, 1, 1, 320, 320, AI_CLEAVER, 0 , 3, 50, 8, 6, 12, 0, 0, 0, 0, 50, MonsterClass::Demon, RESIST_FIRE | RESIST_LIGHTNING , RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 3,T_UNIQ+UITEM_CLEAVER, 710 },
/* MT_FAT */ { P_("monster", "Overlord"), "Fat\\Fat", "Monsters\\Fat\\Fat%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 1130, true, false, false, { 8, 10, 15, 6, 16, 10 }, { 4, 1, 1, 1, 1, 1 }, 5, 7, 10, 60, 80, AI_FAT, 0 , 0, 55, 8, 6, 12, 0, 0, 0, 0, 55, MonsterClass::Demon, 0 , RESIST_FIRE , 3, 0, 635 },
/* MT_MUDMAN, */ { P_("monster", "Mud Man"), "Fat\\Fat", "Monsters\\Fat\\Fat%c%i.WAV", "Monsters\\Fat\\Blue.TRN", MonsterAvailability::Retail, 128, 1130, true, false, true, { 8, 10, 15, 6, 16, 10 }, { 4, 1, 1, 1, 1, 1 }, 7, 9, 14, 100, 125, AI_FAT, MFLAG_SEARCH , 1, 60, 8, 8, 16, 0, 0, 0, 0, 60, MonsterClass::Demon, 0 , IMMUNE_LIGHTNING , 3, 0, 1165 },
/* MT_TOAD */ { P_("monster", "Toad Demon"), "Fat\\Fat", "Monsters\\Fat\\Fat%c%i.WAV", "Monsters\\Fat\\FatB.TRN", MonsterAvailability::Retail, 128, 1130, true, false, true, { 8, 10, 15, 6, 16, 10 }, { 4, 1, 1, 1, 1, 1 }, 8, 10, 16, 135, 160, AI_FAT, MFLAG_SEARCH , 2, 70, 8, 8, 16, 40, 0, 8, 20, 65, MonsterClass::Demon, IMMUNE_MAGIC , IMMUNE_MAGIC | RESIST_LIGHTNING , 3, 0, 1380 },
/* MT_FLAYED */ { P_("monster", "Flayed One"), "Fat\\Fat", "Monsters\\Fat\\Fat%c%i.WAV", "Monsters\\Fat\\FatF.TRN", MonsterAvailability::Retail, 128, 1130, true, false, true, { 8, 10, 15, 6, 16, 10 }, { 4, 1, 1, 1, 1, 1 }, 10, 12, 20, 160, 200, AI_FAT, MFLAG_SEARCH , 3, 85, 8, 10, 20, 0, 0, 0, 0, 70, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 3, 0, 2058 },
/* MT_WYRM */ { P_("monster", "Wyrm"), "Worm\\Worm", "Monsters\\Fat\\Fat%c%i.WAV", nullptr, MonsterAvailability::Never, 160, 2420, false, false, false, { 13, 13, 13, 11, 19, 0 }, { 1, 1, 1, 1, 1, 1 }, 5, 7, 11, 60, 90, AI_SKELSD, 0 , 0, 40, 8, 4, 10, 0, 0, 0, 0, 25, MonsterClass::Animal, RESIST_MAGIC , RESIST_MAGIC , 3, 0, 660 },
/* MT_CAVSLUG */ { P_("monster", "Cave Slug"), "Worm\\Worm", "Monsters\\Fat\\Fat%c%i.WAV", nullptr, MonsterAvailability::Never, 160, 2420, false, false, false, { 13, 13, 13, 11, 19, 0 }, { 1, 1, 1, 1, 1, 1 }, 6, 8, 13, 75, 110, AI_SKELSD, 0 , 1, 50, 8, 6, 13, 0, 0, 0, 0, 30, MonsterClass::Animal, RESIST_MAGIC , RESIST_MAGIC , 3, 0, 994 },
/* MT_DVLWYRM */ { P_("monster", "Devil Wyrm"), "Worm\\Worm", "Monsters\\Fat\\Fat%c%i.WAV", nullptr, MonsterAvailability::Never, 160, 2420, false, false, false, { 13, 13, 13, 11, 19, 0 }, { 1, 1, 1, 1, 1, 1 }, 7, 9, 15, 100, 140, AI_SKELSD, 0 , 2, 55, 8, 8, 16, 0, 0, 0, 0, 30, MonsterClass::Animal, RESIST_MAGIC | RESIST_FIRE , RESIST_MAGIC | RESIST_FIRE , 3, 0, 1320 },
/* MT_DEVOUR */ { P_("monster", "Devourer"), "Worm\\Worm", "Monsters\\Fat\\Fat%c%i.WAV", nullptr, MonsterAvailability::Never, 160, 2420, false, false, false, { 13, 13, 13, 11, 19, 0 }, { 1, 1, 1, 1, 1, 1 }, 8, 10, 17, 125, 200, AI_SKELSD, 0 , 3, 60, 8, 10, 20, 0, 0, 0, 0, 35, MonsterClass::Animal, RESIST_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , RESIST_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , 3, 0, 1827 },
/* MT_NMAGMA */ { P_("monster", "Magma Demon"), "Magma\\Magma", "Monsters\\Magma\\Magma%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 1680, true, true, false, { 8, 10, 14, 7, 18, 18 }, { 2, 1, 1, 1, 1, 1 }, 8, 9, 13, 50, 70, AI_MAGMA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 0, 45, 4, 2, 10, 50, 13, 0, 0, 45, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 7, 0, 1076 },
/* MT_YMAGMA */ { P_("monster", "Blood Stone"), "Magma\\Magma", "Monsters\\Magma\\Magma%c%i.WAV", "Monsters\\Magma\\Yellow.TRN", MonsterAvailability::Retail, 128, 1680, true, true, true, { 8, 10, 14, 7, 18, 18 }, { 2, 1, 1, 1, 1, 1 }, 8, 10, 14, 55, 75, AI_MAGMA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 1, 50, 4, 2, 12, 50, 14, 0, 0, 45, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 7, 0, 1309 },
/* MT_BMAGMA */ { P_("monster", "Hell Stone"), "Magma\\Magma", "Monsters\\Magma\\Magma%c%i.WAV", "Monsters\\Magma\\Blue.TRN", MonsterAvailability::Retail, 128, 1680, true, true, true, { 8, 10, 14, 7, 18, 18 }, { 2, 1, 1, 1, 1, 1 }, 9, 11, 16, 60, 80, AI_MAGMA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 60, 4, 2, 20, 60, 14, 0, 0, 50, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 7, 0, 1680 },
/* MT_WMAGMA */ { P_("monster", "Lava Lord"), "Magma\\Magma", "Monsters\\Magma\\Magma%c%i.WAV", "Monsters\\Magma\\Wierd.TRN", MonsterAvailability::Retail, 128, 1680, true, true, true, { 8, 10, 14, 7, 18, 18 }, { 2, 1, 1, 1, 1, 1 }, 9, 11, 18, 70, 85, AI_MAGMA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 75, 4, 4, 24, 60, 14, 0, 0, 60, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 7, 0, 2124 },
/* MT_HORNED */ { P_("monster", "Horned Demon"), "Rhino\\Rhino", "Monsters\\Rhino\\Rhino%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 1630, true, true, false, { 8, 8, 14, 6, 16, 6 }, { 2, 1, 1, 1, 1, 1 }, 7, 9, 13, 40, 80, AI_RHINO, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 0, 60, 7, 2, 16, 100, 0, 5, 32, 40, MonsterClass::Animal, 0 , RESIST_FIRE , 7, 0, 1172 },
/* MT_MUDRUN */ { P_("monster", "Mud Runner"), "Rhino\\Rhino", "Monsters\\Rhino\\Rhino%c%i.WAV", "Monsters\\Rhino\\Orange.TRN", MonsterAvailability::Retail, 160, 1630, true, true, true, { 8, 8, 14, 6, 16, 6 }, { 2, 1, 1, 1, 1, 1 }, 8, 10, 15, 50, 90, AI_RHINO, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 1, 70, 7, 6, 18, 100, 0, 12, 36, 45, MonsterClass::Animal, 0 , RESIST_FIRE , 7, 0, 1404 },
/* MT_FROSTC */ { P_("monster", "Frost Charger"), "Rhino\\Rhino", "Monsters\\Rhino\\Rhino%c%i.WAV", "Monsters\\Rhino\\Blue.TRN", MonsterAvailability::Retail, 160, 1630, true, true, true, { 8, 8, 14, 6, 16, 6 }, { 2, 1, 1, 1, 1, 1 }, 9, 11, 17, 60, 100, AI_RHINO, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 80, 7, 8, 20, 100, 0, 20, 40, 50, MonsterClass::Animal, IMMUNE_MAGIC | RESIST_LIGHTNING , IMMUNE_MAGIC | RESIST_LIGHTNING , 7, 0, 1720 },
/* MT_OBLORD */ { P_("monster", "Obsidian Lord"), "Rhino\\Rhino", "Monsters\\Rhino\\Rhino%c%i.WAV", "Monsters\\Rhino\\RhinoB.TRN", MonsterAvailability::Retail, 160, 1630, true, true, true, { 8, 8, 14, 6, 16, 6 }, { 2, 1, 1, 1, 1, 1 }, 10, 12, 19, 70, 110, AI_RHINO, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 90, 7, 10, 22, 100, 0, 20, 50, 55, MonsterClass::Animal, IMMUNE_MAGIC | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 7, 0, 1809 },
/* MT_BONEDMN */ { P_("monster", "oldboned"), "Demskel\\Demskl", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Never, 128, 1740, true, true, false, { 10, 8, 20, 6, 24, 16 }, { 3, 1, 1, 1, 1, 1 }, 24, 24, 12, 70, 70, AI_STORM, 0 , 0, 60, 8, 6, 14, 12, 0, 0, 0, 50, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_NULL_40 , 7, 0, 1344 },
/* MT_REDDTH */ { P_("monster", "Red Death"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Never, 160, 1740, true, true, true, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 8, 10, 16, 96, 96, AI_STORM, 0 , 1, 75, 5, 10, 20, 0, 0, 0, 0, 60, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 7, 0, 2168 },
/* MT_LTCHDMN */ { P_("monster", "Litch Demon"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Never, 160, 1740, true, true, true, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 9, 11, 18, 110, 110, AI_STORM, 0 , 2, 80, 5, 10, 24, 0, 0, 0, 0, 45, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 2736 },
/* MT_UDEDBLRG*/ { P_("monster", "Undead Balrog"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Never, 160, 1740, true, true, true, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 11, 13, 22, 130, 130, AI_STORM, 0 , 3, 85, 5, 12, 30, 0, 0, 0, 0, 65, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 3575 },
/* MT_INCIN */ { P_("monster", "Incinerator"), "Fireman\\FireM", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 1460, true, false, false, { 14, 19, 20, 8, 14, 23 }, { 1, 1, 1, 1, 1, 1 }, 21, 22, 16, 30, 45, AI_FIREMAN, 0 , 0, 75, 8, 8, 16, 0, 0, 0, 0, 25, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 3, 0, 1888 },
/* MT_FLAMLRD */ { P_("monster", "Flame Lord"), "Fireman\\FireM", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 1460, true, false, false, { 14, 19, 20, 8, 14, 23 }, { 1, 1, 1, 1, 1, 1 }, 22, 23, 18, 40, 55, AI_FIREMAN, 0 , 1, 75, 8, 10, 20, 0, 0, 0, 0, 25, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 3, 0, 2250 },
/* MT_DOOMFIRE*/ { P_("monster", "Doom Fire"), "Fireman\\FireM", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 1460, true, false, false, { 14, 19, 20, 8, 14, 23 }, { 1, 1, 1, 1, 1, 1 }, 23, 24, 20, 50, 65, AI_FIREMAN, 0 , 2, 80, 8, 12, 24, 0, 0, 0, 0, 30, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , 3, 0, 2740 },
/* MT_HELLBURN*/ { P_("monster", "Hell Burner"), "Fireman\\FireM", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 1460, true, false, false, { 14, 19, 20, 8, 14, 23 }, { 1, 1, 1, 1, 1, 1 }, 24, 24, 22, 60, 80, AI_FIREMAN, 0 , 3, 85, 8, 15, 30, 0, 0, 0, 0, 30, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , 3, 0, 3355 },
/* MT_STORM */ { P_("monster", "Red Storm"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Retail, 160, 1740, true, true, true, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 9, 11, 18, 55, 110, AI_STORM, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 0, 80, 5, 8, 18, 75, 8, 4, 16, 30, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_LIGHTNING , 7, 0, 2160 },
/* MT_RSTORM */ { P_("monster", "Storm Rider"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 1740, true, true, false, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 10, 12, 20, 60, 120, AI_STORM, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 1, 80, 5, 8, 18, 80, 8, 4, 16, 30, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_LIGHTNING , IMMUNE_MAGIC | IMMUNE_LIGHTNING , 7, 0, 2391 },
/* MT_STORML */ { P_("monster", "Storm Lord"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv2.TRN", MonsterAvailability::Retail, 160, 1740, true, true, true, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 11, 13, 22, 75, 135, AI_STORM, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 85, 5, 12, 24, 75, 8, 4, 16, 35, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_LIGHTNING , IMMUNE_MAGIC | IMMUNE_LIGHTNING , 7, 0, 2775 },
/* MT_MAEL */ { P_("monster", "Maelstrom"), "Thin\\Thin", "Monsters\\Thin\\Thin%c%i.WAV", "Monsters\\Thin\\Thinv1.TRN", MonsterAvailability::Retail, 160, 1740, true, true, true, { 8, 8, 18, 4, 17, 14 }, { 3, 1, 1, 1, 1, 1 }, 12, 14, 24, 90, 150, AI_STORM, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 90, 5, 12, 28, 75, 8, 4, 16, 40, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 3177 },
/* MT_BIGFALL */ { P_("monster", "Devil Kin Brute"), "BigFall\\Fallg", "Monsters\\newsfx\\KBrute%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 800, true, false, false, { 10, 8, 11, 8, 17, 0 }, { 1, 1, 1, 1, 2, 2 }, 21, 22, 27, 120, 160, AI_SKELSD, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 100, 6, 18, 24, 0, 0, 0, 0, 70, MonsterClass::Animal, RESIST_FIRE | RESIST_LIGHTNING , RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , 3, 0, 2400 },
/* MT_WINGED */ { P_("monster", "Winged-Demon"), "Gargoyle\\Gargo", "Monsters\\Gargoyle\\Gargo%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 1650, true, false, false, { 14, 14, 14, 10, 18, 14 }, { 1, 1, 1, 1, 1, 2 }, 5, 7, 9, 45, 60, AI_GARG, MFLAG_CAN_OPEN_DOOR, 0, 50, 7, 10, 16, 0, 0, 0, 0, 45, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , 6, 0, 662 },
/* MT_GARGOYLE*/ { P_("monster", "Gargoyle"), "Gargoyle\\Gargo", "Monsters\\Gargoyle\\Gargo%c%i.WAV", "Monsters\\Gargoyle\\GarE.TRN", MonsterAvailability::Retail, 160, 1650, true, false, true, { 14, 14, 14, 10, 18, 14 }, { 1, 1, 1, 1, 1, 2 }, 7, 9, 13, 60, 90, AI_GARG, MFLAG_CAN_OPEN_DOOR, 1, 65, 7, 10, 16, 0, 0, 0, 0, 45, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 6, 0, 1205 },
/* MT_BLOODCLW*/ { P_("monster", "Blood Claw"), "Gargoyle\\Gargo", "Monsters\\Gargoyle\\Gargo%c%i.WAV", "Monsters\\Gargoyle\\GargBr.TRN", MonsterAvailability::Retail, 160, 1650, true, false, true, { 14, 14, 14, 10, 18, 14 }, { 1, 1, 1, 1, 1, 1 }, 9, 11, 19, 75, 125, AI_GARG, MFLAG_CAN_OPEN_DOOR, 2, 80, 7, 14, 22, 0, 0, 0, 0, 50, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 6, 0, 1873 },
/* MT_DEATHW */ { P_("monster", "Death Wing"), "Gargoyle\\Gargo", "Monsters\\Gargoyle\\Gargo%c%i.WAV", "Monsters\\Gargoyle\\GargB.TRN", MonsterAvailability::Retail, 160, 1650, true, false, true, { 14, 14, 14, 10, 18, 14 }, { 1, 1, 1, 1, 1, 1 }, 10, 12, 23, 90, 150, AI_GARG, MFLAG_CAN_OPEN_DOOR, 3, 95, 7, 16, 28, 0, 0, 0, 0, 60, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 6, 0, 2278 },
/* MT_MEGA */ { P_("monster", "Slayer"), "Mega\\Mega", "Monsters\\Mega\\Mega%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 2220, true, true, false, { 6, 7, 14, 1, 24, 5 }, { 3, 1, 1, 1, 2, 1 }, 10, 12, 20, 120, 140, AI_MEGA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 0, 100, 8, 12, 20, 0, 3, 0, 0, 60, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE , RESIST_MAGIC | IMMUNE_FIRE , 7, 0, 2300 },
/* MT_GUARD */ { P_("monster", "Guardian"), "Mega\\Mega", "Monsters\\Mega\\Mega%c%i.WAV", "Monsters\\Mega\\Guard.TRN", MonsterAvailability::Retail, 160, 2220, true, true, true, { 6, 7, 14, 1, 24, 5 }, { 3, 1, 1, 1, 2, 1 }, 11, 13, 22, 140, 160, AI_MEGA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 1, 110, 8, 14, 22, 0, 3, 0, 0, 65, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE , RESIST_MAGIC | IMMUNE_FIRE , 7, 0, 2714 },
/* MT_VTEXLRD */ { P_("monster", "Vortex Lord"), "Mega\\Mega", "Monsters\\Mega\\Mega%c%i.WAV", "Monsters\\Mega\\Vtexl.TRN", MonsterAvailability::Retail, 160, 2220, true, true, true, { 6, 7, 14, 1, 24, 5 }, { 3, 1, 1, 1, 2, 1 }, 12, 14, 24, 160, 180, AI_MEGA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 120, 8, 18, 24, 0, 3, 0, 0, 70, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 3252 },
/* MT_BALROG */ { P_("monster", "Balrog"), "Mega\\Mega", "Monsters\\Mega\\Mega%c%i.WAV", "Monsters\\Mega\\Balr.TRN", MonsterAvailability::Retail, 160, 2220, true, true, true, { 6, 7, 14, 1, 24, 5 }, { 3, 1, 1, 1, 2, 1 }, 13, 15, 26, 180, 200, AI_MEGA, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 130, 8, 22, 30, 0, 3, 0, 0, 75, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 3643 },
/* MT_NSNAKE */ { P_("monster", "Cave Viper"), "Snake\\Snake", "Monsters\\Snake\\Snake%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 1270, false, false, false, { 12, 11, 13, 5, 18, 0 }, { 2, 1, 1, 1, 1, 1 }, 11, 13, 21, 100, 150, AI_SNAKE, MFLAG_SEARCH , 0, 90, 8, 8, 20, 0, 0, 0, 0, 60, MonsterClass::Demon, IMMUNE_MAGIC , IMMUNE_MAGIC , 7, 0, 2725 },
/* MT_RSNAKE */ { P_("monster", "Fire Drake"), "Snake\\Snake", "Monsters\\Snake\\Snake%c%i.WAV", "Monsters\\Snake\\SnakR.TRN", MonsterAvailability::Retail, 160, 1270, false, false, true, { 12, 11, 13, 5, 18, 0 }, { 2, 1, 1, 1, 1, 1 }, 12, 14, 23, 120, 170, AI_SNAKE, MFLAG_SEARCH , 1, 105, 8, 12, 24, 0, 0, 0, 0, 65, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE , IMMUNE_MAGIC | IMMUNE_FIRE , 7, 0, 3139 },
/* MT_BSNAKE */ { P_("monster", "Gold Viper"), "Snake\\Snake", "Monsters\\Snake\\Snake%c%i.WAV", "Monsters\\Snake\\Snakg.TRN", MonsterAvailability::Retail, 160, 1270, false, false, true, { 12, 11, 13, 5, 18, 0 }, { 2, 1, 1, 1, 1, 1 }, 13, 14, 25, 140, 180, AI_SNAKE, MFLAG_SEARCH , 2, 120, 8, 15, 26, 0, 0, 0, 0, 70, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_LIGHTNING , IMMUNE_MAGIC | RESIST_LIGHTNING , 7, 0, 3540 },
/* MT_GSNAKE */ { P_("monster", "Azure Drake"), "Snake\\Snake", "Monsters\\Snake\\Snake%c%i.WAV", "Monsters\\Snake\\Snakb.TRN", MonsterAvailability::Retail, 160, 1270, false, false, true, { 12, 11, 13, 5, 18, 0 }, { 2, 1, 1, 1, 1, 1 }, 15, 16, 27, 160, 200, AI_SNAKE, MFLAG_SEARCH , 3, 130, 8, 18, 30, 0, 0, 0, 0, 75, MonsterClass::Demon, RESIST_FIRE | RESIST_LIGHTNING , IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING , 7, 0, 3791 },
/* MT_NBLACK */ { P_("monster", "Black Knight"), "Black\\Black", "Monsters\\Black\\Black%c%i.WAV", nullptr, MonsterAvailability::Retail, 160, 2120, false, false, false, { 8, 8, 16, 4, 24, 0 }, { 2, 1, 1, 1, 1, 1 }, 12, 14, 24, 150, 150, AI_SKELSD, MFLAG_SEARCH , 0, 110, 8, 15, 20, 0, 0, 0, 0, 75, MonsterClass::Demon, RESIST_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , RESIST_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 3360 },
/* MT_RTBLACK */ { P_("monster", "Doom Guard"), "Black\\Black", "Monsters\\Black\\Black%c%i.WAV", "Monsters\\Black\\BlkKntRT.TRN", MonsterAvailability::Retail, 160, 2120, false, false, true, { 8, 8, 16, 4, 24, 0 }, { 2, 1, 1, 1, 1, 1 }, 13, 15, 26, 165, 165, AI_SKELSD, MFLAG_SEARCH , 0, 130, 8, 18, 25, 0, 0, 0, 0, 75, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | IMMUNE_NULL_40 , RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40 , 7, 0, 3650 },
/* MT_BTBLACK */ { P_("monster", "Steel Lord"), "Black\\Black", "Monsters\\Black\\Black%c%i.WAV", "Monsters\\Black\\BlkKntBT.TRN", MonsterAvailability::Retail, 160, 2120, false, false, true, { 8, 8, 16, 4, 24, 0 }, { 2, 1, 1, 1, 1, 1 }, 14, 16, 28, 180, 180, AI_SKELSD, MFLAG_SEARCH , 1, 120, 8, 20, 30, 0, 0, 0, 0, 80, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 4252 },
/* MT_RBLACK */ { P_("monster", "Blood Knight"), "Black\\Black", "Monsters\\Black\\Black%c%i.WAV", "Monsters\\Black\\BlkKntBe.TRN", MonsterAvailability::Retail, 160, 2120, false, false, true, { 8, 8, 16, 4, 24, 0 }, { 2, 1, 1, 1, 1, 1 }, 13, 14, 30, 200, 200, AI_SKELSD, MFLAG_SEARCH , 1, 130, 8, 25, 35, 0, 0, 0, 0, 85, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 5130 },
/* MT_UNRAV */ { P_("monster", "The Shredded"), "Unrav\\Unrav", "Monsters\\newsfx\\Shred%c%i.WAV", nullptr, MonsterAvailability::Retail, 96, 484, false, false, false, { 10, 10, 12, 5, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 17, 18, 23, 70, 90, AI_SKELSD, 0 , 0, 75, 7, 4, 12, 0, 0, 0, 0, 65, MonsterClass::Undead, RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 900 },
/* MT_HOLOWONE*/ { P_("monster", "Hollow One"), "Unrav\\Unrav", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 96, 484, false, false, false, { 10, 10, 12, 5, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 18, 19, 27, 135, 240, AI_SKELSD, 0 , 1, 75, 7, 12, 24, 0, 0, 0, 0, 75, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 4374 },
/* MT_PAINMSTR*/ { P_("monster", "Pain Master"), "Unrav\\Unrav", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 96, 484, false, false, false, { 10, 10, 12, 5, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 19, 20, 29, 110, 200, AI_SKELSD, 0 , 2, 80, 7, 16, 30, 0, 0, 0, 0, 80, MonsterClass::Undead, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 5147 },
/* MT_REALWEAV*/ { P_("monster", "Reality Weaver"), "Unrav\\Unrav", "Monsters\\Acid\\Acid%c%i.WAV", nullptr, MonsterAvailability::Never, 96, 484, false, false, false, { 10, 10, 12, 5, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 20, 20, 30, 135, 240, AI_SKELSD, 0 , 3, 85, 7, 20, 35, 0, 0, 0, 0, 85, MonsterClass::Undead, RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 5925 },
/* MT_SUCCUBUS*/ { P_("monster", "Succubus"), "Succ\\Scbs", "Monsters\\Succ\\Scbs%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 980, false, false, false, { 14, 8, 16, 7, 24, 0 }, { 1, 1, 1, 1, 1, 1 }, 12, 14, 24, 120, 150, AI_SUCC, MFLAG_CAN_OPEN_DOOR, 0, 100, 10, 1, 20, 0, 0, 0, 0, 60, MonsterClass::Demon, RESIST_MAGIC , IMMUNE_MAGIC | RESIST_FIRE , 3, 0, 3696 },
/* MT_SNOWWICH*/ { P_("monster", "Snow Witch"), "Succ\\Scbs", "Monsters\\Succ\\Scbs%c%i.WAV", "Monsters\\Succ\\Succb.TRN", MonsterAvailability::Retail, 128, 980, false, false, true, { 14, 8, 16, 7, 24, 0 }, { 1, 1, 1, 1, 1, 1 }, 13, 15, 26, 135, 175, AI_SUCC, MFLAG_CAN_OPEN_DOOR, 1, 110, 10, 1, 24, 0, 0, 0, 0, 65, MonsterClass::Demon, RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 4084 },
/* MT_HLSPWN */ { P_("monster", "Hell Spawn"), "Succ\\Scbs", "Monsters\\Succ\\Scbs%c%i.WAV", "Monsters\\Succ\\Succrw.TRN", MonsterAvailability::Retail, 128, 980, false, false, true, { 14, 8, 16, 7, 24, 0 }, { 1, 1, 1, 1, 1, 1 }, 14, 16, 28, 150, 200, AI_SUCC, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 2, 115, 10, 1, 30, 0, 0, 0, 0, 75, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , 3, 0, 4480 },
/* MT_SOLBRNR */ { P_("monster", "Soul Burner"), "Succ\\Scbs", "Monsters\\Succ\\Scbs%c%i.WAV", "Monsters\\Succ\\Succbw.TRN", MonsterAvailability::Retail, 128, 980, false, false, true, { 14, 8, 16, 7, 24, 0 }, { 1, 1, 1, 1, 1, 1 }, 15, 16, 30, 140, 225, AI_SUCC, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 120, 10, 1, 35, 0, 0, 0, 0, 85, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 3, 0, 4644 },
/* MT_COUNSLR */ { P_("monster", "Counselor"), "Mage\\Mage", "Monsters\\Mage\\Mage%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 2000, true, false, false, { 12, 1, 20, 8, 28, 20 }, { 1, 1, 1, 1, 1, 1 }, 13, 14, 25, 70, 70, AI_COUNSLR, MFLAG_CAN_OPEN_DOOR, 0, 90, 8, 8, 20, 0, 0, 0, 0, 0, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , 7, 0, 4070 },
/* MT_MAGISTR */ { P_("monster", "Magistrate"), "Mage\\Mage", "Monsters\\Mage\\Mage%c%i.WAV", "Monsters\\Mage\\Cnselg.TRN", MonsterAvailability::Retail, 128, 2000, true, false, true, { 12, 1, 20, 8, 28, 20 }, { 1, 1, 1, 1, 1, 1 }, 14, 15, 27, 85, 85, AI_COUNSLR, MFLAG_CAN_OPEN_DOOR, 1, 100, 8, 10, 24, 0, 0, 0, 0, 0, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 4478 },
/* MT_CABALIST*/ { P_("monster", "Cabalist"), "Mage\\Mage", "Monsters\\Mage\\Mage%c%i.WAV", "Monsters\\Mage\\Cnselgd.TRN", MonsterAvailability::Retail, 128, 2000, true, false, true, { 12, 1, 20, 8, 28, 20 }, { 1, 1, 1, 1, 1, 1 }, 15, 16, 29, 120, 120, AI_COUNSLR, MFLAG_CAN_OPEN_DOOR, 2, 110, 8, 14, 30, 0, 0, 0, 0, 0, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 4929 },
/* MT_ADVOCATE*/ { P_("monster", "Advocate"), "Mage\\Mage", "Monsters\\Mage\\Mage%c%i.WAV", "Monsters\\Mage\\Cnselbk.TRN", MonsterAvailability::Retail, 128, 2000, true, false, true, { 12, 1, 20, 8, 28, 20 }, { 1, 1, 1, 1, 1, 1 }, 16, 16, 30, 145, 145, AI_COUNSLR, MFLAG_CAN_OPEN_DOOR, 3, 120, 8, 15, 25, 0, 0, 0, 0, 0, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 4968 },
/* MT_GOLEM */ { P_("monster", "Golem"), "Golem\\Golem", "Monsters\\Golem\\Golm%c%i.WAV", nullptr, MonsterAvailability::Never, 96, 386, true, false, false, { 0, 16, 12, 0, 12, 20 }, { 1, 1, 1, 1, 1, 1 }, 1, 1, 12, 1, 1, AI_GOLUM, MFLAG_CAN_OPEN_DOOR, 0, 0, 7, 1, 1, 0, 0, 0, 0, 1, MonsterClass::Demon, 0 , 0 , 0, 0, 0 },
/* MT_DIABLO */ { P_("monster", "The Dark Lord"), "Diablo\\Diablo", "Monsters\\Diablo\\Diablo%c%i.WAV", nullptr, MonsterAvailability::Never, 160, 2000, true, true, false, { 16, 6, 16, 6, 16, 16 }, { 1, 1, 1, 1, 1, 1 }, 26, 26, 45, 3333, 3333, AI_DIABLO, MFLAG_KNOCKBACK | MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 220, 4, 30, 60, 0, 11, 0, 0, 90, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 31666 },
/* MT_DARKMAGE*/ { P_("monster", "The Arch-Litch Malignus"), "DarkMage\\Dmage", "Monsters\\DarkMage\\Dmag%c%i.WAV", nullptr, MonsterAvailability::Never, 128, 1060, true, false, false, { 6, 1, 21, 6, 23, 18 }, { 1, 1, 1, 1, 1, 1 }, 21, 21, 30, 160, 160, AI_COUNSLR, MFLAG_CAN_OPEN_DOOR, 3, 120, 8, 20, 40, 0, 0, 0, 0, 70, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 4968 },
/* MT_HELLBOAR*/ { P_("monster", "Hellboar"), "Fork\\Fork", "Monsters\\newsfx\\HBoar%c%i.WAV", nullptr, MonsterAvailability::Retail, 188, 800, false, false, false, { 10, 10, 15, 6, 16, 0 }, { 2, 1, 1, 1, 1, 1 }, 17, 18, 23, 80, 100, AI_SKELSD, MFLAG_KNOCKBACK | MFLAG_SEARCH , 2, 70, 7, 16, 24, 0, 0, 0, 0, 60, MonsterClass::Demon, 0 , RESIST_FIRE | RESIST_LIGHTNING , 3, 0, 750 },
/* MT_STINGER */ { P_("monster", "Stinger"), "Scorp\\Scorp", "Monsters\\newsfx\\Stingr%c%i.WAV", nullptr, MonsterAvailability::Retail, 64, 305, false, false, false, { 10, 10, 12, 6, 15, 0 }, { 2, 1, 1, 1, 1, 1 }, 17, 18, 22, 30, 40, AI_SKELSD, 0 , 3, 85, 8, 1, 20, 0, 0, 0, 0, 50, MonsterClass::Animal, 0 , RESIST_LIGHTNING , 1, 0, 500 },
/* MT_PSYCHORB*/ { P_("monster", "Psychorb"), "Eye\\Eye", "Monsters\\newsfx\\psyco%c%i.WAV", nullptr, MonsterAvailability::Retail, 156, 800, false, false, false, { 12, 13, 13, 7, 21, 0 }, { 2, 1, 1, 1, 1, 1 }, 17, 18, 22, 20, 30, AI_PSYCHORB, 0 , 3, 80, 8, 10, 10, 0, 0, 0, 0, 40, MonsterClass::Animal, 0 , RESIST_FIRE , 6, 0, 450 },
/* MT_ARACHNON*/ { P_("monster", "Arachnon"), "Spider\\Spider", "Monsters\\newsfx\\SLord%c%i.WAV", nullptr, MonsterAvailability::Retail, 148, 800, false, false, false, { 12, 10, 15, 6, 20, 0 }, { 2, 1, 1, 1, 1, 1 }, 17, 18, 22, 60, 80, AI_SKELSD, MFLAG_SEARCH , 3, 50, 8, 5, 15, 0, 0, 0, 0, 50, MonsterClass::Animal, 0 , RESIST_LIGHTNING , 7, 0, 500 },
/* MT_FELLTWIN*/ { P_("monster", "Felltwin"), "TSneak\\TSneak", "Monsters\\newsfx\\FTwin%c%i.WAV", nullptr, MonsterAvailability::Retail, 128, 800, false, false, false, { 13, 13, 15, 11, 16, 0 }, { 2, 1, 1, 1, 1, 1 }, 17, 18, 22, 50, 70, AI_SKELSD, MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 70, 8, 10, 18, 0, 0, 0, 0, 50, MonsterClass::Demon, IMMUNE_NULL_40 , RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 600 },
/* MT_HORKSPWN*/ { P_("monster", "Hork Spawn"), "Spawn\\Spawn", "Monsters\\newsfx\\HSpawn%c%i.WAV", nullptr, MonsterAvailability::Retail, 164, 520, false, true, false, { 15, 12, 14, 11, 14, 0 }, { 1, 1, 1, 1, 1, 1 }, 18, 19, 22, 30, 30, AI_SKELSD, 0 , 3, 60, 8, 10, 25, 0, 0, 0, 0, 25, MonsterClass::Demon, RESIST_MAGIC , RESIST_MAGIC , 3, 0, 250 },
/* MT_VENMTAIL*/ { P_("monster", "Venomtail"), "WScorp\\WScorp", "Monsters\\newsfx\\Stingr%c%i.WAV", nullptr, MonsterAvailability::Retail, 86, 305, false, false, false, { 10, 10, 12, 6, 15, 0 }, { 2, 1, 1, 1, 1, 1 }, 19, 20, 24, 40, 50, AI_SKELSD, 0 , 3, 85, 8, 1, 30, 0, 0, 0, 0, 60, MonsterClass::Animal, RESIST_LIGHTNING , IMMUNE_LIGHTNING , 1, 0, 1000 },
/* MT_NECRMORB*/ { P_("monster", "Necromorb"), "Eye2\\Eye2", "Monsters\\newsfx\\Psyco%c%i.WAV", nullptr, MonsterAvailability::Retail, 140, 800, false, false, false, { 12, 13, 13, 7, 21, 0 }, { 2, 1, 1, 1, 1, 1 }, 19, 20, 24, 30, 40, AI_NECROMORB, 0 , 3, 80, 8, 20, 20, 0, 0, 0, 0, 50, MonsterClass::Animal, RESIST_FIRE , IMMUNE_FIRE | RESIST_LIGHTNING , 6, 0, 1100 },
/* MT_SPIDLORD*/ { P_("monster", "Spider Lord"), "bSpidr\\bSpidr", "Monsters\\newsfx\\SLord%c%i.WAV", nullptr, MonsterAvailability::Retail, 148, 800, true, true, false, { 12, 10, 15, 6, 20, 10 }, { 2, 1, 1, 1, 1, 1 }, 19, 20, 24, 80, 100, AI_ACID, MFLAG_SEARCH , 3, 60, 8, 8, 20, 75, 8, 10, 10, 60, MonsterClass::Animal, RESIST_LIGHTNING , RESIST_FIRE | IMMUNE_LIGHTNING , 7, 0, 1250 },
/* MT_LASHWORM*/ { P_("monster", "Lashworm"), "Clasp\\Clasp", "Monsters\\newsfx\\Lworm%c%i.WAV", nullptr, MonsterAvailability::Retail, 176, 800, false, false, false, { 10, 12, 15, 6, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 19, 20, 20, 30, 30, AI_SKELSD, 0 , 3, 90, 8, 12, 20, 0, 0, 0, 0, 50, MonsterClass::Animal, 0 , RESIST_FIRE , 3, 0, 600 },
/* MT_TORCHANT*/ { P_("monster", "Torchant"), "AntWorm\\Worm", "Monsters\\newsfx\\TchAnt%c%i.WAV", nullptr, MonsterAvailability::Retail, 192, 800, false, false, false, { 14, 12, 12, 6, 20, 0 }, { 2, 1, 1, 1, 1, 1 }, 19, 20, 22, 60, 80, AI_TORCHANT, 0 , 3, 75, 8, 20, 30, 0, 0, 0, 0, 70, MonsterClass::Animal, IMMUNE_FIRE , RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , 7, 0, 1250 },
/* MT_HORKDMN */ { P_("monster", "Hork Demon"), "HorkD\\HorkD", "Monsters\\newsfx\\HDemon%c%i.WAV", nullptr, MonsterAvailability::Never, 138, 800, true, true, false, { 15, 8, 16, 6, 16, 9 }, { 2, 1, 1, 1, 1, 2 }, 19, 19, 27, 120, 160, AI_SKELSD, 0 , 3, 60, 8, 20, 35, 80, 8, 0, 0, 80, MonsterClass::Demon, RESIST_LIGHTNING , RESIST_MAGIC | IMMUNE_LIGHTNING , 7, 0, 2000 },
/* MT_DEFILER */ { P_("monster", "Hell Bug"), "Hellbug\\Hellbg", "Monsters\\newsfx\\Defile%c%i.WAV", nullptr, MonsterAvailability::Never, 198, 800, true, true, false, { 8, 8, 14, 6, 14, 12 }, { 1, 1, 1, 1, 1, 1 }, 20, 20, 30, 240, 240, AI_SKELSD, MFLAG_SEARCH , 3, 110, 8, 20, 30, 90, 8, 50, 60, 80, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING , RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 7, 0, 5000 },
/* MT_GRAVEDIG*/ { P_("monster", "Gravedigger"), "Gravdg\\Gravdg", "Monsters\\newsfx\\GDiggr%c%i.WAV", nullptr, MonsterAvailability::Retail, 124, 800, true, true, false, { 24, 24, 12, 6, 16, 16 }, { 2, 1, 1, 1, 1, 1 }, 21, 21, 26, 120, 240, AI_SCAV, MFLAG_CAN_OPEN_DOOR, 3, 80, 6, 2, 12, 0, 0, 0, 0, 20, MonsterClass::Undead, IMMUNE_LIGHTNING | IMMUNE_NULL_40 , RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 2000 },
/* MT_TOMBRAT */ { P_("monster", "Tomb Rat"), "Rat\\Rat", "Monsters\\newsfx\\TmbRat%c%i.WAV", nullptr, MonsterAvailability::Retail, 104, 550, false, false, false, { 11, 8, 12, 6, 20, 0 }, { 2, 1, 1, 1, 1, 1 }, 21, 22, 24, 80, 120, AI_SKELSD, 0 , 3, 120, 8, 12, 25, 0, 0, 0, 0, 30, MonsterClass::Animal, 0 , RESIST_FIRE | RESIST_LIGHTNING , 3, 0, 1800 },
/* MT_FIREBAT */ { P_("monster", "Firebat"), "Hellbat\\Helbat", "Monsters\\newsfx\\HelBat%c%i.WAV", nullptr, MonsterAvailability::Retail, 96, 550, false, false, false, { 18, 16, 14, 6, 18, 11 }, { 2, 1, 1, 1, 1, 1 }, 21, 22, 24, 60, 80, AI_FIREBAT, 0 , 3, 100, 8, 15, 20, 0, 0, 0, 0, 70, MonsterClass::Animal, IMMUNE_FIRE , RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , 7, 0, 2400 },
/* MT_SKLWING */ { P_("monster", "Skullwing"), "Demskel\\Demskl", "Monsters\\newsfx\\SWing%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Retail, 128, 1740, true, false, false, { 10, 8, 20, 6, 24, 16 }, { 3, 1, 1, 1, 1, 1 }, 21, 22, 27, 70, 70, AI_SKELSD, 0 , 0, 75, 7, 15, 20, 75, 9, 15, 20, 80, MonsterClass::Undead, RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 3000 },
/* MT_LICH */ { P_("monster", "Lich"), "Lich\\Lich", "Monsters\\newsfx\\Lich%c%i.WAV", nullptr, MonsterAvailability::Retail, 96, 800, false, true, false, { 12, 10, 10, 7, 21, 0 }, { 2, 1, 1, 1, 2, 1 }, 21, 22, 25, 80, 100, AI_LICH, 0 , 3, 100, 8, 15, 20, 0, 0, 0, 0, 60, MonsterClass::Undead, RESIST_LIGHTNING | IMMUNE_NULL_40 , RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 3000 },
/* MT_CRYPTDMN*/ { P_("monster", "Crypt Demon"), "Bubba\\Bubba", "Monsters\\newsfx\\Crypt%c%i.WAV", nullptr, MonsterAvailability::Retail, 154, 800, false, true, false, { 8, 18, 12, 8, 21, 0 }, { 3, 1, 1, 1, 1, 1 }, 22, 23, 28, 200, 240, AI_SKELSD, 0 , 3, 100, 8, 20, 40, 0, 0, 0, 0, 85, MonsterClass::Demon, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , 3, 0, 3200 },
/* MT_HELLBAT */ { P_("monster", "Hellbat"), "Hellbat2\\bhelbt", "Monsters\\newsfx\\HelBat%c%i.WAV", nullptr, MonsterAvailability::Retail, 96, 550, true, false, false, { 18, 16, 14, 6, 18, 11 }, { 2, 1, 1, 1, 1, 1 }, 23, 24, 29, 100, 140, AI_TORCHANT, 0 , 3, 110, 8, 30, 30, 0, 0, 0, 0, 80, MonsterClass::Demon, RESIST_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , RESIST_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 7, 0, 3600 },
/* MT_BONEDEMN*/ { P_("monster", "Bone Demon"), "Demskel\\Demskl", "Monsters\\newsfx\\SWing%c%i.WAV", "Monsters\\Thin\\Thinv3.TRN", MonsterAvailability::Retail, 128, 1740, true, true, false, { 10, 8, 20, 6, 24, 16 }, { 3, 1, 1, 1, 1, 1 }, 23, 24, 30, 240, 280, AI_BONEDEMON, 0 , 0, 100, 8, 40, 50, 160, 12, 50, 50, 50, MonsterClass::Undead, IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 5000 },
/* MT_ARCHLICH*/ { P_("monster", "Arch Lich"), "Lich2\\Lich2", "Monsters\\newsfx\\Lich%c%i.WAV", nullptr, MonsterAvailability::Retail, 136, 800, false, true, false, { 12, 10, 10, 7, 21, 0 }, { 2, 1, 1, 1, 2, 1 }, 23, 24, 30, 180, 200, AI_ARCHLICH, 0 , 3, 120, 8, 30, 30, 0, 0, 0, 0, 75, MonsterClass::Undead, RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 3, 0, 4000 },
/* MT_BICLOPS */ { P_("monster", "Biclops"), "Byclps\\Byclps", "Monsters\\newsfx\\Biclop%c%i.WAV", nullptr, MonsterAvailability::Retail, 180, 800, false, false, false, { 10, 11, 16, 6, 16, 0 }, { 2, 1, 1, 1, 2, 1 }, 23, 24, 30, 200, 240, AI_SKELSD, MFLAG_KNOCKBACK | MFLAG_CAN_OPEN_DOOR, 3, 90, 8, 40, 50, 0, 0, 0, 0, 80, MonsterClass::Demon, RESIST_LIGHTNING , RESIST_FIRE | RESIST_LIGHTNING , 3, 0, 4000 },
/* MT_FLESTHNG*/ { P_("monster", "Flesh Thing"), "Flesh\\Flesh", "Monsters\\newsfx\\FleshT%c%i.WAV", nullptr, MonsterAvailability::Retail, 164, 800, false, true, false, { 15, 24, 15, 6, 16, 0 }, { 1, 1, 1, 1, 1, 1 }, 23, 24, 28, 300, 400, AI_SKELSD, 0 , 3, 150, 8, 12, 18, 0, 0, 0, 0, 70, MonsterClass::Demon, RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , 3, 0, 4000 },
/* MT_REAPER */ { P_("monster", "Reaper"), "Reaper\\Reap", "Monsters\\newsfx\\Reaper%c%i.WAV", nullptr, MonsterAvailability::Retail, 180, 800, false, false, false, { 12, 10, 14, 6, 16, 0 }, { 2, 1, 1, 1, 1, 1 }, 23, 24, 30, 260, 300, AI_SKELSD, 0 , 3, 120, 8, 30, 35, 0, 0, 0, 0, 90, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , 3, 0, 6000 },
// TRANSLATORS: Monster Block end
/* MT_NAKRUL */ { P_("monster", "Na-Krul"), "Nkr\\Nkr", "Monsters\\newsfx\\Nakrul%c%i.WAV", nullptr, MonsterAvailability::Never, 226, 1200, true, true, false, { 2, 6, 16, 3, 16, 16 }, { 0, 0, 0, 0, 0, 0 }, 31, 31, 40, 1332, 1332, AI_SKELSD, MFLAG_KNOCKBACK | MFLAG_SEARCH | MFLAG_CAN_OPEN_DOOR, 3, 150, 7, 40, 50, 150, 10, 40, 50, 125, MonsterClass::Demon, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40 , IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40 , 7, 0, 13333 },
// clang-format on
};
/**
* Map between .DUN file value and monster type enum
*/
const _monster_id MonstConvTbl[] = {
MT_NZOMBIE,
MT_BZOMBIE,
MT_GZOMBIE,
MT_YZOMBIE,
MT_RFALLSP,
MT_DFALLSP,
MT_YFALLSP,
MT_BFALLSP,
MT_WSKELAX,
MT_TSKELAX,
MT_RSKELAX,
MT_XSKELAX,
MT_RFALLSD,
MT_DFALLSD,
MT_YFALLSD,
MT_BFALLSD,
MT_NSCAV,
MT_BSCAV,
MT_WSCAV,
MT_YSCAV,
MT_WSKELBW,
MT_TSKELBW,
MT_RSKELBW,
MT_XSKELBW,
MT_WSKELSD,
MT_TSKELSD,
MT_RSKELSD,
MT_XSKELSD,
MT_SNEAK,
MT_STALKER,
MT_UNSEEN,
MT_ILLWEAV,
MT_NGOATMC,
MT_BGOATMC,
MT_RGOATMC,
MT_GGOATMC,
MT_FIEND,
MT_GLOOM,
MT_BLINK,
MT_FAMILIAR,
MT_NGOATBW,
MT_BGOATBW,
MT_RGOATBW,
MT_GGOATBW,
MT_NACID,
MT_RACID,
MT_BACID,
MT_XACID,
MT_SKING,
MT_FAT,
MT_MUDMAN,
MT_TOAD,
MT_FLAYED,
MT_WYRM,
MT_CAVSLUG,
MT_DEVOUR,
MT_DVLWYRM,
MT_NMAGMA,
MT_YMAGMA,
MT_BMAGMA,
MT_WMAGMA,
MT_HORNED,
MT_MUDRUN,
MT_FROSTC,
MT_OBLORD,
MT_BONEDMN,
MT_REDDTH,
MT_LTCHDMN,
MT_UDEDBLRG,
MT_INVALID,
MT_INVALID,
MT_INVALID,
MT_INVALID,
MT_INCIN,
MT_FLAMLRD,
MT_DOOMFIRE,
MT_HELLBURN,
MT_INVALID,
MT_INVALID,
MT_INVALID,
MT_INVALID,
MT_RSTORM,
MT_STORM,
MT_STORML,
MT_MAEL,
MT_WINGED,
MT_GARGOYLE,
MT_BLOODCLW,
MT_DEATHW,
MT_MEGA,
MT_GUARD,
MT_VTEXLRD,
MT_BALROG,
MT_NSNAKE,
MT_RSNAKE,
MT_GSNAKE,
MT_BSNAKE,
MT_NBLACK,
MT_RTBLACK,
MT_BTBLACK,
MT_RBLACK,
MT_UNRAV,
MT_HOLOWONE,
MT_PAINMSTR,
MT_REALWEAV,
MT_SUCCUBUS,
MT_SNOWWICH,
MT_HLSPWN,
MT_SOLBRNR,
MT_COUNSLR,
MT_MAGISTR,
MT_CABALIST,
MT_ADVOCATE,
MT_INVALID,
MT_DIABLO,
MT_INVALID,
MT_GOLEM,
MT_INVALID,
MT_INVALID,
MT_INVALID, // Monster from blood1.dun and blood2.dun
MT_INVALID,
MT_INVALID,
MT_INVALID,
MT_INVALID, // Snotspill from banner2.dun
MT_INVALID,
MT_INVALID,
MT_BIGFALL,
MT_DARKMAGE,
MT_HELLBOAR,
MT_STINGER,
MT_PSYCHORB,
MT_ARACHNON,
MT_FELLTWIN,
MT_HORKSPWN,
MT_VENMTAIL,
MT_NECRMORB,
MT_SPIDLORD,
MT_LASHWORM,
MT_TORCHANT,
MT_HORKDMN,
MT_DEFILER,
MT_GRAVEDIG,
MT_TOMBRAT,
MT_FIREBAT,
MT_SKLWING,
MT_LICH,
MT_CRYPTDMN,
MT_HELLBAT,
MT_BONEDEMN,
MT_LICH,
MT_BICLOPS,
MT_FLESTHNG,
MT_REAPER,
MT_NAKRUL,
MT_CLEAVER,
MT_INVILORD,
MT_LRDSAYTR,
};
/** Contains the data related to each unique monster ID. */
const UniqueMonsterData UniqueMonstersData[] = {
// clang-format off
// mtype, mName, mTrnName, mlevel, mmaxhp, mAi, mint, mMinDamage, mMaxDamage, mMagicRes, monsterPack, customToHit, customArmorClass, mtalkmsg
// TRANSLATORS: Unique Monster Block start
{ MT_NGOATMC, P_("monster", "Gharbad the Weak"), "BSDB", 4, 120, AI_GARBUD, 3, 8, 16, IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_GARBUD1 },
{ MT_SKING, P_("monster", "Skeleton King"), "GENRL", 0, 240, AI_SKELKING, 3, 6, 16, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Independent, 0, 0, TEXT_NONE },
{ MT_COUNSLR, P_("monster", "Zhar the Mad"), "GENERAL", 8, 360, AI_ZHAR, 3, 16, 40, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_ZHAR1 },
{ MT_BFALLSP, P_("monster", "Snotspill"), "BNG", 4, 220, AI_SNOTSPIL, 3, 10, 18, RESIST_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_BANNER10 },
{ MT_ADVOCATE, P_("monster", "Arch-Bishop Lazarus"), "GENERAL", 0, 600, AI_LAZARUS, 3, 30, 50, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_VILE13 },
{ MT_HLSPWN, P_("monster", "Red Vex"), "REDV", 0, 400, AI_LAZHELP, 3, 30, 50, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_VILE13 },
{ MT_HLSPWN, P_("monster", "Black Jade"), "BLKJD", 0, 400, AI_LAZHELP, 3, 30, 50, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_VILE13 },
{ MT_RBLACK, P_("monster", "Lachdanan"), "BHKA", 14, 500, AI_LACHDAN, 3, 0, 0, 0 , UniqueMonsterPack::None, 0, 0, TEXT_VEIL9 },
{ MT_BTBLACK, P_("monster", "Warlord of Blood"), "GENERAL", 13, 850, AI_WARLORD, 3, 35, 50, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_WARLRD9 },
{ MT_CLEAVER, P_("monster", "The Butcher"), "GENRL", 0, 220, AI_CLEAVER, 3, 6, 12, RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_HORKDMN, P_("monster", "Hork Demon"), "GENRL", 19, 300, AI_HORKDMN, 3, 20, 35, RESIST_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_DEFILER, P_("monster", "The Defiler"), "GENRL", 20, 480, AI_SKELSD, 3, 30, 40, RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_NAKRUL, P_("monster", "Na-Krul"), "GENRL", 0, 1332, AI_SKELSD, 3, 40, 50, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_TSKELAX, P_("monster", "Bonehead Keenaxe"), "BHKA", 2, 91, AI_SKELSD, 2, 4, 10, IMMUNE_MAGIC | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 100, 0, TEXT_NONE },
{ MT_RFALLSD, P_("monster", "Bladeskin the Slasher"), "BSTS", 2, 51, AI_FALLEN, 0, 6, 18, RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 45, TEXT_NONE },
{ MT_NZOMBIE, P_("monster", "Soulpus"), "GENERAL", 2, 133, AI_ZOMBIE, 0, 4, 8, RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_RFALLSP, P_("monster", "Pukerat the Unclean"), "PTU", 2, 77, AI_FALLEN, 3, 1, 5, RESIST_FIRE , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_WSKELAX, P_("monster", "Boneripper"), "BR", 2, 54, AI_BAT, 0, 6, 15, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_NZOMBIE, P_("monster", "Rotfeast the Hungry"), "ETH", 2, 85, AI_SKELSD, 3, 4, 12, IMMUNE_MAGIC | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_DFALLSD, P_("monster", "Gutshank the Quick"), "GTQ", 3, 66, AI_BAT, 2, 6, 16, RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_TSKELSD, P_("monster", "Brokenhead Bangshield"), "BHBS", 3, 108, AI_SKELSD, 3, 12, 20, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_YFALLSP, P_("monster", "Bongo"), "BNG", 3, 178, AI_FALLEN, 3, 9, 21, 0 , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BZOMBIE, P_("monster", "Rotcarnage"), "RCRN", 3, 102, AI_ZOMBIE, 3, 9, 24, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 45, TEXT_NONE },
{ MT_NSCAV, P_("monster", "Shadowbite"), "SHBT", 2, 60, AI_SKELSD, 3, 3, 20, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_WSKELBW, P_("monster", "Deadeye"), "DE", 2, 49, AI_GOATBOW, 0, 6, 9, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_RSKELAX, P_("monster", "Madeye the Dead"), "MTD", 4, 75, AI_BAT, 0, 9, 21, IMMUNE_MAGIC | IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 30, TEXT_NONE },
{ MT_BSCAV, P_("monster", "El Chupacabras"), "GENERAL", 3, 120, AI_GOATMC, 0, 10, 18, RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_TSKELBW, P_("monster", "Skullfire"), "SKFR", 3, 125, AI_GOATBOW, 1, 6, 10, IMMUNE_FIRE , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_SNEAK, P_("monster", "Warpskull"), "TSPO", 3, 117, AI_SNEAK, 2, 6, 18, RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_GZOMBIE, P_("monster", "Goretongue"), "PMR", 3, 156, AI_SKELSD, 1, 15, 30, IMMUNE_MAGIC | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_WSCAV, P_("monster", "Pulsecrawler"), "BHKA", 4, 150, AI_SCAV, 0, 16, 20, IMMUNE_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 45, TEXT_NONE },
{ MT_BLINK, P_("monster", "Moonbender"), "GENERAL", 4, 135, AI_BAT, 0, 9, 27, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BLINK, P_("monster", "Wrathraven"), "GENERAL", 5, 135, AI_BAT, 2, 9, 22, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_YSCAV, P_("monster", "Spineeater"), "GENERAL", 4, 180, AI_SCAV, 1, 18, 25, IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RSKELBW, P_("monster", "Blackash the Burning"), "BASHTB", 4, 120, AI_GOATBOW, 0, 6, 16, IMMUNE_MAGIC | IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BFALLSD, P_("monster", "Shadowcrow"), "GENERAL", 5, 270, AI_SNEAK, 2, 12, 25, 0 , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_LRDSAYTR, P_("monster", "Blightstone the Weak"), "BHKA", 4, 360, AI_SKELSD, 0, 4, 12, IMMUNE_MAGIC | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 70, 0, TEXT_NONE },
{ MT_FAT, P_("monster", "Bilefroth the Pit Master"), "BFTP", 6, 210, AI_BAT, 1, 16, 23, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_NGOATBW, P_("monster", "Bloodskin Darkbow"), "BSDB", 5, 207, AI_GOATBOW, 0, 3, 16, RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 55, TEXT_NONE },
{ MT_GLOOM, P_("monster", "Foulwing"), "DB", 5, 246, AI_RHINO, 3, 12, 28, RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_XSKELSD, P_("monster", "Shadowdrinker"), "SHDR", 5, 300, AI_SNEAK, 1, 18, 26, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 45, TEXT_NONE },
{ MT_UNSEEN, P_("monster", "Hazeshifter"), "BHKA", 5, 285, AI_SNEAK, 3, 18, 30, IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_NACID, P_("monster", "Deathspit"), "BFDS", 6, 303, AI_ACIDUNIQ, 0, 12, 32, RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RGOATMC, P_("monster", "Bloodgutter"), "BGBL", 6, 315, AI_BAT, 1, 24, 34, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BGOATMC, P_("monster", "Deathshade Fleshmaul"), "DSFM", 6, 276, AI_RHINO, 0, 12, 24, IMMUNE_MAGIC | RESIST_FIRE , UniqueMonsterPack::None, 0, 65, TEXT_NONE },
{ MT_WYRM, P_("monster", "Warmaggot the Mad"), "GENERAL", 6, 246, AI_BAT, 3, 15, 30, RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_STORM, P_("monster", "Glasskull the Jagged"), "BHKA", 7, 354, AI_STORM, 0, 18, 30, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RGOATBW, P_("monster", "Blightfire"), "BLF", 7, 321, AI_SUCC, 2, 13, 21, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_GARGOYLE, P_("monster", "Nightwing the Cold"), "GENERAL", 7, 342, AI_BAT, 1, 18, 26, IMMUNE_MAGIC | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_GGOATBW, P_("monster", "Gorestone"), "GENERAL", 7, 303, AI_GOATBOW, 1, 15, 28, RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 70, 0, TEXT_NONE },
{ MT_BMAGMA, P_("monster", "Bronzefist Firestone"), "GENERAL", 8, 360, AI_MAGMA, 0, 30, 36, IMMUNE_MAGIC | RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_INCIN, P_("monster", "Wrathfire the Doomed"), "WFTD", 8, 270, AI_SKELSD, 2, 20, 30, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_NMAGMA, P_("monster", "Firewound the Grim"), "BHKA", 8, 303, AI_MAGMA, 0, 18, 22, IMMUNE_MAGIC | RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_MUDMAN, P_("monster", "Baron Sludge"), "BSM", 8, 315, AI_SNEAK, 3, 25, 34, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 75, TEXT_NONE },
{ MT_GGOATMC, P_("monster", "Blighthorn Steelmace"), "BHSM", 7, 250, AI_RHINO, 0, 20, 28, RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 45, TEXT_NONE },
{ MT_RACID, P_("monster", "Chaoshowler"), "GENERAL", 8, 240, AI_ACIDUNIQ, 0, 12, 20, 0 , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_REDDTH, P_("monster", "Doomgrin the Rotting"), "GENERAL", 8, 405, AI_STORM, 3, 25, 50, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_FLAMLRD, P_("monster", "Madburner"), "GENERAL", 9, 270, AI_STORM, 0, 20, 40, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_LTCHDMN, P_("monster", "Bonesaw the Litch"), "GENERAL", 9, 495, AI_STORM, 2, 30, 55, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_MUDRUN, P_("monster", "Breakspine"), "GENERAL", 9, 351, AI_RHINO, 0, 25, 34, RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_REDDTH, P_("monster", "Devilskull Sharpbone"), "GENERAL", 9, 444, AI_STORM, 1, 25, 40, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_STORM, P_("monster", "Brokenstorm"), "GENERAL", 9, 411, AI_STORM, 2, 25, 36, IMMUNE_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RSTORM, P_("monster", "Stormbane"), "GENERAL", 9, 555, AI_STORM, 3, 30, 30, IMMUNE_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_TOAD, P_("monster", "Oozedrool"), "GENERAL", 9, 483, AI_FAT, 3, 25, 30, RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BLOODCLW, P_("monster", "Goldblight of the Flame"), "GENERAL", 10, 405, AI_GARG, 0, 15, 35, IMMUNE_MAGIC | IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 80, TEXT_NONE },
{ MT_OBLORD, P_("monster", "Blackstorm"), "GENERAL", 10, 525, AI_RHINO, 3, 20, 40, IMMUNE_MAGIC | IMMUNE_LIGHTNING , UniqueMonsterPack::Leashed, 0, 90, TEXT_NONE },
{ MT_RACID, P_("monster", "Plaguewrath"), "GENERAL", 10, 450, AI_ACIDUNIQ, 2, 20, 30, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RSTORM, P_("monster", "The Flayer"), "GENERAL", 10, 501, AI_STORM, 1, 20, 35, RESIST_MAGIC | RESIST_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_FROSTC, P_("monster", "Bluehorn"), "GENERAL", 11, 477, AI_RHINO, 1, 25, 30, IMMUNE_MAGIC | RESIST_FIRE , UniqueMonsterPack::Leashed, 0, 90, TEXT_NONE },
{ MT_HELLBURN, P_("monster", "Warpfire Hellspawn"), "GENERAL", 11, 525, AI_FIREMAN, 3, 10, 40, RESIST_MAGIC | IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_NSNAKE, P_("monster", "Fangspeir"), "GENERAL", 11, 444, AI_SKELSD, 1, 15, 32, IMMUNE_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_UDEDBLRG, P_("monster", "Festerskull"), "GENERAL", 11, 600, AI_STORM, 2, 15, 30, IMMUNE_MAGIC | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_NBLACK, P_("monster", "Lionskull the Bent"), "GENERAL", 12, 525, AI_SKELSD, 2, 25, 25, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_COUNSLR, P_("monster", "Blacktongue"), "GENERAL", 12, 360, AI_COUNSLR, 3, 15, 30, RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_DEATHW, P_("monster", "Viletouch"), "GENERAL", 12, 525, AI_GARG, 3, 20, 40, IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RSNAKE, P_("monster", "Viperflame"), "GENERAL", 12, 570, AI_SKELSD, 1, 25, 35, IMMUNE_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BSNAKE, P_("monster", "Fangskin"), "BHKA", 14, 681, AI_SKELSD, 2, 15, 50, IMMUNE_MAGIC | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_SUCCUBUS, P_("monster", "Witchfire the Unholy"), "GENERAL", 12, 444, AI_SUCC, 3, 10, 20, IMMUNE_MAGIC | IMMUNE_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_BALROG, P_("monster", "Blackskull"), "BHKA", 13, 750, AI_SKELSD, 3, 25, 40, IMMUNE_MAGIC | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_UNRAV, P_("monster", "Soulslash"), "GENERAL", 12, 450, AI_SKELSD, 0, 25, 25, IMMUNE_MAGIC | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_VTEXLRD, P_("monster", "Windspawn"), "GENERAL", 12, 711, AI_SKELSD, 1, 35, 40, IMMUNE_MAGIC | IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_GSNAKE, P_("monster", "Lord of the Pit"), "GENERAL", 13, 762, AI_SKELSD, 2, 25, 42, RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_RTBLACK, P_("monster", "Rustweaver"), "GENERAL", 13, 400, AI_SKELSD, 3, 1, 60, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_HOLOWONE, P_("monster", "Howlingire the Shade"), "GENERAL", 13, 450, AI_SKELSD, 2, 40, 75, RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_MAEL, P_("monster", "Doomcloud"), "GENERAL", 13, 612, AI_STORM, 1, 1, 60, RESIST_FIRE | IMMUNE_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_PAINMSTR, P_("monster", "Bloodmoon Soulfire"), "GENERAL", 13, 684, AI_SKELSD, 1, 15, 40, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_SNOWWICH, P_("monster", "Witchmoon"), "GENERAL", 13, 310, AI_SUCC, 3, 30, 40, RESIST_LIGHTNING , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_VTEXLRD, P_("monster", "Gorefeast"), "GENERAL", 13, 771, AI_SKELSD, 3, 20, 55, RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_RTBLACK, P_("monster", "Graywar the Slayer"), "GENERAL", 14, 672, AI_SKELSD, 1, 30, 50, RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_MAGISTR, P_("monster", "Dreadjudge"), "GENERAL", 14, 540, AI_COUNSLR, 1, 30, 40, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_HLSPWN, P_("monster", "Stareye the Witch"), "GENERAL", 14, 726, AI_SUCC, 2, 30, 50, IMMUNE_FIRE , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_BTBLACK, P_("monster", "Steelskull the Hunter"), "GENERAL", 14, 831, AI_SKELSD, 3, 40, 50, RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_RBLACK, P_("monster", "Sir Gorash"), "GENERAL", 16, 1050, AI_SKELSD, 1, 20, 60, IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_CABALIST, P_("monster", "The Vizier"), "GENERAL", 15, 850, AI_COUNSLR, 2, 25, 40, IMMUNE_FIRE , UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_REALWEAV, P_("monster", "Zamphir"), "GENERAL", 15, 891, AI_SKELSD, 2, 30, 50, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_HLSPWN, P_("monster", "Bloodlust"), "GENERAL", 15, 825, AI_SUCC, 1, 20, 55, IMMUNE_MAGIC | IMMUNE_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_HLSPWN, P_("monster", "Webwidow"), "GENERAL", 16, 774, AI_SUCC, 1, 20, 50, IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_SOLBRNR, P_("monster", "Fleshdancer"), "GENERAL", 16, 999, AI_SUCC, 3, 30, 50, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::None, 0, 0, TEXT_NONE },
{ MT_OBLORD, P_("monster", "Grimspike"), "GENERAL", 19, 534, AI_SNEAK, 1, 25, 40, IMMUNE_MAGIC | RESIST_FIRE | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
// TRANSLATORS: Unique Monster Block end
{ MT_STORML, P_("monster", "Doomlock"), "GENERAL", 28, 534, AI_SNEAK, 1, 35, 55, IMMUNE_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_NULL_40, UniqueMonsterPack::Leashed, 0, 0, TEXT_NONE },
{ MT_INVALID, nullptr, nullptr, 0, 0, AI_INVALID, 0, 0, 0, 0 , UniqueMonsterPack::None, 0, 0, TEXT_NONE },
// clang-format on
};
} // namespace devilution
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkThreadLogger.h"
#include "itksys/SystemTools.hxx"
namespace itk
{
ThreadLogger ::ThreadLogger()
{
m_Delay = 300; // ms
m_TerminationRequested = false;
m_Thread = std::thread(&ThreadLogger::ThreadFunction, this);
}
ThreadLogger ::~ThreadLogger()
{
if (m_Thread.joinable())
{
m_TerminationRequested = true;
m_Thread.join(); // waits for it to finish if necessary
}
}
void
ThreadLogger ::SetPriorityLevel(PriorityLevelType level)
{
this->m_Mutex.lock();
this->m_OperationQ.push(SET_PRIORITY_LEVEL);
this->m_LevelQ.push(level);
this->m_Mutex.unlock();
}
Logger::PriorityLevelType
ThreadLogger ::GetPriorityLevel() const
{
this->m_Mutex.lock();
PriorityLevelType level = this->m_PriorityLevel;
this->m_Mutex.unlock();
return level;
}
void
ThreadLogger ::SetLevelForFlushing(PriorityLevelType level)
{
this->m_Mutex.lock();
this->m_LevelForFlushing = level;
this->m_OperationQ.push(SET_LEVEL_FOR_FLUSHING);
this->m_LevelQ.push(level);
this->m_Mutex.unlock();
}
Logger::PriorityLevelType
ThreadLogger ::GetLevelForFlushing() const
{
this->m_Mutex.lock();
PriorityLevelType level = this->m_LevelForFlushing;
this->m_Mutex.unlock();
return level;
}
void
ThreadLogger ::SetDelay(DelayType delay)
{
this->m_Mutex.lock();
this->m_Delay = delay;
this->m_Mutex.unlock();
}
ThreadLogger::DelayType
ThreadLogger ::GetDelay() const
{
this->m_Mutex.lock();
DelayType delay = this->m_Delay;
this->m_Mutex.unlock();
return delay;
}
void
ThreadLogger ::AddLogOutput(OutputType * output)
{
this->m_Mutex.lock();
this->m_OperationQ.push(ADD_LOG_OUTPUT);
this->m_OutputQ.push(output);
this->m_Mutex.unlock();
}
void
ThreadLogger ::Write(PriorityLevelType level, std::string const & content)
{
this->m_Mutex.lock();
this->m_OperationQ.push(WRITE);
this->m_MessageQ.push(content);
this->m_LevelQ.push(level);
this->m_Mutex.unlock();
if (this->m_LevelForFlushing >= level)
{
this->InternalFlush();
}
}
void
ThreadLogger ::Flush()
{
this->m_Mutex.lock();
this->m_OperationQ.push(FLUSH);
this->m_Mutex.unlock();
this->InternalFlush();
}
void
ThreadLogger ::InternalFlush()
{
this->m_Mutex.lock();
while (!this->m_OperationQ.empty())
{
switch (this->m_OperationQ.front())
{
case ThreadLogger::SET_PRIORITY_LEVEL:
this->m_PriorityLevel = this->m_LevelQ.front();
this->m_LevelQ.pop();
break;
case ThreadLogger::SET_LEVEL_FOR_FLUSHING:
this->m_LevelForFlushing = this->m_LevelQ.front();
this->m_LevelQ.pop();
break;
case ThreadLogger::ADD_LOG_OUTPUT:
this->m_Output->AddLogOutput(this->m_OutputQ.front());
this->m_OutputQ.pop();
break;
case ThreadLogger::WRITE:
this->Logger::Write(this->m_LevelQ.front(), this->m_MessageQ.front());
this->m_LevelQ.pop();
this->m_MessageQ.pop();
break;
case ThreadLogger::FLUSH:
this->Logger::Flush();
break;
}
this->m_OperationQ.pop();
}
this->m_Output->Flush();
this->m_Mutex.unlock();
}
void
ThreadLogger ::ThreadFunction()
{
while (!m_TerminationRequested)
{
m_Mutex.lock();
while (!m_OperationQ.empty())
{
switch (m_OperationQ.front())
{
case ThreadLogger::SET_PRIORITY_LEVEL:
m_PriorityLevel = m_LevelQ.front();
m_LevelQ.pop();
break;
case ThreadLogger::SET_LEVEL_FOR_FLUSHING:
m_LevelForFlushing = m_LevelQ.front();
m_LevelQ.pop();
break;
case ThreadLogger::ADD_LOG_OUTPUT:
m_Output->AddLogOutput(m_OutputQ.front());
m_OutputQ.pop();
break;
case ThreadLogger::WRITE:
Logger::Write(m_LevelQ.front(), m_MessageQ.front());
m_LevelQ.pop();
m_MessageQ.pop();
break;
case ThreadLogger::FLUSH:
Logger::Flush();
break;
}
m_OperationQ.pop();
}
m_Mutex.unlock();
itksys::SystemTools::Delay(this->GetDelay());
}
}
void
ThreadLogger ::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Thread ID: " << this->m_Thread.get_id() << std::endl;
os << indent << "Low-priority Message Delay: " << this->m_Delay << std::endl;
os << indent << "Operation Queue Size: " << this->m_OperationQ.size() << std::endl;
os << indent << "Message Queue Size: " << this->m_MessageQ.size() << std::endl;
os << indent << "Level Queue Size: " << this->m_LevelQ.size() << std::endl;
os << indent << "Output Queue Size: " << this->m_OutputQ.size() << std::endl;
}
} // namespace itk
|
/****************************************************************************/
/// @file ROLoader.cpp
/// @author Daniel Krajzewicz
/// @author Jakob Erdmann
/// @author Sascha Krieg
/// @author Michael Behrisch
/// @author Christian Roessel
/// @date Sept 2002
/// @version $Id$
///
// Loader for networks and route imports
/****************************************************************************/
// SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
// Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors
/****************************************************************************/
//
// This file is part of SUMO.
// SUMO is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
/****************************************************************************/
// ===========================================================================
// included modules
// ===========================================================================
#ifdef _MSC_VER
#include <windows_config.h>
#else
#include <config.h>
#endif
#include <iostream>
#include <string>
#include <iomanip>
#include <xercesc/parsers/SAXParser.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <utils/options/OptionsCont.h>
#include <utils/common/ToString.h>
#include <utils/common/StringTokenizer.h>
#include <utils/common/MsgHandler.h>
#include <utils/common/UtilExceptions.h>
#include <utils/common/FileHelpers.h>
#include <utils/xml/XMLSubSys.h>
#include <utils/xml/SAXWeightsHandler.h>
#include <utils/xml/SUMORouteLoader.h>
#include <utils/xml/SUMORouteLoaderControl.h>
#include "RONet.h"
#include "RONetHandler.h"
#include "ROLoader.h"
#include "ROEdge.h"
#include "RORouteHandler.h"
// ===========================================================================
// method definitions
// ===========================================================================
// ---------------------------------------------------------------------------
// ROLoader::EdgeFloatTimeLineRetriever_EdgeTravelTime - methods
// ---------------------------------------------------------------------------
void
ROLoader::EdgeFloatTimeLineRetriever_EdgeTravelTime::addEdgeWeight(const std::string& id,
double val, double beg, double end) const {
ROEdge* e = myNet.getEdge(id);
if (e != 0) {
e->addTravelTime(val, beg, end);
} else {
if (id[0] != ':') {
if (OptionsCont::getOptions().getBool("ignore-errors")) {
WRITE_WARNING("Trying to set a weight for the unknown edge '" + id + "'.");
} else {
WRITE_ERROR("Trying to set a weight for the unknown edge '" + id + "'.");
}
}
}
}
// ---------------------------------------------------------------------------
// ROLoader::EdgeFloatTimeLineRetriever_EdgeWeight - methods
// ---------------------------------------------------------------------------
void
ROLoader::EdgeFloatTimeLineRetriever_EdgeWeight::addEdgeWeight(const std::string& id,
double val, double beg, double end) const {
ROEdge* e = myNet.getEdge(id);
if (e != 0) {
e->addEffort(val, beg, end);
} else {
if (id[0] != ':') {
if (OptionsCont::getOptions().getBool("ignore-errors")) {
WRITE_WARNING("Trying to set a weight for the unknown edge '" + id + "'.");
} else {
WRITE_ERROR("Trying to set a weight for the unknown edge '" + id + "'.");
}
}
}
}
// ---------------------------------------------------------------------------
// ROLoader - methods
// ---------------------------------------------------------------------------
ROLoader::ROLoader(OptionsCont& oc, const bool emptyDestinationsAllowed, const bool logSteps) :
myOptions(oc),
myEmptyDestinationsAllowed(emptyDestinationsAllowed),
myLogSteps(logSteps),
myLoaders(oc.exists("unsorted-input") && oc.getBool("unsorted-input") ? 0 : DELTA_T) {
}
ROLoader::~ROLoader() {
}
void
ROLoader::loadNet(RONet& toFill, ROAbstractEdgeBuilder& eb) {
std::string file = myOptions.getString("net-file");
if (file == "") {
throw ProcessError("Missing definition of network to load!");
}
if (!FileHelpers::isReadable(file)) {
throw ProcessError("The network file '" + file + "' is not accessible.");
}
PROGRESS_BEGIN_MESSAGE("Loading net");
RONetHandler handler(toFill, eb);
handler.setFileName(file);
if (!XMLSubSys::runParser(handler, file, true)) {
PROGRESS_FAILED_MESSAGE();
throw ProcessError();
} else {
PROGRESS_DONE_MESSAGE();
}
if (!deprecatedVehicleClassesSeen.empty()) {
WRITE_WARNING("Deprecated vehicle classes '" + toString(deprecatedVehicleClassesSeen) + "' in input network.");
deprecatedVehicleClassesSeen.clear();
}
if (myOptions.isSet("additional-files", false)) { // dfrouter does not register this option
std::vector<std::string> files = myOptions.getStringVector("additional-files");
for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
if (!FileHelpers::isReadable(*fileIt)) {
throw ProcessError("The additional file '" + *fileIt + "' is not accessible.");
}
PROGRESS_BEGIN_MESSAGE("Loading additional file '" + *fileIt + "' ");
handler.setFileName(*fileIt);
if (!XMLSubSys::runParser(handler, *fileIt)) {
PROGRESS_FAILED_MESSAGE();
throw ProcessError();
} else {
PROGRESS_DONE_MESSAGE();
}
}
}
}
void
ROLoader::openRoutes(RONet& net) {
// build loader
// load relevant elements from additional file
bool ok = openTypedRoutes("additional-files", net);
// load sumo routes, trips, and flows
ok &= openTypedRoutes("route-files", net);
// check
if (ok) {
myLoaders.loadNext(string2time(myOptions.getString("begin")));
if (!net.furtherStored()) {
if (MsgHandler::getErrorInstance()->wasInformed()) {
throw ProcessError();
} else {
const std::string error = "No route input specified or all routes were invalid.";
if (myOptions.getBool("ignore-errors")) {
WRITE_WARNING(error);
} else {
throw ProcessError(error);
}
}
}
// skip routes prior to the begin time
if (!myOptions.getBool("unsorted-input")) {
WRITE_MESSAGE("Skipped until: " + time2string(myLoaders.getFirstLoadTime()));
}
}
}
void
ROLoader::processRoutes(const SUMOTime start, const SUMOTime end, const SUMOTime increment,
RONet& net, const RORouterProvider& provider) {
const SUMOTime absNo = end - start;
const bool endGiven = !OptionsCont::getOptions().isDefault("end");
// skip routes that begin before the simulation's begin
// loop till the end
const SUMOTime firstStep = myLoaders.getFirstLoadTime();
SUMOTime lastStep = firstStep;
SUMOTime time = MIN2(firstStep, end);
while (time <= end) {
writeStats(time, start, absNo, endGiven);
myLoaders.loadNext(time);
if (!net.furtherStored() || MsgHandler::getErrorInstance()->wasInformed()) {
break;
}
lastStep = net.saveAndRemoveRoutesUntil(myOptions, provider, time);
if ((!net.furtherStored() && myLoaders.haveAllLoaded()) || MsgHandler::getErrorInstance()->wasInformed()) {
break;
}
if (time < end && time + increment > end) {
time = end;
} else {
time += increment;
}
}
if (myLogSteps) {
WRITE_MESSAGE("Routes found between time steps " + time2string(firstStep) + " and " + time2string(lastStep) + ".");
}
}
bool
ROLoader::openTypedRoutes(const std::string& optionName,
RONet& net) {
// check whether the current loader is known
// (not all routers import all route formats)
if (!myOptions.exists(optionName)) {
return true;
}
// check whether the current loader is wished
// and the file(s) can be used
if (!myOptions.isUsableFileList(optionName)) {
return !myOptions.isSet(optionName);
}
bool ok = true;
std::vector<std::string> files = myOptions.getStringVector(optionName);
for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
// build the instance when everything's all right
try {
myLoaders.add(new SUMORouteLoader(new RORouteHandler(net, *fileIt, myOptions.getBool("repair"), myEmptyDestinationsAllowed, myOptions.getBool("ignore-errors"))));
} catch (ProcessError& e) {
std::string msg = "The loader for " + optionName + " from file '" + *fileIt + "' could not be initialised;";
std::string reason = e.what();
if (reason != "Process Error" && reason != "") {
msg = msg + "\n Reason: " + reason + ".";
} else {
msg = msg + "\n (unknown reason).";
}
WRITE_ERROR(msg);
ok = false;
}
}
return ok;
}
bool
ROLoader::loadWeights(RONet& net, const std::string& optionName,
const std::string& measure, const bool useLanes, const bool boundariesOverride) {
// check whether the file exists
if (!myOptions.isUsableFileList(optionName)) {
return false;
}
// build and prepare the weights handler
std::vector<SAXWeightsHandler::ToRetrieveDefinition*> retrieverDefs;
// travel time, first (always used)
EdgeFloatTimeLineRetriever_EdgeTravelTime ttRetriever(net);
retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition("traveltime", !useLanes, ttRetriever));
// the measure to use, then
EdgeFloatTimeLineRetriever_EdgeWeight eRetriever(net);
if (measure != "traveltime") {
std::string umeasure = measure;
if (measure == "CO" || measure == "CO2" || measure == "HC" || measure == "PMx" || measure == "NOx" || measure == "fuel" || measure == "electricity") {
umeasure = measure + "_perVeh";
}
retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition(umeasure, !useLanes, eRetriever));
}
// set up handler
SAXWeightsHandler handler(retrieverDefs, "");
// go through files
std::vector<std::string> files = myOptions.getStringVector(optionName);
for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
PROGRESS_BEGIN_MESSAGE("Loading precomputed net weights from '" + *fileIt + "'");
if (XMLSubSys::runParser(handler, *fileIt)) {
PROGRESS_DONE_MESSAGE();
} else {
WRITE_MESSAGE("failed.");
return false;
}
}
// build edge-internal time lines
const std::map<std::string, ROEdge*>& edges = net.getEdgeMap();
for (std::map<std::string, ROEdge*>::const_iterator i = edges.begin(); i != edges.end(); ++i) {
(*i).second->buildTimeLines(measure, boundariesOverride);
}
return true;
}
void
ROLoader::writeStats(const SUMOTime time, const SUMOTime start, const SUMOTime absNo, bool endGiven) {
if (myLogSteps) {
if (endGiven) {
const double perc = (double)(time - start) / (double) absNo;
std::cout << "Reading up to time step: " + time2string(time) + " (" + time2string(time - start) + "/" + time2string(absNo) + " = " + toString(perc * 100) + "% done) \r";
} else {
std::cout << "Reading up to time step: " + time2string(time) + "\r";
}
}
}
/****************************************************************************/
|
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "FlopperamCheckStyle.h"
#include "FlopperamCheck.h"
#include "Framework/Application/SlateApplication.h"
#include "Styling/SlateStyleRegistry.h"
#include "Slate/SlateGameResources.h"
#include "Interfaces/IPluginManager.h"
#include "Toolkits/AssetEditorManager.h"
TSharedPtr< FSlateStyleSet > FFlopperamCheckStyle::StyleInstance = NULL;
void FFlopperamCheckStyle::Initialize()
{
if (!StyleInstance.IsValid())
{
StyleInstance = Create();
FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
}
}
void FFlopperamCheckStyle::Shutdown()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
ensure(StyleInstance.IsUnique());
StyleInstance.Reset();
}
FName FFlopperamCheckStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("FlopperamCheckStyle"));
return StyleSetName;
}
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
TSharedRef< FSlateStyleSet > FFlopperamCheckStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable(new FSlateStyleSet("FlopperamCheckStyle"));
Style->SetContentRoot(IPluginManager::Get().FindPlugin("FlopperamCheck")->GetBaseDir() / TEXT("Resources"));
Style->Set("FlopperamCheck.PluginAction", new IMAGE_BRUSH(TEXT("ButtonIcon_40x"), Icon40x40));
return Style;
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
void FFlopperamCheckStyle::ReloadTextures()
{
if (FSlateApplication::IsInitialized())
{
FSlateApplication::Get().GetRenderer()->ReloadTextureResources();
}
}
const ISlateStyle& FFlopperamCheckStyle::Get()
{
return *StyleInstance;
}
|
//$Id$
//------------------------------------------------------------------------------
// SolarRadiationPressure
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2018 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: D.Conway
// Created: 2003/03/14
// Modified: 2003/03/30 Waka Waktola GSFC Code 583
// Updated for GMAT style, standards.
///
/**
* This is the SolarRadiationPressure class.
*
* @note original prolog information included at end of file prolog.
*/
// *** File Name : SolarRadiationPressure.cpp
// *** Created : February 27, 2003
// **************************************************************************
// *** Developed By : Thinking Systems, Inc. (www.thinksysinc.com) ***
// *** For: Flight Dynamics Analysis Branch (Code 572) ***
// *** Under Contract: P.O. GSFC S-66617-G ***
// *** ***
// *** Copyright U.S. Government 2002 ***
// *** Copyright United States Government as represented by the ***
// *** Administrator of the National Aeronautics and Space ***
// *** Administration ***
// *** ***
// *** This software is subject to the Sofware Usage Agreement described ***
// *** by NASA Case Number GSC-14735-1. The Softare Usage Agreement ***
// *** must be included in any distribution. Removal of this header is ***
// *** strictly prohibited. ***
// *** ***
// *** ***
// *** Header Version: July 12, 2002 ***
// **************************************************************************
// Module Type : ANSI C++ Source
// Development Environment : Visual C++ 7.0
// **************************************************************************
#ifndef SolarRadiationPressure_hpp
#define SolarRadiationPressure_hpp
#include "PhysicalModel.hpp"
#include "SolarSystem.hpp"
#include "CelestialBody.hpp"
#include "Rvector6.hpp"
#include "gmatdefs.hpp"
#include "ShadowState.hpp"
/**
* Solar radiation pressure model -- currently incomplete
*
* This class models solar radiation pressure. The current implementation
* builds a force directed along the x-axis with magnitude equal to a nominal
* SRP acceleration. The force toggles on and off at 40 minute intervals.
*
* Note that this is <B>NOT</B> an implementation of Solar Radiation Pressure
* in its current form because (1) the force is not applied in the correct
* direction and (2) the magnitude of the force does bot change with distance
* from the Sun. The current implementation is used solely to test
* discontinuities in the force model.
*/
class GMAT_API SolarRadiationPressure : public PhysicalModel
{
public:
SolarRadiationPressure(const std::string &name = ""); //loj: 5/28/04 added default
virtual ~SolarRadiationPressure();
SolarRadiationPressure(const SolarRadiationPressure &srp);
SolarRadiationPressure& operator=(const SolarRadiationPressure &srp);
virtual bool IsUnique(const std::string &forBody = "");
virtual bool Initialize();
virtual bool SetCentralBody();
virtual bool GetDerivatives(Real *state, Real dt = 0.0, Integer order = 1,
const Integer id = -1);
virtual Rvector6 GetDerivativesForSpacecraft(Spacecraft *sc);
// inherited from GmatBase
virtual GmatBase* Clone() const;
// Parameter access methods - overridden from GmatBase
virtual std::string GetParameterText(const Integer id) const;
virtual Integer GetParameterID(const std::string &str) const;
virtual Gmat::ParameterType GetParameterType(const Integer id) const;
virtual std::string GetParameterTypeString(const Integer id) const;
virtual bool IsParameterReadOnly(const Integer id) const;
virtual Real GetRealParameter(const Integer id) const;
virtual Real SetRealParameter(const Integer id, const Real value);
virtual bool GetBooleanParameter(const Integer id) const;
virtual bool SetBooleanParameter(const Integer id, const bool value);
virtual Integer GetIntegerParameter(const Integer id) const;
virtual Integer SetIntegerParameter(const Integer id, const Integer value);
virtual std::string GetStringParameter(const Integer id) const;
virtual std::string GetStringParameter(const std::string &label) const;
virtual bool SetStringParameter(const Integer id,
const std::string &value);
virtual bool SetStringParameter(const std::string &label,
const char *value);
virtual bool SetStringParameter(const std::string &label,
const std::string &value);
virtual const StringArray&
GetPropertyEnumStrings(const Integer id) const;
virtual void SetSatelliteParameter(const Integer i,
const std::string parmName,
const Real parm,
const Integer parmID = -1);
virtual void SetSatelliteParameter(const Integer i,
Integer parmID,
const Real parm);
virtual void ClearSatelliteParameters(const std::string parmName = "");
virtual void SetSpaceObject(const Integer i, GmatBase *obj);
// Methods used by the ODEModel to set the state indexes, etc
virtual bool SupportsDerivative(Gmat::StateElementId id);
virtual bool SetStart(Gmat::StateElementId id, Integer index,
Integer quantity, Integer sizeOfType);
DEFAULT_TO_NO_CLONES
DEFAULT_TO_NO_REFOBJECTS
protected:
// Parameter IDs
enum
{
SHADOWMODELTYPE, /// ID for the type of shadow model to use
VECTORTYPE /// ID for the force orientation model to use
// ParamCount /// Count of the parameters for this class waw: 04/19/04
};
/// Enumeration to ease pain of figuring out which shadow model is active
enum ShadowModel
{
CYLINDRICAL_MODEL = 1,
CONICAL_MODEL
};
/// Enumeration to ease pain of determining which force direction is active
enum ForceDirection
{
SUN_PARALLEL = 1,
ATTITUDE_BASED
};
/// Pointer to the source of planetary ephemerides
CelestialBody *theSun;
/// Pointer to the ShadowState
ShadowState *shadowState;
/// Flag used to indicate using an analytic model to locate the Sun
bool useAnalytic;
/// Shadow model type indicator: 1 for cylinder, 2 for cones
Integer shadowModel;
/// Vector model: 1 for (anti)parallel to Sun, 2 attitude based
Integer vectorModel;
/// Radius of the body casting the shadow
Real bodyRadius;
/// Vector to the Sun from the central body -- eventually from DE file
Real *cbSunVector;
/// Vector to the Sun from the spacecraft
Real *forceVector;
/// Radius of the Sun
Real sunRadius;
/// Flag used to indicate that there are other bodies casting shadows
bool hasMoons;
/// Basically the reflectivity of the body experiencing the force
std::vector<Real> cr;
/// Reflective surface area of the body, in square meters
std::vector<Real> area;
/// Mass of the body, in kg
std::vector<Real> mass;
/// Pointers to the spacecraft
std::vector<GmatBase*> scObjs;
/// Solar flux, in W/m^2
Real flux;
/// Solar flux, in N/m^2
Real fluxPressure;
// the model to use - Spherical or SPADFile
std::string srpModel;
/// Distance from the Sun, currently set to a dummy value
Real sunDistance;
/// Nominal distance to the Sun used in the model: 1 AU
Real nominalSun;
/// Flag used to detect if the central body is Sol
bool bodyIsTheSun;
// Conical shadow model parameters that are used in multiple methods
/// Conical model: projected sun radius
Real psunrad;
/// Conical model: projected central body radius
Real pcbrad;
/// Weighting for partial lighting
Real percentSun;
/// Flag used to track is the SRP STM partial sun message has posted
bool warnSRPMath;
/// Central body ID for the model
Integer bodyID;
Rvector6 sunrv;
Rvector6 cbrv;
/// Number of spacecraft in the state vector that use CartesianState
Integer satCount;
// /// Start index for the Cartesian state
// Integer cartIndex;
// /// Flag indicating if the Cartesian state should be populated
// bool fillCartesian;
//
// /// Number of spacecraft in the state vector that use OrbitSTM
// Integer stmCount;
// /// Start index for the OrbitSTM
// Integer stmIndex;
// /// Flag indicating if the OrbitSTM should be populated
// bool fillSTM;
Integer massID;
Integer crID;
Integer areaID;
bool estimatingCr;
Integer crEpsilonID;
Integer crEpsilonRow;
std::vector<Real> crEpsilon;
std::vector<Real> crInitial;
// void FindShadowState(bool &lit, bool &dark, Real *state);
// Real ShadowFunction(Real *state);
Rvector6 ComputeSPADAcceleration(Integer scID, Real ep,
Real *state, Real *cbSun);
static const Real FLUX_LOWER_BOUND;
static const Real FLUX_UPPER_BOUND;
static const Real FLUX_PRESSURE_LOWER_BOUND;
static const Real FLUX_PRESSURE_UPPER_BOUND;
static const Real NOMINAL_SUN_LOWER_BOUND;
static const Real NOMINAL_SUN_UPPER_BOUND;
private:
/// Parameter IDs
enum
{
USE_ANALYTIC = PhysicalModelParamCount,
SHADOW_MODEL,
VECTOR_MODEL,
BODY_RADIUS,
SUN_RADIUS,
HAS_MOONS,
CR,
AREA,
MASS,
FLUX,
FLUX_PRESSURE,
SRP_MODEL,
SUN_DISTANCE,
NOMINAL_SUN,
PSUNRAD,
PCBRAD,
PERCENT_SUN,
SRPParamCount // Count of the parameters for this class
};
static const std::string PARAMETER_TEXT[SRPParamCount - PhysicalModelParamCount];
static const Gmat::ParameterType PARAMETER_TYPE[SRPParamCount - PhysicalModelParamCount];
};
#endif
|
/* This file is part of Jellyfish.
Jellyfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
n the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jellyfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jellyfish. If not, see <http://www.gnu.org/licenses/>.
*/
#include <signal.h>
#include <config.h>
#include <jellyfish/misc.hpp>
#include <jellyfish/err.hpp>
#include <jellyfish/backtrace.hpp>
uint64_t bogus_sum(void *data, size_t len) {
uint64_t res = 0, tmp = 0;
uint64_t *ptr = (uint64_t *)data;
while(len >= sizeof(uint64_t)) {
res ^= *ptr++;
len -= sizeof(uint64_t);
}
if(len > 0) {
memcpy(&tmp, ptr, len);
res ^= tmp;
}
return res;
}
void disabled_misaligned_mem_access() {
#if defined(__GNUC__)
# if defined(__i386__)
/* Enable Alignment Checking on x86 */
__asm__("pushf\norl $0x40000,(%esp)\npopf");
# elif defined(__x86_64__)
/* Enable Alignment Checking on x86_64 */
__asm__("pushf\norl $0x40000,(%rsp)\npopf");
# endif
#endif
}
|
#include "RE/Misc/FixedStrings.h"
namespace RE
{
FixedStrings* FixedStrings::GetSingleton()
{
using func_t = decltype(&FixedStrings::GetSingleton);
REL::Relocation<func_t> func{ REL::ID(11308) };
return func();
}
}
|
#pragma once
#include "../include.hpp"
using namespace std;
namespace cxesCore {
///lexer
extern vector<string> lexer(istream& input);
} // namespace cxesCore
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkImageDataItem.h"
#include "mitkMemoryUtilities.h"
#include <vtkImageData.h>
#include <vtkPointData.h>
#include <vtkBitArray.h>
#include <vtkCharArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkIntArray.h>
#include <vtkLongArray.h>
#include <vtkShortArray.h>
#include <vtkUnsignedCharArray.h>
#include <vtkUnsignedIntArray.h>
#include <vtkUnsignedLongArray.h>
#include <vtkUnsignedShortArray.h>
#include <mitkImageVtkAccessor.h>
#include <mitkImage.h>
mitk::ImageDataItem::ImageDataItem(const ImageDataItem& aParent, const mitk::ImageDescriptor::Pointer desc, int timestep, unsigned int dimension, void *data, bool manageMemory, size_t offset)
: m_Data(static_cast<unsigned char*>(aParent.m_Data)+offset)
, m_PixelType(new mitk::PixelType(aParent.GetPixelType()))
, m_ManageMemory(false)
, m_VtkImageData(nullptr)
, m_VtkImageAccessor(nullptr)
, m_Offset(offset)
, m_IsComplete(false)
, m_Size(0)
, m_Parent(&aParent)
, m_Dimension(dimension)
, m_Timestep(timestep)
{
// compute size
//const unsigned int *dims = desc->GetDimensions();
for( unsigned int i=0; i<dimension; i++)
{
m_Dimensions[i] = desc->GetDimensions()[i];
}
this->ComputeItemSize(m_Dimensions,dimension);
if(data != nullptr && data != m_Data)
{
memcpy(m_Data, data, m_Size);
if(manageMemory)
{
delete [] (unsigned char*) data;
}
}
m_ReferenceCount = 0;
}
mitk::ImageDataItem::~ImageDataItem()
{
if(m_VtkImageData!=nullptr)
{
m_VtkImageData->Delete();
}
if(m_VtkImageAccessor != nullptr) {
delete m_VtkImageAccessor;
}
if(m_Parent.IsNull())
{
if(m_ManageMemory)
delete [] m_Data;
}
delete m_PixelType;
}
mitk::ImageDataItem::ImageDataItem(const mitk::ImageDescriptor::Pointer desc, int timestep,
void *data, bool manageMemory)
: m_Data(static_cast<unsigned char*>(data))
, m_PixelType(new mitk::PixelType(desc->GetChannelDescriptor(0).GetPixelType()))
, m_ManageMemory(manageMemory)
, m_VtkImageData(nullptr)
, m_VtkImageAccessor(nullptr)
, m_Offset(0)
, m_IsComplete(false)
, m_Size(0)
, m_Dimension(desc->GetNumberOfDimensions())
, m_Timestep(timestep)
{
// compute size
const unsigned int *dimensions = desc->GetDimensions();
for( unsigned int i=0; i<m_Dimension; i++)
{
m_Dimensions[i] = dimensions[i];
}
this->ComputeItemSize(m_Dimensions, m_Dimension );
if(m_Data == nullptr)
{
m_Data = mitk::MemoryUtilities::AllocateElements<unsigned char>( m_Size );
m_ManageMemory = true;
}
m_ReferenceCount = 0;
}
mitk::ImageDataItem::ImageDataItem(const mitk::PixelType& type, int timestep,
unsigned int dimension, unsigned int *dimensions,
void *data, bool manageMemory)
: m_Data(static_cast<unsigned char*>(data))
, m_PixelType(new mitk::PixelType(type))
, m_ManageMemory(manageMemory)
, m_VtkImageData(nullptr)
, m_VtkImageAccessor(nullptr)
, m_Offset(0)
, m_IsComplete(false)
, m_Size(0)
, m_Parent(nullptr)
, m_Dimension(dimension)
, m_Timestep(timestep)
{
for( unsigned int i=0; i<m_Dimension; i++)
{
m_Dimensions[i] = dimensions[i];
}
this->ComputeItemSize(dimensions, dimension);
if(m_Data == nullptr)
{
m_Data = mitk::MemoryUtilities::AllocateElements<unsigned char>( m_Size );
m_ManageMemory = true;
}
m_ReferenceCount = 0;
}
mitk::ImageDataItem::ImageDataItem(const ImageDataItem &other)
: itk::LightObject()
, m_Data(other.m_Data)
, m_PixelType(new mitk::PixelType(*other.m_PixelType))
, m_ManageMemory(other.m_ManageMemory)
, m_VtkImageData(nullptr)
, m_VtkImageAccessor(nullptr)
, m_Offset(other.m_Offset)
, m_IsComplete(other.m_IsComplete)
, m_Size(other.m_Size)
, m_Parent(other.m_Parent)
, m_Dimension(other.m_Dimension)
, m_Timestep(other.m_Timestep)
{
// copy m_Data ??
for (int i = 0; i < MAX_IMAGE_DIMENSIONS; ++i)
m_Dimensions[i] = other.m_Dimensions[i];
}
itk::LightObject::Pointer
mitk::ImageDataItem::InternalClone() const
{
Self::Pointer newGeometry = new Self(*this);
newGeometry->UnRegister();
return newGeometry.GetPointer();
}
void mitk::ImageDataItem::ComputeItemSize(const unsigned int *dimensions, unsigned int dimension)
{
m_Size = m_PixelType->GetSize();
for( unsigned int i=0; i<dimension; i++)
{
m_Size *= *(dimensions+i);
}
}
void mitk::ImageDataItem::ConstructVtkImageData(ImageConstPointer iP) const
{
vtkImageData *inData = vtkImageData::New();
vtkDataArray *scalars = nullptr;
const unsigned int *dims = m_Dimensions;
const unsigned int dim = m_Dimension;
size_t size = 0;
if ( dim == 1 )
{
inData->SetDimensions( dims[0] -1, 1, 1);
size = dims[0];
inData->SetOrigin( ((mitk::ScalarType) dims[0]) / 2.0, 0, 0 );
}
else
if ( dim == 2 )
{
inData->SetDimensions( dims[0] , dims[1] , 1 );
size = dims[0] * dims[1];
inData->SetOrigin( ((mitk::ScalarType) dims[0]) / 2.0f, ((mitk::ScalarType) dims[1]) / 2.0f, 0 );
}
else
if ( dim >= 3 )
{
inData->SetDimensions( dims[0], dims[1], dims[2] );
size = dims[0] * dims[1] * dims[2];
// Test
//inData->SetOrigin( (float) dims[0] / 2.0f, (float) dims[1] / 2.0f, (float) dims[2] / 2.0f );
inData->SetOrigin( 0, 0, 0 );
}
else
{
inData->Delete () ;
return;
}
if (m_Timestep >= 0)
{
SlicedGeometry3D* geom3d;
geom3d = iP->GetSlicedGeometry(m_Timestep);
const mitk::Vector3D vspacing = geom3d->GetSpacing();
double dspacing[3] = { vspacing[0], vspacing[1], vspacing[2] };
inData->SetSpacing(dspacing);
}
if ( m_PixelType->GetComponentType() == itk::ImageIOBase::CHAR )
{
scalars = vtkCharArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::UCHAR)
{
scalars = vtkUnsignedCharArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::SHORT )
{
scalars = vtkShortArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::USHORT )
{
scalars = vtkUnsignedShortArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::INT )
{
scalars = vtkIntArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::UINT )
{
scalars = vtkUnsignedIntArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::LONG )
{
scalars = vtkLongArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::ULONG )
{
scalars = vtkUnsignedLongArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::FLOAT )
{
scalars = vtkFloatArray::New();
}
else if ( m_PixelType->GetComponentType() == itk::ImageIOBase::DOUBLE )
{
scalars = vtkDoubleArray::New();
}
else
{
inData->Delete();
return;
}
m_VtkImageData = inData;
// set mitk imageDataItem void array to vtk scalar values
scalars->SetNumberOfComponents(m_PixelType->GetNumberOfComponents());
scalars->SetVoidArray(m_Data, size * m_PixelType->GetNumberOfComponents(), 1);
m_VtkImageData->GetPointData()->SetScalars(scalars);
scalars->Delete();
}
void mitk::ImageDataItem::Modified() const
{
if(m_VtkImageData)
m_VtkImageData->Modified();
}
mitk::ImageVtkAccessor* mitk::ImageDataItem::GetVtkImageAccessor(ImagePointer iP)
{
if(m_VtkImageData==nullptr) {
ConstructVtkImageData(iP.GetPointer());
}
if (m_VtkImageAccessor == nullptr) {
m_VtkImageAccessor = new ImageVtkAccessor(iP);
}
return m_VtkImageAccessor;
}
vtkImageData* mitk::ImageDataItem::getVtkImageData(ImagePointer iP)
{
if (m_VtkImageData == nullptr) {
ConstructVtkImageData(iP.GetPointer());
}
return m_VtkImageData;
}
|
/*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2001-2007, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "sctp_crc32.h"
namespace SctpDc {
/**
*
* Routine Description:
*
* Computes the CRC32c checksum for the specified buffer using the slicing by 8
* algorithm over 64 bit quantities.
*
* Arguments:
*
* p_running_crc - pointer to the initial or final remainder value
* used in CRC computations. It should be set to
* non-NULL if the mode argument is equal to CONT or END
* p_buf - the packet buffer where crc computations are being performed
* length - the length of p_buf in bytes
* init_bytes - the number of initial bytes that need to be procesed before
* aligning p_buf to multiples of 4 bytes
* mode - can be any of the following: BEGIN, CONT, END, BODY, ALIGN
*
* Return value:
*
* The computed CRC32c value
*/
/*
* Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved
*
*
* This software program is licensed subject to the BSD License, available at
* http://www.opensource.org/licenses/bsd-license.html.
*
* Abstract:
*
* Tables for software CRC generation
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o32[256] =
{
0x00000000, 0xF26B8303, 0xE13B70F7, 0x1350F3F4, 0xC79A971F, 0x35F1141C, 0x26A1E7E8, 0xD4CA64EB,
0x8AD958CF, 0x78B2DBCC, 0x6BE22838, 0x9989AB3B, 0x4D43CFD0, 0xBF284CD3, 0xAC78BF27, 0x5E133C24,
0x105EC76F, 0xE235446C, 0xF165B798, 0x030E349B, 0xD7C45070, 0x25AFD373, 0x36FF2087, 0xC494A384,
0x9A879FA0, 0x68EC1CA3, 0x7BBCEF57, 0x89D76C54, 0x5D1D08BF, 0xAF768BBC, 0xBC267848, 0x4E4DFB4B,
0x20BD8EDE, 0xD2D60DDD, 0xC186FE29, 0x33ED7D2A, 0xE72719C1, 0x154C9AC2, 0x061C6936, 0xF477EA35,
0xAA64D611, 0x580F5512, 0x4B5FA6E6, 0xB93425E5, 0x6DFE410E, 0x9F95C20D, 0x8CC531F9, 0x7EAEB2FA,
0x30E349B1, 0xC288CAB2, 0xD1D83946, 0x23B3BA45, 0xF779DEAE, 0x05125DAD, 0x1642AE59, 0xE4292D5A,
0xBA3A117E, 0x4851927D, 0x5B016189, 0xA96AE28A, 0x7DA08661, 0x8FCB0562, 0x9C9BF696, 0x6EF07595,
0x417B1DBC, 0xB3109EBF, 0xA0406D4B, 0x522BEE48, 0x86E18AA3, 0x748A09A0, 0x67DAFA54, 0x95B17957,
0xCBA24573, 0x39C9C670, 0x2A993584, 0xD8F2B687, 0x0C38D26C, 0xFE53516F, 0xED03A29B, 0x1F682198,
0x5125DAD3, 0xA34E59D0, 0xB01EAA24, 0x42752927, 0x96BF4DCC, 0x64D4CECF, 0x77843D3B, 0x85EFBE38,
0xDBFC821C, 0x2997011F, 0x3AC7F2EB, 0xC8AC71E8, 0x1C661503, 0xEE0D9600, 0xFD5D65F4, 0x0F36E6F7,
0x61C69362, 0x93AD1061, 0x80FDE395, 0x72966096, 0xA65C047D, 0x5437877E, 0x4767748A, 0xB50CF789,
0xEB1FCBAD, 0x197448AE, 0x0A24BB5A, 0xF84F3859, 0x2C855CB2, 0xDEEEDFB1, 0xCDBE2C45, 0x3FD5AF46,
0x7198540D, 0x83F3D70E, 0x90A324FA, 0x62C8A7F9, 0xB602C312, 0x44694011, 0x5739B3E5, 0xA55230E6,
0xFB410CC2, 0x092A8FC1, 0x1A7A7C35, 0xE811FF36, 0x3CDB9BDD, 0xCEB018DE, 0xDDE0EB2A, 0x2F8B6829,
0x82F63B78, 0x709DB87B, 0x63CD4B8F, 0x91A6C88C, 0x456CAC67, 0xB7072F64, 0xA457DC90, 0x563C5F93,
0x082F63B7, 0xFA44E0B4, 0xE9141340, 0x1B7F9043, 0xCFB5F4A8, 0x3DDE77AB, 0x2E8E845F, 0xDCE5075C,
0x92A8FC17, 0x60C37F14, 0x73938CE0, 0x81F80FE3, 0x55326B08, 0xA759E80B, 0xB4091BFF, 0x466298FC,
0x1871A4D8, 0xEA1A27DB, 0xF94AD42F, 0x0B21572C, 0xDFEB33C7, 0x2D80B0C4, 0x3ED04330, 0xCCBBC033,
0xA24BB5A6, 0x502036A5, 0x4370C551, 0xB11B4652, 0x65D122B9, 0x97BAA1BA, 0x84EA524E, 0x7681D14D,
0x2892ED69, 0xDAF96E6A, 0xC9A99D9E, 0x3BC21E9D, 0xEF087A76, 0x1D63F975, 0x0E330A81, 0xFC588982,
0xB21572C9, 0x407EF1CA, 0x532E023E, 0xA145813D, 0x758FE5D6, 0x87E466D5, 0x94B49521, 0x66DF1622,
0x38CC2A06, 0xCAA7A905, 0xD9F75AF1, 0x2B9CD9F2, 0xFF56BD19, 0x0D3D3E1A, 0x1E6DCDEE, 0xEC064EED,
0xC38D26C4, 0x31E6A5C7, 0x22B65633, 0xD0DDD530, 0x0417B1DB, 0xF67C32D8, 0xE52CC12C, 0x1747422F,
0x49547E0B, 0xBB3FFD08, 0xA86F0EFC, 0x5A048DFF, 0x8ECEE914, 0x7CA56A17, 0x6FF599E3, 0x9D9E1AE0,
0xD3D3E1AB, 0x21B862A8, 0x32E8915C, 0xC083125F, 0x144976B4, 0xE622F5B7, 0xF5720643, 0x07198540,
0x590AB964, 0xAB613A67, 0xB831C993, 0x4A5A4A90, 0x9E902E7B, 0x6CFBAD78, 0x7FAB5E8C, 0x8DC0DD8F,
0xE330A81A, 0x115B2B19, 0x020BD8ED, 0xF0605BEE, 0x24AA3F05, 0xD6C1BC06, 0xC5914FF2, 0x37FACCF1,
0x69E9F0D5, 0x9B8273D6, 0x88D28022, 0x7AB90321, 0xAE7367CA, 0x5C18E4C9, 0x4F48173D, 0xBD23943E,
0xF36E6F75, 0x0105EC76, 0x12551F82, 0xE03E9C81, 0x34F4F86A, 0xC69F7B69, 0xD5CF889D, 0x27A40B9E,
0x79B737BA, 0x8BDCB4B9, 0x988C474D, 0x6AE7C44E, 0xBE2DA0A5, 0x4C4623A6, 0x5F16D052, 0xAD7D5351
};
/*
* end of the CRC lookup table crc_tableil8_o32
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o40[256] =
{
0x00000000, 0x13A29877, 0x274530EE, 0x34E7A899, 0x4E8A61DC, 0x5D28F9AB, 0x69CF5132, 0x7A6DC945,
0x9D14C3B8, 0x8EB65BCF, 0xBA51F356, 0xA9F36B21, 0xD39EA264, 0xC03C3A13, 0xF4DB928A, 0xE7790AFD,
0x3FC5F181, 0x2C6769F6, 0x1880C16F, 0x0B225918, 0x714F905D, 0x62ED082A, 0x560AA0B3, 0x45A838C4,
0xA2D13239, 0xB173AA4E, 0x859402D7, 0x96369AA0, 0xEC5B53E5, 0xFFF9CB92, 0xCB1E630B, 0xD8BCFB7C,
0x7F8BE302, 0x6C297B75, 0x58CED3EC, 0x4B6C4B9B, 0x310182DE, 0x22A31AA9, 0x1644B230, 0x05E62A47,
0xE29F20BA, 0xF13DB8CD, 0xC5DA1054, 0xD6788823, 0xAC154166, 0xBFB7D911, 0x8B507188, 0x98F2E9FF,
0x404E1283, 0x53EC8AF4, 0x670B226D, 0x74A9BA1A, 0x0EC4735F, 0x1D66EB28, 0x298143B1, 0x3A23DBC6,
0xDD5AD13B, 0xCEF8494C, 0xFA1FE1D5, 0xE9BD79A2, 0x93D0B0E7, 0x80722890, 0xB4958009, 0xA737187E,
0xFF17C604, 0xECB55E73, 0xD852F6EA, 0xCBF06E9D, 0xB19DA7D8, 0xA23F3FAF, 0x96D89736, 0x857A0F41,
0x620305BC, 0x71A19DCB, 0x45463552, 0x56E4AD25, 0x2C896460, 0x3F2BFC17, 0x0BCC548E, 0x186ECCF9,
0xC0D23785, 0xD370AFF2, 0xE797076B, 0xF4359F1C, 0x8E585659, 0x9DFACE2E, 0xA91D66B7, 0xBABFFEC0,
0x5DC6F43D, 0x4E646C4A, 0x7A83C4D3, 0x69215CA4, 0x134C95E1, 0x00EE0D96, 0x3409A50F, 0x27AB3D78,
0x809C2506, 0x933EBD71, 0xA7D915E8, 0xB47B8D9F, 0xCE1644DA, 0xDDB4DCAD, 0xE9537434, 0xFAF1EC43,
0x1D88E6BE, 0x0E2A7EC9, 0x3ACDD650, 0x296F4E27, 0x53028762, 0x40A01F15, 0x7447B78C, 0x67E52FFB,
0xBF59D487, 0xACFB4CF0, 0x981CE469, 0x8BBE7C1E, 0xF1D3B55B, 0xE2712D2C, 0xD69685B5, 0xC5341DC2,
0x224D173F, 0x31EF8F48, 0x050827D1, 0x16AABFA6, 0x6CC776E3, 0x7F65EE94, 0x4B82460D, 0x5820DE7A,
0xFBC3FAF9, 0xE861628E, 0xDC86CA17, 0xCF245260, 0xB5499B25, 0xA6EB0352, 0x920CABCB, 0x81AE33BC,
0x66D73941, 0x7575A136, 0x419209AF, 0x523091D8, 0x285D589D, 0x3BFFC0EA, 0x0F186873, 0x1CBAF004,
0xC4060B78, 0xD7A4930F, 0xE3433B96, 0xF0E1A3E1, 0x8A8C6AA4, 0x992EF2D3, 0xADC95A4A, 0xBE6BC23D,
0x5912C8C0, 0x4AB050B7, 0x7E57F82E, 0x6DF56059, 0x1798A91C, 0x043A316B, 0x30DD99F2, 0x237F0185,
0x844819FB, 0x97EA818C, 0xA30D2915, 0xB0AFB162, 0xCAC27827, 0xD960E050, 0xED8748C9, 0xFE25D0BE,
0x195CDA43, 0x0AFE4234, 0x3E19EAAD, 0x2DBB72DA, 0x57D6BB9F, 0x447423E8, 0x70938B71, 0x63311306,
0xBB8DE87A, 0xA82F700D, 0x9CC8D894, 0x8F6A40E3, 0xF50789A6, 0xE6A511D1, 0xD242B948, 0xC1E0213F,
0x26992BC2, 0x353BB3B5, 0x01DC1B2C, 0x127E835B, 0x68134A1E, 0x7BB1D269, 0x4F567AF0, 0x5CF4E287,
0x04D43CFD, 0x1776A48A, 0x23910C13, 0x30339464, 0x4A5E5D21, 0x59FCC556, 0x6D1B6DCF, 0x7EB9F5B8,
0x99C0FF45, 0x8A626732, 0xBE85CFAB, 0xAD2757DC, 0xD74A9E99, 0xC4E806EE, 0xF00FAE77, 0xE3AD3600,
0x3B11CD7C, 0x28B3550B, 0x1C54FD92, 0x0FF665E5, 0x759BACA0, 0x663934D7, 0x52DE9C4E, 0x417C0439,
0xA6050EC4, 0xB5A796B3, 0x81403E2A, 0x92E2A65D, 0xE88F6F18, 0xFB2DF76F, 0xCFCA5FF6, 0xDC68C781,
0x7B5FDFFF, 0x68FD4788, 0x5C1AEF11, 0x4FB87766, 0x35D5BE23, 0x26772654, 0x12908ECD, 0x013216BA,
0xE64B1C47, 0xF5E98430, 0xC10E2CA9, 0xD2ACB4DE, 0xA8C17D9B, 0xBB63E5EC, 0x8F844D75, 0x9C26D502,
0x449A2E7E, 0x5738B609, 0x63DF1E90, 0x707D86E7, 0x0A104FA2, 0x19B2D7D5, 0x2D557F4C, 0x3EF7E73B,
0xD98EEDC6, 0xCA2C75B1, 0xFECBDD28, 0xED69455F, 0x97048C1A, 0x84A6146D, 0xB041BCF4, 0xA3E32483
};
/*
* end of the CRC lookup table crc_tableil8_o40
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o48[256] =
{
0x00000000, 0xA541927E, 0x4F6F520D, 0xEA2EC073, 0x9EDEA41A, 0x3B9F3664, 0xD1B1F617, 0x74F06469,
0x38513EC5, 0x9D10ACBB, 0x773E6CC8, 0xD27FFEB6, 0xA68F9ADF, 0x03CE08A1, 0xE9E0C8D2, 0x4CA15AAC,
0x70A27D8A, 0xD5E3EFF4, 0x3FCD2F87, 0x9A8CBDF9, 0xEE7CD990, 0x4B3D4BEE, 0xA1138B9D, 0x045219E3,
0x48F3434F, 0xEDB2D131, 0x079C1142, 0xA2DD833C, 0xD62DE755, 0x736C752B, 0x9942B558, 0x3C032726,
0xE144FB14, 0x4405696A, 0xAE2BA919, 0x0B6A3B67, 0x7F9A5F0E, 0xDADBCD70, 0x30F50D03, 0x95B49F7D,
0xD915C5D1, 0x7C5457AF, 0x967A97DC, 0x333B05A2, 0x47CB61CB, 0xE28AF3B5, 0x08A433C6, 0xADE5A1B8,
0x91E6869E, 0x34A714E0, 0xDE89D493, 0x7BC846ED, 0x0F382284, 0xAA79B0FA, 0x40577089, 0xE516E2F7,
0xA9B7B85B, 0x0CF62A25, 0xE6D8EA56, 0x43997828, 0x37691C41, 0x92288E3F, 0x78064E4C, 0xDD47DC32,
0xC76580D9, 0x622412A7, 0x880AD2D4, 0x2D4B40AA, 0x59BB24C3, 0xFCFAB6BD, 0x16D476CE, 0xB395E4B0,
0xFF34BE1C, 0x5A752C62, 0xB05BEC11, 0x151A7E6F, 0x61EA1A06, 0xC4AB8878, 0x2E85480B, 0x8BC4DA75,
0xB7C7FD53, 0x12866F2D, 0xF8A8AF5E, 0x5DE93D20, 0x29195949, 0x8C58CB37, 0x66760B44, 0xC337993A,
0x8F96C396, 0x2AD751E8, 0xC0F9919B, 0x65B803E5, 0x1148678C, 0xB409F5F2, 0x5E273581, 0xFB66A7FF,
0x26217BCD, 0x8360E9B3, 0x694E29C0, 0xCC0FBBBE, 0xB8FFDFD7, 0x1DBE4DA9, 0xF7908DDA, 0x52D11FA4,
0x1E704508, 0xBB31D776, 0x511F1705, 0xF45E857B, 0x80AEE112, 0x25EF736C, 0xCFC1B31F, 0x6A802161,
0x56830647, 0xF3C29439, 0x19EC544A, 0xBCADC634, 0xC85DA25D, 0x6D1C3023, 0x8732F050, 0x2273622E,
0x6ED23882, 0xCB93AAFC, 0x21BD6A8F, 0x84FCF8F1, 0xF00C9C98, 0x554D0EE6, 0xBF63CE95, 0x1A225CEB,
0x8B277743, 0x2E66E53D, 0xC448254E, 0x6109B730, 0x15F9D359, 0xB0B84127, 0x5A968154, 0xFFD7132A,
0xB3764986, 0x1637DBF8, 0xFC191B8B, 0x595889F5, 0x2DA8ED9C, 0x88E97FE2, 0x62C7BF91, 0xC7862DEF,
0xFB850AC9, 0x5EC498B7, 0xB4EA58C4, 0x11ABCABA, 0x655BAED3, 0xC01A3CAD, 0x2A34FCDE, 0x8F756EA0,
0xC3D4340C, 0x6695A672, 0x8CBB6601, 0x29FAF47F, 0x5D0A9016, 0xF84B0268, 0x1265C21B, 0xB7245065,
0x6A638C57, 0xCF221E29, 0x250CDE5A, 0x804D4C24, 0xF4BD284D, 0x51FCBA33, 0xBBD27A40, 0x1E93E83E,
0x5232B292, 0xF77320EC, 0x1D5DE09F, 0xB81C72E1, 0xCCEC1688, 0x69AD84F6, 0x83834485, 0x26C2D6FB,
0x1AC1F1DD, 0xBF8063A3, 0x55AEA3D0, 0xF0EF31AE, 0x841F55C7, 0x215EC7B9, 0xCB7007CA, 0x6E3195B4,
0x2290CF18, 0x87D15D66, 0x6DFF9D15, 0xC8BE0F6B, 0xBC4E6B02, 0x190FF97C, 0xF321390F, 0x5660AB71,
0x4C42F79A, 0xE90365E4, 0x032DA597, 0xA66C37E9, 0xD29C5380, 0x77DDC1FE, 0x9DF3018D, 0x38B293F3,
0x7413C95F, 0xD1525B21, 0x3B7C9B52, 0x9E3D092C, 0xEACD6D45, 0x4F8CFF3B, 0xA5A23F48, 0x00E3AD36,
0x3CE08A10, 0x99A1186E, 0x738FD81D, 0xD6CE4A63, 0xA23E2E0A, 0x077FBC74, 0xED517C07, 0x4810EE79,
0x04B1B4D5, 0xA1F026AB, 0x4BDEE6D8, 0xEE9F74A6, 0x9A6F10CF, 0x3F2E82B1, 0xD50042C2, 0x7041D0BC,
0xAD060C8E, 0x08479EF0, 0xE2695E83, 0x4728CCFD, 0x33D8A894, 0x96993AEA, 0x7CB7FA99, 0xD9F668E7,
0x9557324B, 0x3016A035, 0xDA386046, 0x7F79F238, 0x0B899651, 0xAEC8042F, 0x44E6C45C, 0xE1A75622,
0xDDA47104, 0x78E5E37A, 0x92CB2309, 0x378AB177, 0x437AD51E, 0xE63B4760, 0x0C158713, 0xA954156D,
0xE5F54FC1, 0x40B4DDBF, 0xAA9A1DCC, 0x0FDB8FB2, 0x7B2BEBDB, 0xDE6A79A5, 0x3444B9D6, 0x91052BA8
};
/*
* end of the CRC lookup table crc_tableil8_o48
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o56[256] =
{
0x00000000, 0xDD45AAB8, 0xBF672381, 0x62228939, 0x7B2231F3, 0xA6679B4B, 0xC4451272, 0x1900B8CA,
0xF64463E6, 0x2B01C95E, 0x49234067, 0x9466EADF, 0x8D665215, 0x5023F8AD, 0x32017194, 0xEF44DB2C,
0xE964B13D, 0x34211B85, 0x560392BC, 0x8B463804, 0x924680CE, 0x4F032A76, 0x2D21A34F, 0xF06409F7,
0x1F20D2DB, 0xC2657863, 0xA047F15A, 0x7D025BE2, 0x6402E328, 0xB9474990, 0xDB65C0A9, 0x06206A11,
0xD725148B, 0x0A60BE33, 0x6842370A, 0xB5079DB2, 0xAC072578, 0x71428FC0, 0x136006F9, 0xCE25AC41,
0x2161776D, 0xFC24DDD5, 0x9E0654EC, 0x4343FE54, 0x5A43469E, 0x8706EC26, 0xE524651F, 0x3861CFA7,
0x3E41A5B6, 0xE3040F0E, 0x81268637, 0x5C632C8F, 0x45639445, 0x98263EFD, 0xFA04B7C4, 0x27411D7C,
0xC805C650, 0x15406CE8, 0x7762E5D1, 0xAA274F69, 0xB327F7A3, 0x6E625D1B, 0x0C40D422, 0xD1057E9A,
0xABA65FE7, 0x76E3F55F, 0x14C17C66, 0xC984D6DE, 0xD0846E14, 0x0DC1C4AC, 0x6FE34D95, 0xB2A6E72D,
0x5DE23C01, 0x80A796B9, 0xE2851F80, 0x3FC0B538, 0x26C00DF2, 0xFB85A74A, 0x99A72E73, 0x44E284CB,
0x42C2EEDA, 0x9F874462, 0xFDA5CD5B, 0x20E067E3, 0x39E0DF29, 0xE4A57591, 0x8687FCA8, 0x5BC25610,
0xB4868D3C, 0x69C32784, 0x0BE1AEBD, 0xD6A40405, 0xCFA4BCCF, 0x12E11677, 0x70C39F4E, 0xAD8635F6,
0x7C834B6C, 0xA1C6E1D4, 0xC3E468ED, 0x1EA1C255, 0x07A17A9F, 0xDAE4D027, 0xB8C6591E, 0x6583F3A6,
0x8AC7288A, 0x57828232, 0x35A00B0B, 0xE8E5A1B3, 0xF1E51979, 0x2CA0B3C1, 0x4E823AF8, 0x93C79040,
0x95E7FA51, 0x48A250E9, 0x2A80D9D0, 0xF7C57368, 0xEEC5CBA2, 0x3380611A, 0x51A2E823, 0x8CE7429B,
0x63A399B7, 0xBEE6330F, 0xDCC4BA36, 0x0181108E, 0x1881A844, 0xC5C402FC, 0xA7E68BC5, 0x7AA3217D,
0x52A0C93F, 0x8FE56387, 0xEDC7EABE, 0x30824006, 0x2982F8CC, 0xF4C75274, 0x96E5DB4D, 0x4BA071F5,
0xA4E4AAD9, 0x79A10061, 0x1B838958, 0xC6C623E0, 0xDFC69B2A, 0x02833192, 0x60A1B8AB, 0xBDE41213,
0xBBC47802, 0x6681D2BA, 0x04A35B83, 0xD9E6F13B, 0xC0E649F1, 0x1DA3E349, 0x7F816A70, 0xA2C4C0C8,
0x4D801BE4, 0x90C5B15C, 0xF2E73865, 0x2FA292DD, 0x36A22A17, 0xEBE780AF, 0x89C50996, 0x5480A32E,
0x8585DDB4, 0x58C0770C, 0x3AE2FE35, 0xE7A7548D, 0xFEA7EC47, 0x23E246FF, 0x41C0CFC6, 0x9C85657E,
0x73C1BE52, 0xAE8414EA, 0xCCA69DD3, 0x11E3376B, 0x08E38FA1, 0xD5A62519, 0xB784AC20, 0x6AC10698,
0x6CE16C89, 0xB1A4C631, 0xD3864F08, 0x0EC3E5B0, 0x17C35D7A, 0xCA86F7C2, 0xA8A47EFB, 0x75E1D443,
0x9AA50F6F, 0x47E0A5D7, 0x25C22CEE, 0xF8878656, 0xE1873E9C, 0x3CC29424, 0x5EE01D1D, 0x83A5B7A5,
0xF90696D8, 0x24433C60, 0x4661B559, 0x9B241FE1, 0x8224A72B, 0x5F610D93, 0x3D4384AA, 0xE0062E12,
0x0F42F53E, 0xD2075F86, 0xB025D6BF, 0x6D607C07, 0x7460C4CD, 0xA9256E75, 0xCB07E74C, 0x16424DF4,
0x106227E5, 0xCD278D5D, 0xAF050464, 0x7240AEDC, 0x6B401616, 0xB605BCAE, 0xD4273597, 0x09629F2F,
0xE6264403, 0x3B63EEBB, 0x59416782, 0x8404CD3A, 0x9D0475F0, 0x4041DF48, 0x22635671, 0xFF26FCC9,
0x2E238253, 0xF36628EB, 0x9144A1D2, 0x4C010B6A, 0x5501B3A0, 0x88441918, 0xEA669021, 0x37233A99,
0xD867E1B5, 0x05224B0D, 0x6700C234, 0xBA45688C, 0xA345D046, 0x7E007AFE, 0x1C22F3C7, 0xC167597F,
0xC747336E, 0x1A0299D6, 0x782010EF, 0xA565BA57, 0xBC65029D, 0x6120A825, 0x0302211C, 0xDE478BA4,
0x31035088, 0xEC46FA30, 0x8E647309, 0x5321D9B1, 0x4A21617B, 0x9764CBC3, 0xF54642FA, 0x2803E842
};
/*
* end of the CRC lookup table crc_tableil8_o56
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o64[256] =
{
0x00000000, 0x38116FAC, 0x7022DF58, 0x4833B0F4, 0xE045BEB0, 0xD854D11C, 0x906761E8, 0xA8760E44,
0xC5670B91, 0xFD76643D, 0xB545D4C9, 0x8D54BB65, 0x2522B521, 0x1D33DA8D, 0x55006A79, 0x6D1105D5,
0x8F2261D3, 0xB7330E7F, 0xFF00BE8B, 0xC711D127, 0x6F67DF63, 0x5776B0CF, 0x1F45003B, 0x27546F97,
0x4A456A42, 0x725405EE, 0x3A67B51A, 0x0276DAB6, 0xAA00D4F2, 0x9211BB5E, 0xDA220BAA, 0xE2336406,
0x1BA8B557, 0x23B9DAFB, 0x6B8A6A0F, 0x539B05A3, 0xFBED0BE7, 0xC3FC644B, 0x8BCFD4BF, 0xB3DEBB13,
0xDECFBEC6, 0xE6DED16A, 0xAEED619E, 0x96FC0E32, 0x3E8A0076, 0x069B6FDA, 0x4EA8DF2E, 0x76B9B082,
0x948AD484, 0xAC9BBB28, 0xE4A80BDC, 0xDCB96470, 0x74CF6A34, 0x4CDE0598, 0x04EDB56C, 0x3CFCDAC0,
0x51EDDF15, 0x69FCB0B9, 0x21CF004D, 0x19DE6FE1, 0xB1A861A5, 0x89B90E09, 0xC18ABEFD, 0xF99BD151,
0x37516AAE, 0x0F400502, 0x4773B5F6, 0x7F62DA5A, 0xD714D41E, 0xEF05BBB2, 0xA7360B46, 0x9F2764EA,
0xF236613F, 0xCA270E93, 0x8214BE67, 0xBA05D1CB, 0x1273DF8F, 0x2A62B023, 0x625100D7, 0x5A406F7B,
0xB8730B7D, 0x806264D1, 0xC851D425, 0xF040BB89, 0x5836B5CD, 0x6027DA61, 0x28146A95, 0x10050539,
0x7D1400EC, 0x45056F40, 0x0D36DFB4, 0x3527B018, 0x9D51BE5C, 0xA540D1F0, 0xED736104, 0xD5620EA8,
0x2CF9DFF9, 0x14E8B055, 0x5CDB00A1, 0x64CA6F0D, 0xCCBC6149, 0xF4AD0EE5, 0xBC9EBE11, 0x848FD1BD,
0xE99ED468, 0xD18FBBC4, 0x99BC0B30, 0xA1AD649C, 0x09DB6AD8, 0x31CA0574, 0x79F9B580, 0x41E8DA2C,
0xA3DBBE2A, 0x9BCAD186, 0xD3F96172, 0xEBE80EDE, 0x439E009A, 0x7B8F6F36, 0x33BCDFC2, 0x0BADB06E,
0x66BCB5BB, 0x5EADDA17, 0x169E6AE3, 0x2E8F054F, 0x86F90B0B, 0xBEE864A7, 0xF6DBD453, 0xCECABBFF,
0x6EA2D55C, 0x56B3BAF0, 0x1E800A04, 0x269165A8, 0x8EE76BEC, 0xB6F60440, 0xFEC5B4B4, 0xC6D4DB18,
0xABC5DECD, 0x93D4B161, 0xDBE70195, 0xE3F66E39, 0x4B80607D, 0x73910FD1, 0x3BA2BF25, 0x03B3D089,
0xE180B48F, 0xD991DB23, 0x91A26BD7, 0xA9B3047B, 0x01C50A3F, 0x39D46593, 0x71E7D567, 0x49F6BACB,
0x24E7BF1E, 0x1CF6D0B2, 0x54C56046, 0x6CD40FEA, 0xC4A201AE, 0xFCB36E02, 0xB480DEF6, 0x8C91B15A,
0x750A600B, 0x4D1B0FA7, 0x0528BF53, 0x3D39D0FF, 0x954FDEBB, 0xAD5EB117, 0xE56D01E3, 0xDD7C6E4F,
0xB06D6B9A, 0x887C0436, 0xC04FB4C2, 0xF85EDB6E, 0x5028D52A, 0x6839BA86, 0x200A0A72, 0x181B65DE,
0xFA2801D8, 0xC2396E74, 0x8A0ADE80, 0xB21BB12C, 0x1A6DBF68, 0x227CD0C4, 0x6A4F6030, 0x525E0F9C,
0x3F4F0A49, 0x075E65E5, 0x4F6DD511, 0x777CBABD, 0xDF0AB4F9, 0xE71BDB55, 0xAF286BA1, 0x9739040D,
0x59F3BFF2, 0x61E2D05E, 0x29D160AA, 0x11C00F06, 0xB9B60142, 0x81A76EEE, 0xC994DE1A, 0xF185B1B6,
0x9C94B463, 0xA485DBCF, 0xECB66B3B, 0xD4A70497, 0x7CD10AD3, 0x44C0657F, 0x0CF3D58B, 0x34E2BA27,
0xD6D1DE21, 0xEEC0B18D, 0xA6F30179, 0x9EE26ED5, 0x36946091, 0x0E850F3D, 0x46B6BFC9, 0x7EA7D065,
0x13B6D5B0, 0x2BA7BA1C, 0x63940AE8, 0x5B856544, 0xF3F36B00, 0xCBE204AC, 0x83D1B458, 0xBBC0DBF4,
0x425B0AA5, 0x7A4A6509, 0x3279D5FD, 0x0A68BA51, 0xA21EB415, 0x9A0FDBB9, 0xD23C6B4D, 0xEA2D04E1,
0x873C0134, 0xBF2D6E98, 0xF71EDE6C, 0xCF0FB1C0, 0x6779BF84, 0x5F68D028, 0x175B60DC, 0x2F4A0F70,
0xCD796B76, 0xF56804DA, 0xBD5BB42E, 0x854ADB82, 0x2D3CD5C6, 0x152DBA6A, 0x5D1E0A9E, 0x650F6532,
0x081E60E7, 0x300F0F4B, 0x783CBFBF, 0x402DD013, 0xE85BDE57, 0xD04AB1FB, 0x9879010F, 0xA0686EA3
};
/*
* end of the CRC lookup table crc_tableil8_o64
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o72[256] =
{
0x00000000, 0xEF306B19, 0xDB8CA0C3, 0x34BCCBDA, 0xB2F53777, 0x5DC55C6E, 0x697997B4, 0x8649FCAD,
0x6006181F, 0x8F367306, 0xBB8AB8DC, 0x54BAD3C5, 0xD2F32F68, 0x3DC34471, 0x097F8FAB, 0xE64FE4B2,
0xC00C303E, 0x2F3C5B27, 0x1B8090FD, 0xF4B0FBE4, 0x72F90749, 0x9DC96C50, 0xA975A78A, 0x4645CC93,
0xA00A2821, 0x4F3A4338, 0x7B8688E2, 0x94B6E3FB, 0x12FF1F56, 0xFDCF744F, 0xC973BF95, 0x2643D48C,
0x85F4168D, 0x6AC47D94, 0x5E78B64E, 0xB148DD57, 0x370121FA, 0xD8314AE3, 0xEC8D8139, 0x03BDEA20,
0xE5F20E92, 0x0AC2658B, 0x3E7EAE51, 0xD14EC548, 0x570739E5, 0xB83752FC, 0x8C8B9926, 0x63BBF23F,
0x45F826B3, 0xAAC84DAA, 0x9E748670, 0x7144ED69, 0xF70D11C4, 0x183D7ADD, 0x2C81B107, 0xC3B1DA1E,
0x25FE3EAC, 0xCACE55B5, 0xFE729E6F, 0x1142F576, 0x970B09DB, 0x783B62C2, 0x4C87A918, 0xA3B7C201,
0x0E045BEB, 0xE13430F2, 0xD588FB28, 0x3AB89031, 0xBCF16C9C, 0x53C10785, 0x677DCC5F, 0x884DA746,
0x6E0243F4, 0x813228ED, 0xB58EE337, 0x5ABE882E, 0xDCF77483, 0x33C71F9A, 0x077BD440, 0xE84BBF59,
0xCE086BD5, 0x213800CC, 0x1584CB16, 0xFAB4A00F, 0x7CFD5CA2, 0x93CD37BB, 0xA771FC61, 0x48419778,
0xAE0E73CA, 0x413E18D3, 0x7582D309, 0x9AB2B810, 0x1CFB44BD, 0xF3CB2FA4, 0xC777E47E, 0x28478F67,
0x8BF04D66, 0x64C0267F, 0x507CEDA5, 0xBF4C86BC, 0x39057A11, 0xD6351108, 0xE289DAD2, 0x0DB9B1CB,
0xEBF65579, 0x04C63E60, 0x307AF5BA, 0xDF4A9EA3, 0x5903620E, 0xB6330917, 0x828FC2CD, 0x6DBFA9D4,
0x4BFC7D58, 0xA4CC1641, 0x9070DD9B, 0x7F40B682, 0xF9094A2F, 0x16392136, 0x2285EAEC, 0xCDB581F5,
0x2BFA6547, 0xC4CA0E5E, 0xF076C584, 0x1F46AE9D, 0x990F5230, 0x763F3929, 0x4283F2F3, 0xADB399EA,
0x1C08B7D6, 0xF338DCCF, 0xC7841715, 0x28B47C0C, 0xAEFD80A1, 0x41CDEBB8, 0x75712062, 0x9A414B7B,
0x7C0EAFC9, 0x933EC4D0, 0xA7820F0A, 0x48B26413, 0xCEFB98BE, 0x21CBF3A7, 0x1577387D, 0xFA475364,
0xDC0487E8, 0x3334ECF1, 0x0788272B, 0xE8B84C32, 0x6EF1B09F, 0x81C1DB86, 0xB57D105C, 0x5A4D7B45,
0xBC029FF7, 0x5332F4EE, 0x678E3F34, 0x88BE542D, 0x0EF7A880, 0xE1C7C399, 0xD57B0843, 0x3A4B635A,
0x99FCA15B, 0x76CCCA42, 0x42700198, 0xAD406A81, 0x2B09962C, 0xC439FD35, 0xF08536EF, 0x1FB55DF6,
0xF9FAB944, 0x16CAD25D, 0x22761987, 0xCD46729E, 0x4B0F8E33, 0xA43FE52A, 0x90832EF0, 0x7FB345E9,
0x59F09165, 0xB6C0FA7C, 0x827C31A6, 0x6D4C5ABF, 0xEB05A612, 0x0435CD0B, 0x308906D1, 0xDFB96DC8,
0x39F6897A, 0xD6C6E263, 0xE27A29B9, 0x0D4A42A0, 0x8B03BE0D, 0x6433D514, 0x508F1ECE, 0xBFBF75D7,
0x120CEC3D, 0xFD3C8724, 0xC9804CFE, 0x26B027E7, 0xA0F9DB4A, 0x4FC9B053, 0x7B757B89, 0x94451090,
0x720AF422, 0x9D3A9F3B, 0xA98654E1, 0x46B63FF8, 0xC0FFC355, 0x2FCFA84C, 0x1B736396, 0xF443088F,
0xD200DC03, 0x3D30B71A, 0x098C7CC0, 0xE6BC17D9, 0x60F5EB74, 0x8FC5806D, 0xBB794BB7, 0x544920AE,
0xB206C41C, 0x5D36AF05, 0x698A64DF, 0x86BA0FC6, 0x00F3F36B, 0xEFC39872, 0xDB7F53A8, 0x344F38B1,
0x97F8FAB0, 0x78C891A9, 0x4C745A73, 0xA344316A, 0x250DCDC7, 0xCA3DA6DE, 0xFE816D04, 0x11B1061D,
0xF7FEE2AF, 0x18CE89B6, 0x2C72426C, 0xC3422975, 0x450BD5D8, 0xAA3BBEC1, 0x9E87751B, 0x71B71E02,
0x57F4CA8E, 0xB8C4A197, 0x8C786A4D, 0x63480154, 0xE501FDF9, 0x0A3196E0, 0x3E8D5D3A, 0xD1BD3623,
0x37F2D291, 0xD8C2B988, 0xEC7E7252, 0x034E194B, 0x8507E5E6, 0x6A378EFF, 0x5E8B4525, 0xB1BB2E3C
};
/*
* end of the CRC lookup table crc_tableil8_o72
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o80[256] =
{
0x00000000, 0x68032CC8, 0xD0065990, 0xB8057558, 0xA5E0C5D1, 0xCDE3E919, 0x75E69C41, 0x1DE5B089,
0x4E2DFD53, 0x262ED19B, 0x9E2BA4C3, 0xF628880B, 0xEBCD3882, 0x83CE144A, 0x3BCB6112, 0x53C84DDA,
0x9C5BFAA6, 0xF458D66E, 0x4C5DA336, 0x245E8FFE, 0x39BB3F77, 0x51B813BF, 0xE9BD66E7, 0x81BE4A2F,
0xD27607F5, 0xBA752B3D, 0x02705E65, 0x6A7372AD, 0x7796C224, 0x1F95EEEC, 0xA7909BB4, 0xCF93B77C,
0x3D5B83BD, 0x5558AF75, 0xED5DDA2D, 0x855EF6E5, 0x98BB466C, 0xF0B86AA4, 0x48BD1FFC, 0x20BE3334,
0x73767EEE, 0x1B755226, 0xA370277E, 0xCB730BB6, 0xD696BB3F, 0xBE9597F7, 0x0690E2AF, 0x6E93CE67,
0xA100791B, 0xC90355D3, 0x7106208B, 0x19050C43, 0x04E0BCCA, 0x6CE39002, 0xD4E6E55A, 0xBCE5C992,
0xEF2D8448, 0x872EA880, 0x3F2BDDD8, 0x5728F110, 0x4ACD4199, 0x22CE6D51, 0x9ACB1809, 0xF2C834C1,
0x7AB7077A, 0x12B42BB2, 0xAAB15EEA, 0xC2B27222, 0xDF57C2AB, 0xB754EE63, 0x0F519B3B, 0x6752B7F3,
0x349AFA29, 0x5C99D6E1, 0xE49CA3B9, 0x8C9F8F71, 0x917A3FF8, 0xF9791330, 0x417C6668, 0x297F4AA0,
0xE6ECFDDC, 0x8EEFD114, 0x36EAA44C, 0x5EE98884, 0x430C380D, 0x2B0F14C5, 0x930A619D, 0xFB094D55,
0xA8C1008F, 0xC0C22C47, 0x78C7591F, 0x10C475D7, 0x0D21C55E, 0x6522E996, 0xDD279CCE, 0xB524B006,
0x47EC84C7, 0x2FEFA80F, 0x97EADD57, 0xFFE9F19F, 0xE20C4116, 0x8A0F6DDE, 0x320A1886, 0x5A09344E,
0x09C17994, 0x61C2555C, 0xD9C72004, 0xB1C40CCC, 0xAC21BC45, 0xC422908D, 0x7C27E5D5, 0x1424C91D,
0xDBB77E61, 0xB3B452A9, 0x0BB127F1, 0x63B20B39, 0x7E57BBB0, 0x16549778, 0xAE51E220, 0xC652CEE8,
0x959A8332, 0xFD99AFFA, 0x459CDAA2, 0x2D9FF66A, 0x307A46E3, 0x58796A2B, 0xE07C1F73, 0x887F33BB,
0xF56E0EF4, 0x9D6D223C, 0x25685764, 0x4D6B7BAC, 0x508ECB25, 0x388DE7ED, 0x808892B5, 0xE88BBE7D,
0xBB43F3A7, 0xD340DF6F, 0x6B45AA37, 0x034686FF, 0x1EA33676, 0x76A01ABE, 0xCEA56FE6, 0xA6A6432E,
0x6935F452, 0x0136D89A, 0xB933ADC2, 0xD130810A, 0xCCD53183, 0xA4D61D4B, 0x1CD36813, 0x74D044DB,
0x27180901, 0x4F1B25C9, 0xF71E5091, 0x9F1D7C59, 0x82F8CCD0, 0xEAFBE018, 0x52FE9540, 0x3AFDB988,
0xC8358D49, 0xA036A181, 0x1833D4D9, 0x7030F811, 0x6DD54898, 0x05D66450, 0xBDD31108, 0xD5D03DC0,
0x8618701A, 0xEE1B5CD2, 0x561E298A, 0x3E1D0542, 0x23F8B5CB, 0x4BFB9903, 0xF3FEEC5B, 0x9BFDC093,
0x546E77EF, 0x3C6D5B27, 0x84682E7F, 0xEC6B02B7, 0xF18EB23E, 0x998D9EF6, 0x2188EBAE, 0x498BC766,
0x1A438ABC, 0x7240A674, 0xCA45D32C, 0xA246FFE4, 0xBFA34F6D, 0xD7A063A5, 0x6FA516FD, 0x07A63A35,
0x8FD9098E, 0xE7DA2546, 0x5FDF501E, 0x37DC7CD6, 0x2A39CC5F, 0x423AE097, 0xFA3F95CF, 0x923CB907,
0xC1F4F4DD, 0xA9F7D815, 0x11F2AD4D, 0x79F18185, 0x6414310C, 0x0C171DC4, 0xB412689C, 0xDC114454,
0x1382F328, 0x7B81DFE0, 0xC384AAB8, 0xAB878670, 0xB66236F9, 0xDE611A31, 0x66646F69, 0x0E6743A1,
0x5DAF0E7B, 0x35AC22B3, 0x8DA957EB, 0xE5AA7B23, 0xF84FCBAA, 0x904CE762, 0x2849923A, 0x404ABEF2,
0xB2828A33, 0xDA81A6FB, 0x6284D3A3, 0x0A87FF6B, 0x17624FE2, 0x7F61632A, 0xC7641672, 0xAF673ABA,
0xFCAF7760, 0x94AC5BA8, 0x2CA92EF0, 0x44AA0238, 0x594FB2B1, 0x314C9E79, 0x8949EB21, 0xE14AC7E9,
0x2ED97095, 0x46DA5C5D, 0xFEDF2905, 0x96DC05CD, 0x8B39B544, 0xE33A998C, 0x5B3FECD4, 0x333CC01C,
0x60F48DC6, 0x08F7A10E, 0xB0F2D456, 0xD8F1F89E, 0xC5144817, 0xAD1764DF, 0x15121187, 0x7D113D4F
};
/*
* end of the CRC lookup table crc_tableil8_o80
*/
/*
* The following CRC lookup table was generated automagically using the
* following model parameters:
*
* Generator Polynomial = ................. 0x1EDC6F41
* Generator Polynomial Length = .......... 32 bits
* Reflected Bits = ....................... TRUE
* Table Generation Offset = .............. 32 bits
* Number of Slices = ..................... 8 slices
* Slice Lengths = ........................ 8 8 8 8 8 8 8 8
* Directory Name = ....................... .\
* File Name = ............................ 8x256_tables.c
*/
static const uint32_t sctp_crc_tableil8_o88[256] =
{
0x00000000, 0x493C7D27, 0x9278FA4E, 0xDB448769, 0x211D826D, 0x6821FF4A, 0xB3657823, 0xFA590504,
0x423B04DA, 0x0B0779FD, 0xD043FE94, 0x997F83B3, 0x632686B7, 0x2A1AFB90, 0xF15E7CF9, 0xB86201DE,
0x847609B4, 0xCD4A7493, 0x160EF3FA, 0x5F328EDD, 0xA56B8BD9, 0xEC57F6FE, 0x37137197, 0x7E2F0CB0,
0xC64D0D6E, 0x8F717049, 0x5435F720, 0x1D098A07, 0xE7508F03, 0xAE6CF224, 0x7528754D, 0x3C14086A,
0x0D006599, 0x443C18BE, 0x9F789FD7, 0xD644E2F0, 0x2C1DE7F4, 0x65219AD3, 0xBE651DBA, 0xF759609D,
0x4F3B6143, 0x06071C64, 0xDD439B0D, 0x947FE62A, 0x6E26E32E, 0x271A9E09, 0xFC5E1960, 0xB5626447,
0x89766C2D, 0xC04A110A, 0x1B0E9663, 0x5232EB44, 0xA86BEE40, 0xE1579367, 0x3A13140E, 0x732F6929,
0xCB4D68F7, 0x827115D0, 0x593592B9, 0x1009EF9E, 0xEA50EA9A, 0xA36C97BD, 0x782810D4, 0x31146DF3,
0x1A00CB32, 0x533CB615, 0x8878317C, 0xC1444C5B, 0x3B1D495F, 0x72213478, 0xA965B311, 0xE059CE36,
0x583BCFE8, 0x1107B2CF, 0xCA4335A6, 0x837F4881, 0x79264D85, 0x301A30A2, 0xEB5EB7CB, 0xA262CAEC,
0x9E76C286, 0xD74ABFA1, 0x0C0E38C8, 0x453245EF, 0xBF6B40EB, 0xF6573DCC, 0x2D13BAA5, 0x642FC782,
0xDC4DC65C, 0x9571BB7B, 0x4E353C12, 0x07094135, 0xFD504431, 0xB46C3916, 0x6F28BE7F, 0x2614C358,
0x1700AEAB, 0x5E3CD38C, 0x857854E5, 0xCC4429C2, 0x361D2CC6, 0x7F2151E1, 0xA465D688, 0xED59ABAF,
0x553BAA71, 0x1C07D756, 0xC743503F, 0x8E7F2D18, 0x7426281C, 0x3D1A553B, 0xE65ED252, 0xAF62AF75,
0x9376A71F, 0xDA4ADA38, 0x010E5D51, 0x48322076, 0xB26B2572, 0xFB575855, 0x2013DF3C, 0x692FA21B,
0xD14DA3C5, 0x9871DEE2, 0x4335598B, 0x0A0924AC, 0xF05021A8, 0xB96C5C8F, 0x6228DBE6, 0x2B14A6C1,
0x34019664, 0x7D3DEB43, 0xA6796C2A, 0xEF45110D, 0x151C1409, 0x5C20692E, 0x8764EE47, 0xCE589360,
0x763A92BE, 0x3F06EF99, 0xE44268F0, 0xAD7E15D7, 0x572710D3, 0x1E1B6DF4, 0xC55FEA9D, 0x8C6397BA,
0xB0779FD0, 0xF94BE2F7, 0x220F659E, 0x6B3318B9, 0x916A1DBD, 0xD856609A, 0x0312E7F3, 0x4A2E9AD4,
0xF24C9B0A, 0xBB70E62D, 0x60346144, 0x29081C63, 0xD3511967, 0x9A6D6440, 0x4129E329, 0x08159E0E,
0x3901F3FD, 0x703D8EDA, 0xAB7909B3, 0xE2457494, 0x181C7190, 0x51200CB7, 0x8A648BDE, 0xC358F6F9,
0x7B3AF727, 0x32068A00, 0xE9420D69, 0xA07E704E, 0x5A27754A, 0x131B086D, 0xC85F8F04, 0x8163F223,
0xBD77FA49, 0xF44B876E, 0x2F0F0007, 0x66337D20, 0x9C6A7824, 0xD5560503, 0x0E12826A, 0x472EFF4D,
0xFF4CFE93, 0xB67083B4, 0x6D3404DD, 0x240879FA, 0xDE517CFE, 0x976D01D9, 0x4C2986B0, 0x0515FB97,
0x2E015D56, 0x673D2071, 0xBC79A718, 0xF545DA3F, 0x0F1CDF3B, 0x4620A21C, 0x9D642575, 0xD4585852,
0x6C3A598C, 0x250624AB, 0xFE42A3C2, 0xB77EDEE5, 0x4D27DBE1, 0x041BA6C6, 0xDF5F21AF, 0x96635C88,
0xAA7754E2, 0xE34B29C5, 0x380FAEAC, 0x7133D38B, 0x8B6AD68F, 0xC256ABA8, 0x19122CC1, 0x502E51E6,
0xE84C5038, 0xA1702D1F, 0x7A34AA76, 0x3308D751, 0xC951D255, 0x806DAF72, 0x5B29281B, 0x1215553C,
0x230138CF, 0x6A3D45E8, 0xB179C281, 0xF845BFA6, 0x021CBAA2, 0x4B20C785, 0x906440EC, 0xD9583DCB,
0x613A3C15, 0x28064132, 0xF342C65B, 0xBA7EBB7C, 0x4027BE78, 0x091BC35F, 0xD25F4436, 0x9B633911,
0xA777317B, 0xEE4B4C5C, 0x350FCB35, 0x7C33B612, 0x866AB316, 0xCF56CE31, 0x14124958, 0x5D2E347F,
0xE54C35A1, 0xAC704886, 0x7734CFEF, 0x3E08B2C8, 0xC451B7CC, 0x8D6DCAEB, 0x56294D82, 0x1F1530A5
};
/*
* end of the CRC lookup table crc_tableil8_o88
*/
static uint32_t
sctp_crc32c_sb8_64_bit(uint32_t crc,
const unsigned char *p_buf,
uint32_t length,
uint32_t init_bytes)
{
uint32_t li;
uint32_t term1, term2;
uint32_t running_length;
uint32_t end_bytes;
running_length = ((length - init_bytes) / 8) * 8;
end_bytes = length - init_bytes - running_length;
for (li = 0; li < init_bytes; li++)
crc = sctp_crc_tableil8_o32[(crc ^ *p_buf++) & 0x000000FF] ^
(crc >> 8);
for (li = 0; li < running_length / 8; li++) {
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
crc ^= *p_buf++;
crc ^= (*p_buf++) << 8;
crc ^= (*p_buf++) << 16;
crc ^= (*p_buf++) << 24;
#else
crc ^= *(const uint32_t *) p_buf;
p_buf += 4;
#endif
term1 = sctp_crc_tableil8_o88[crc & 0x000000FF] ^
sctp_crc_tableil8_o80[(crc >> 8) & 0x000000FF];
term2 = crc >> 16;
crc = term1 ^
sctp_crc_tableil8_o72[term2 & 0x000000FF] ^
sctp_crc_tableil8_o64[(term2 >> 8) & 0x000000FF];
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
crc ^= sctp_crc_tableil8_o56[*p_buf++];
crc ^= sctp_crc_tableil8_o48[*p_buf++];
crc ^= sctp_crc_tableil8_o40[*p_buf++];
crc ^= sctp_crc_tableil8_o32[*p_buf++];
#else
term1 = sctp_crc_tableil8_o56[(*(const uint32_t *) p_buf) & 0x000000FF] ^
sctp_crc_tableil8_o48[((*(const uint32_t *) p_buf) >> 8) & 0x000000FF];
term2 = (*(const uint32_t *) p_buf) >> 16;
crc = crc ^
term1 ^
sctp_crc_tableil8_o40[term2 & 0x000000FF] ^
sctp_crc_tableil8_o32[(term2 >> 8) & 0x000000FF];
p_buf += 4;
#endif
}
for (li = 0; li < end_bytes; li++)
crc = sctp_crc_tableil8_o32[(crc ^ *p_buf++) & 0x000000FF] ^
(crc >> 8);
return (crc);
}
/**
*
* Routine Description:
*
* warms the tables
*
* Arguments:
*
* none
*
* Return value:
*
* none
*/
static uint32_t
multitable_crc32c(uint32_t crc32c,
const unsigned char *buffer,
unsigned int length)
{
uint32_t to_even_word;
if (length == 0) {
return (crc32c);
}
to_even_word = (4 - (((uintptr_t) buffer) & 0x3));
return (sctp_crc32c_sb8_64_bit(crc32c, buffer, length, to_even_word));
}
static const uint32_t sctp_crc_c[256] = {
0x00000000, 0xF26B8303, 0xE13B70F7, 0x1350F3F4,
0xC79A971F, 0x35F1141C, 0x26A1E7E8, 0xD4CA64EB,
0x8AD958CF, 0x78B2DBCC, 0x6BE22838, 0x9989AB3B,
0x4D43CFD0, 0xBF284CD3, 0xAC78BF27, 0x5E133C24,
0x105EC76F, 0xE235446C, 0xF165B798, 0x030E349B,
0xD7C45070, 0x25AFD373, 0x36FF2087, 0xC494A384,
0x9A879FA0, 0x68EC1CA3, 0x7BBCEF57, 0x89D76C54,
0x5D1D08BF, 0xAF768BBC, 0xBC267848, 0x4E4DFB4B,
0x20BD8EDE, 0xD2D60DDD, 0xC186FE29, 0x33ED7D2A,
0xE72719C1, 0x154C9AC2, 0x061C6936, 0xF477EA35,
0xAA64D611, 0x580F5512, 0x4B5FA6E6, 0xB93425E5,
0x6DFE410E, 0x9F95C20D, 0x8CC531F9, 0x7EAEB2FA,
0x30E349B1, 0xC288CAB2, 0xD1D83946, 0x23B3BA45,
0xF779DEAE, 0x05125DAD, 0x1642AE59, 0xE4292D5A,
0xBA3A117E, 0x4851927D, 0x5B016189, 0xA96AE28A,
0x7DA08661, 0x8FCB0562, 0x9C9BF696, 0x6EF07595,
0x417B1DBC, 0xB3109EBF, 0xA0406D4B, 0x522BEE48,
0x86E18AA3, 0x748A09A0, 0x67DAFA54, 0x95B17957,
0xCBA24573, 0x39C9C670, 0x2A993584, 0xD8F2B687,
0x0C38D26C, 0xFE53516F, 0xED03A29B, 0x1F682198,
0x5125DAD3, 0xA34E59D0, 0xB01EAA24, 0x42752927,
0x96BF4DCC, 0x64D4CECF, 0x77843D3B, 0x85EFBE38,
0xDBFC821C, 0x2997011F, 0x3AC7F2EB, 0xC8AC71E8,
0x1C661503, 0xEE0D9600, 0xFD5D65F4, 0x0F36E6F7,
0x61C69362, 0x93AD1061, 0x80FDE395, 0x72966096,
0xA65C047D, 0x5437877E, 0x4767748A, 0xB50CF789,
0xEB1FCBAD, 0x197448AE, 0x0A24BB5A, 0xF84F3859,
0x2C855CB2, 0xDEEEDFB1, 0xCDBE2C45, 0x3FD5AF46,
0x7198540D, 0x83F3D70E, 0x90A324FA, 0x62C8A7F9,
0xB602C312, 0x44694011, 0x5739B3E5, 0xA55230E6,
0xFB410CC2, 0x092A8FC1, 0x1A7A7C35, 0xE811FF36,
0x3CDB9BDD, 0xCEB018DE, 0xDDE0EB2A, 0x2F8B6829,
0x82F63B78, 0x709DB87B, 0x63CD4B8F, 0x91A6C88C,
0x456CAC67, 0xB7072F64, 0xA457DC90, 0x563C5F93,
0x082F63B7, 0xFA44E0B4, 0xE9141340, 0x1B7F9043,
0xCFB5F4A8, 0x3DDE77AB, 0x2E8E845F, 0xDCE5075C,
0x92A8FC17, 0x60C37F14, 0x73938CE0, 0x81F80FE3,
0x55326B08, 0xA759E80B, 0xB4091BFF, 0x466298FC,
0x1871A4D8, 0xEA1A27DB, 0xF94AD42F, 0x0B21572C,
0xDFEB33C7, 0x2D80B0C4, 0x3ED04330, 0xCCBBC033,
0xA24BB5A6, 0x502036A5, 0x4370C551, 0xB11B4652,
0x65D122B9, 0x97BAA1BA, 0x84EA524E, 0x7681D14D,
0x2892ED69, 0xDAF96E6A, 0xC9A99D9E, 0x3BC21E9D,
0xEF087A76, 0x1D63F975, 0x0E330A81, 0xFC588982,
0xB21572C9, 0x407EF1CA, 0x532E023E, 0xA145813D,
0x758FE5D6, 0x87E466D5, 0x94B49521, 0x66DF1622,
0x38CC2A06, 0xCAA7A905, 0xD9F75AF1, 0x2B9CD9F2,
0xFF56BD19, 0x0D3D3E1A, 0x1E6DCDEE, 0xEC064EED,
0xC38D26C4, 0x31E6A5C7, 0x22B65633, 0xD0DDD530,
0x0417B1DB, 0xF67C32D8, 0xE52CC12C, 0x1747422F,
0x49547E0B, 0xBB3FFD08, 0xA86F0EFC, 0x5A048DFF,
0x8ECEE914, 0x7CA56A17, 0x6FF599E3, 0x9D9E1AE0,
0xD3D3E1AB, 0x21B862A8, 0x32E8915C, 0xC083125F,
0x144976B4, 0xE622F5B7, 0xF5720643, 0x07198540,
0x590AB964, 0xAB613A67, 0xB831C993, 0x4A5A4A90,
0x9E902E7B, 0x6CFBAD78, 0x7FAB5E8C, 0x8DC0DD8F,
0xE330A81A, 0x115B2B19, 0x020BD8ED, 0xF0605BEE,
0x24AA3F05, 0xD6C1BC06, 0xC5914FF2, 0x37FACCF1,
0x69E9F0D5, 0x9B8273D6, 0x88D28022, 0x7AB90321,
0xAE7367CA, 0x5C18E4C9, 0x4F48173D, 0xBD23943E,
0xF36E6F75, 0x0105EC76, 0x12551F82, 0xE03E9C81,
0x34F4F86A, 0xC69F7B69, 0xD5CF889D, 0x27A40B9E,
0x79B737BA, 0x8BDCB4B9, 0x988C474D, 0x6AE7C44E,
0xBE2DA0A5, 0x4C4623A6, 0x5F16D052, 0xAD7D5351,
};
#define SCTP_CRC32C(c,d) (c=(c>>8)^sctp_crc_c[(c^(d))&0xFF])
static uint32_t
singletable_crc32c(uint32_t crc32c,
const unsigned char *buffer,
unsigned int length)
{
unsigned int i;
for (i = 0; i < length; i++) {
SCTP_CRC32C(crc32c, buffer[i]);
}
return (crc32c);
}
uint32_t
calculate_crc32c(uint32_t crc32c,
const unsigned char *buffer,
unsigned int length)
{
if (length < 4) {
return (singletable_crc32c(crc32c, buffer, length));
} else {
return (multitable_crc32c(crc32c, buffer, length));
}
}
uint32_t
sctp_finalize_crc32c(uint32_t crc32c)
{
uint32_t result;
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
uint8_t byte0, byte1, byte2, byte3;
#endif
/* Complement the result */
result = ~crc32c;
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
/*
* For BIG-ENDIAN platforms the result is in little-endian form. So we
* must swap the bytes to return the result in network byte order.
*/
byte0 = result & 0x000000ff;
byte1 = (result >> 8) & 0x000000ff;
byte2 = (result >> 16) & 0x000000ff;
byte3 = (result >> 24) & 0x000000ff;
crc32c = ((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3);
#else
/*
* For LITTLE ENDIAN platforms the result is in already in network
* byte order.
*/
crc32c = result;
#endif
return (crc32c);
}
/*
* Compute the SCTP checksum in network byte order for a given mbuf chain m
* which contains an SCTP packet starting at offset.
* Since this function is also called by ipfw, don't assume that
* it is compiled on a kernel with SCTP support.
*/
uint32_t
sctp_calculate_cksum(const void *data, quint32 size)
{
uint32_t base = 0xffffffff;
base = calculate_crc32c(base, static_cast<const unsigned char *>(data), size);
base = sctp_finalize_crc32c(base);
return (base);
}
}
|
#include "source/common/api/os_sys_calls_impl.h"
#include "source/common/common/assert.h"
#include "source/common/common/fmt.h"
#include "source/common/common/thread_impl.h"
#include "source/common/filesystem/watcher_impl.h"
namespace Envoy {
namespace Filesystem {
WatcherImpl::WatcherImpl(Event::Dispatcher& dispatcher, Filesystem::Instance& file_system)
: file_system_(file_system), os_sys_calls_(Api::OsSysCallsSingleton::get()) {
os_fd_t socks[2];
Api::SysCallIntResult result = os_sys_calls_.socketpair(AF_INET, SOCK_STREAM, IPPROTO_TCP, socks);
ASSERT(result.return_value_ == 0);
read_handle_ = std::make_unique<Network::IoSocketHandleImpl>(socks[0], false, AF_INET);
result = read_handle_->setBlocking(false);
ASSERT(result.return_value_ == 0);
write_handle_ = std::make_unique<Network::IoSocketHandleImpl>(socks[1], false, AF_INET);
result = write_handle_->setBlocking(false);
ASSERT(result.return_value_ == 0);
read_handle_->initializeFileEvent(
dispatcher,
[this](uint32_t events) -> void {
ASSERT(events == Event::FileReadyType::Read);
onDirectoryEvent();
},
Event::FileTriggerType::Level, Event::FileReadyType::Read);
thread_exit_event_ = ::CreateEvent(nullptr, false, false, nullptr);
ASSERT(thread_exit_event_ != NULL);
keep_watching_ = true;
// See comments in WorkerImpl::start for the naming convention.
Thread::Options options{absl::StrCat("wat:", dispatcher.name())};
watch_thread_ = thread_factory_.createThread([this]() -> void { watchLoop(); }, options);
}
WatcherImpl::~WatcherImpl() {
const BOOL rc = ::SetEvent(thread_exit_event_);
ASSERT(rc);
watch_thread_->join();
for (auto& entry : callback_map_) {
::CloseHandle(entry.second->dir_handle_);
::CloseHandle(entry.second->overlapped_.hEvent);
}
::CloseHandle(thread_exit_event_);
}
void WatcherImpl::addWatch(absl::string_view path, uint32_t events, OnChangedCb cb) {
if (path == Platform::null_device_path) {
return;
}
const PathSplitResult result = file_system_.splitPathFromFilename(path);
// ReadDirectoryChangesW only has a Unicode version, so we need
// to use wide strings here
const std::wstring directory = wstring_converter_.from_bytes(std::string(result.directory_));
const std::wstring file = wstring_converter_.from_bytes(std::string(result.file_));
const HANDLE dir_handle = CreateFileW(
directory.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
if (dir_handle == INVALID_HANDLE_VALUE) {
throw EnvoyException(
fmt::format("unable to open directory {}: {}", result.directory_, GetLastError()));
}
std::string fii_key(sizeof(FILE_ID_INFO), '\0');
RELEASE_ASSERT(
GetFileInformationByHandleEx(dir_handle, FileIdInfo, &fii_key[0], sizeof(FILE_ID_INFO)),
fmt::format("unable to identify directory {}: {}", result.directory_, GetLastError()));
if (callback_map_.find(fii_key) != callback_map_.end()) {
CloseHandle(dir_handle);
} else {
callback_map_[fii_key] = std::make_unique<DirectoryWatch>();
callback_map_[fii_key]->dir_handle_ = dir_handle;
callback_map_[fii_key]->buffer_.resize(16384);
callback_map_[fii_key]->watcher_ = this;
// According to Microsoft docs, "the hEvent member of the OVERLAPPED structure is not used by
// the system, so you can use it yourself". We will use it for synchronization of the completion
// routines
HANDLE event_handle = ::CreateEvent(nullptr, false, false, nullptr);
RELEASE_ASSERT(event_handle, fmt::format("CreateEvent failed: {}", GetLastError()));
callback_map_[fii_key]->overlapped_.hEvent = event_handle;
dir_watch_complete_events_.push_back(event_handle);
// send the first ReadDirectoryChangesW request to our watch thread. This ensures that all of
// the io completion routines will run in that thread
DWORD rc = ::QueueUserAPC(&issueFirstRead,
static_cast<Thread::ThreadImplWin32*>(watch_thread_.get())->handle(),
reinterpret_cast<ULONG_PTR>(callback_map_[fii_key].get()));
RELEASE_ASSERT(rc, fmt::format("QueueUserAPC failed: {}", GetLastError()));
// wait for issueFirstRead to confirm that it has issued a call to ReadDirectoryChangesW
rc = ::WaitForSingleObject(event_handle, INFINITE);
RELEASE_ASSERT(rc == WAIT_OBJECT_0,
fmt::format("WaitForSingleObject failed: {}", GetLastError()));
ENVOY_LOG(debug, "created watch for directory: '{}' handle: {}", result.directory_, dir_handle);
}
callback_map_[fii_key]->watches_.push_back({file, events, cb});
ENVOY_LOG(debug, "added watch for file '{}' in directory '{}'", result.file_, result.directory_);
}
void WatcherImpl::onDirectoryEvent() {
while (true) {
char data = 0;
const auto result = read_handle_->recv(&data, sizeof(data), 0);
if (result.err_ && result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) {
return;
}
RELEASE_ASSERT(result.err_ == nullptr, fmt::format("recv errored: {}", result.err_));
if (data == 0) {
// no callbacks to run; this is just a notification that a DirectoryWatch exited
return;
}
CbClosure callback;
bool exists = active_callbacks_.try_pop(callback);
RELEASE_ASSERT(exists, "expected callback, found none");
ENVOY_LOG(debug, "executing callback");
callback();
}
}
void WatcherImpl::issueFirstRead(ULONG_PTR param) {
DirectoryWatch* dir_watch = reinterpret_cast<DirectoryWatch*>(param);
// Since the first member in each DirectoryWatch is an OVERLAPPED, we can pass
// a pointer to DirectoryWatch as the OVERLAPPED for ReadDirectoryChangesW. Then, the
// completion routine can use its OVERLAPPED* parameter to access the DirectoryWatch see:
// https://docs.microsoft.com/en-us/windows/desktop/ipc/named-pipe-server-using-completion-routines
ReadDirectoryChangesW(dir_watch->dir_handle_, &(dir_watch->buffer_[0]),
dir_watch->buffer_.capacity(), false,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, nullptr,
reinterpret_cast<LPOVERLAPPED>(param), &directoryChangeCompletion);
const BOOL rc = ::SetEvent(dir_watch->overlapped_.hEvent);
ASSERT(rc);
}
void WatcherImpl::endDirectoryWatch(Network::IoHandle& io_handle, HANDLE event_handle) {
const BOOL rc = ::SetEvent(event_handle);
ASSERT(rc);
// let libevent know that a ReadDirectoryChangesW call returned
Buffer::OwnedImpl buffer;
constexpr absl::string_view data{"a"};
buffer.add(data);
auto result = io_handle.write(buffer);
RELEASE_ASSERT(result.return_value_ == 1,
fmt::format("failed to write 1 byte: {}", result.err_->getErrorDetails()));
}
void WatcherImpl::directoryChangeCompletion(DWORD err, DWORD num_bytes, LPOVERLAPPED overlapped) {
DirectoryWatch* dir_watch = reinterpret_cast<DirectoryWatch*>(overlapped);
WatcherImpl* watcher = dir_watch->watcher_;
PFILE_NOTIFY_INFORMATION fni = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(&dir_watch->buffer_[0]);
if (err == ERROR_OPERATION_ABORTED) {
ENVOY_LOG(debug, "ReadDirectoryChangesW aborted, exiting");
endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent);
return;
} else if (err != 0) {
ENVOY_LOG(error, "ReadDirectoryChangesW errored: {}, exiting", err);
endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent);
return;
} else if (num_bytes < sizeof(_FILE_NOTIFY_INFORMATION)) {
ENVOY_LOG(error, "ReadDirectoryChangesW returned {} bytes, expected {}, exiting", num_bytes,
sizeof(_FILE_NOTIFY_INFORMATION));
endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent);
return;
}
DWORD next_entry = 0;
do {
fni = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(reinterpret_cast<char*>(fni) + next_entry);
// the length of the file name is given in bytes, not wide characters
std::wstring file(fni->FileName, fni->FileNameLength / 2);
ENVOY_LOG(debug, "notification: handle: {} action: {:x} file: {}", dir_watch->dir_handle_,
fni->Action, watcher->wstring_converter_.to_bytes(file));
uint32_t events = 0;
if (fni->Action == FILE_ACTION_RENAMED_NEW_NAME) {
events |= Events::MovedTo;
}
if (fni->Action == FILE_ACTION_MODIFIED) {
events |= Events::Modified;
}
constexpr absl::string_view data{"a"};
for (FileWatch& watch : dir_watch->watches_) {
if (watch.file_ == file && (watch.events_ & events)) {
ENVOY_LOG(debug, "matched callback: file: {}", watcher->wstring_converter_.to_bytes(file));
const auto cb = watch.cb_;
const auto cb_closure = [cb, events]() -> void { cb(events); };
watcher->active_callbacks_.push(cb_closure);
// write a byte to the other end of the socket that libevent is watching
// this tells the libevent callback to pull this callback off the active_callbacks_
// queue. We do this so that the callbacks are executed in the main libevent loop,
// not in this completion routine
Buffer::RawSlice buffer{(void*)data.data(), 1};
auto result = watcher->write_handle_->writev(&buffer, 1);
RELEASE_ASSERT(result.return_value_ == 1,
fmt::format("failed to write 1 byte: {}", result.err_->getErrorDetails()));
}
}
next_entry = fni->NextEntryOffset;
} while (next_entry != 0);
if (!watcher->keep_watching_.load()) {
ENVOY_LOG(debug, "ending watch on directory: handle: {}", dir_watch->dir_handle_);
endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent);
return;
}
ReadDirectoryChangesW(dir_watch->dir_handle_, &(dir_watch->buffer_[0]),
dir_watch->buffer_.capacity(), false,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, nullptr,
overlapped, directoryChangeCompletion);
}
void WatcherImpl::watchLoop() {
while (keep_watching_.load()) {
DWORD wait = WaitForSingleObjectEx(thread_exit_event_, INFINITE, true);
switch (wait) {
case WAIT_OBJECT_0:
// object is getting destroyed, exit the loop
keep_watching_.store(false);
break;
case WAIT_IO_COMPLETION:
// an IO completion routine finished, nothing to do
break;
default:
ENVOY_LOG(error, "WaitForSingleObjectEx: {}, GetLastError: {}, exiting", wait,
GetLastError());
keep_watching_.store(false);
}
}
for (auto& entry : callback_map_) {
::CancelIoEx(entry.second->dir_handle_, nullptr);
}
const int num_directories = dir_watch_complete_events_.size();
if (num_directories > 0) {
while (true) {
DWORD wait = ::WaitForMultipleObjectsEx(num_directories, &dir_watch_complete_events_[0], true,
INFINITE, true);
if (WAIT_OBJECT_0 <= wait && wait < (WAIT_OBJECT_0 + num_directories)) {
// we have no pending IO remaining
return;
} else if (wait == WAIT_IO_COMPLETION) {
// an io completion routine finished, keep waiting
continue;
} else {
ENVOY_LOG(error, "WaitForMultipleObjectsEx: {}, GetLastError: {}, exiting", wait,
GetLastError());
return;
}
}
}
}
} // namespace Filesystem
} // namespace Envoy
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#if defined(__sgi)
#error "iconv not supported on IRIX"
#else
#include <iconv.h>
int main(int, char **)
{
iconv_t x = iconv_open("", "");
char *inp;
char *outp;
size_t inbytes, outbytes;
iconv(x, &inp, &inbytes, &outp, &outbytes);
iconv_close(x);
return 0;
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.