commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
540f95e9bfcc69bb8e601bff604bff674decb27a
|
wangle/acceptor/SSLAcceptorHandshakeHelper.cpp
|
wangle/acceptor/SSLAcceptorHandshakeHelper.cpp
|
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <wangle/acceptor/SSLAcceptorHandshakeHelper.h>
#include <string>
#include <wangle/acceptor/SecureTransportType.h>
namespace wangle {
static const std::string empty_string;
using namespace folly;
void SSLAcceptorHandshakeHelper::start(
folly::AsyncSSLSocket::UniquePtr sock,
AcceptorHandshakeHelper::Callback* callback) noexcept {
socket_ = std::move(sock);
callback_ = callback;
if (acceptor_->getParseClientHello()) {
socket_->enableClientHelloParsing();
}
socket_->sslAccept(this);
}
void SSLAcceptorHandshakeHelper::handshakeSuc(AsyncSSLSocket* sock) noexcept {
const unsigned char* nextProto = nullptr;
unsigned nextProtoLength = 0;
sock->getSelectedNextProtocol(&nextProto, &nextProtoLength);
if (VLOG_IS_ON(3)) {
if (nextProto) {
VLOG(3) << "Client selected next protocol " <<
std::string((const char*)nextProto, nextProtoLength);
} else {
VLOG(3) << "Client did not select a next protocol";
}
}
// fill in SSL-related fields from TransportInfo
// the other fields like RTT are filled in the Acceptor
tinfo_.ssl = true;
tinfo_.acceptTime = acceptTime_;
tinfo_.sslSetupTime = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - acceptTime_
);
tinfo_.sslSetupBytesRead = sock->getRawBytesReceived();
tinfo_.sslSetupBytesWritten = sock->getRawBytesWritten();
tinfo_.sslServerName = sock->getSSLServerName() ?
std::make_shared<std::string>(sock->getSSLServerName()) : nullptr;
tinfo_.sslCipher = sock->getNegotiatedCipherName() ?
std::make_shared<std::string>(sock->getNegotiatedCipherName()) : nullptr;
tinfo_.sslVersion = sock->getSSLVersion();
const char* sigAlgName = sock->getSSLCertSigAlgName();
tinfo_.sslCertSigAlgName =
std::make_shared<std::string>(sigAlgName ? sigAlgName : "");
tinfo_.sslCertSize = sock->getSSLCertSize();
tinfo_.sslResume = SSLUtil::getResumeState(sock);
tinfo_.sslClientCiphers = std::make_shared<std::string>();
sock->getSSLClientCiphers(*tinfo_.sslClientCiphers);
tinfo_.sslServerCiphers = std::make_shared<std::string>();
sock->getSSLServerCiphers(*tinfo_.sslServerCiphers);
tinfo_.sslClientComprMethods =
std::make_shared<std::string>(sock->getSSLClientComprMethods());
tinfo_.sslClientExts =
std::make_shared<std::string>(sock->getSSLClientExts());
tinfo_.sslClientSigAlgs =
std::make_shared<std::string>(sock->getSSLClientSigAlgs());
tinfo_.sslNextProtocol = std::make_shared<std::string>();
tinfo_.sslNextProtocol->assign(reinterpret_cast<const char*>(nextProto),
nextProtoLength);
acceptor_->updateSSLStats(
sock,
tinfo_.sslSetupTime,
SSLErrorEnum::NO_ERROR
);
auto nextProtocol = nextProto ?
std::string((const char*)nextProto, nextProtoLength) : empty_string;
// The callback will delete this.
callback_->connectionReady(
std::move(socket_),
std::move(nextProtocol),
SecureTransportType::TLS);
}
void SSLAcceptorHandshakeHelper::handshakeErr(
AsyncSSLSocket* sock,
const AsyncSocketException& ex) noexcept {
auto elapsedTime =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - acceptTime_);
VLOG(3) << "SSL handshake error after " << elapsedTime.count() <<
" ms; " << sock->getRawBytesReceived() << " bytes received & " <<
sock->getRawBytesWritten() << " bytes sent: " <<
ex.what();
acceptor_->updateSSLStats(sock, elapsedTime, sslError_);
auto sslEx = folly::make_exception_wrapper<SSLException>(
sslError_, elapsedTime, sock->getRawBytesReceived());
// The callback will delete this.
callback_->connectionError(sslEx);
}
}
|
/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <wangle/acceptor/SSLAcceptorHandshakeHelper.h>
#include <string>
#include <wangle/acceptor/SecureTransportType.h>
namespace wangle {
static const std::string empty_string;
using namespace folly;
void SSLAcceptorHandshakeHelper::start(
folly::AsyncSSLSocket::UniquePtr sock,
AcceptorHandshakeHelper::Callback* callback) noexcept {
socket_ = std::move(sock);
callback_ = callback;
if (acceptor_->getParseClientHello()) {
socket_->enableClientHelloParsing();
}
socket_->forceCacheAddrOnFailure(true);
socket_->sslAccept(this);
}
void SSLAcceptorHandshakeHelper::handshakeSuc(AsyncSSLSocket* sock) noexcept {
const unsigned char* nextProto = nullptr;
unsigned nextProtoLength = 0;
sock->getSelectedNextProtocol(&nextProto, &nextProtoLength);
if (VLOG_IS_ON(3)) {
if (nextProto) {
VLOG(3) << "Client selected next protocol " <<
std::string((const char*)nextProto, nextProtoLength);
} else {
VLOG(3) << "Client did not select a next protocol";
}
}
// fill in SSL-related fields from TransportInfo
// the other fields like RTT are filled in the Acceptor
tinfo_.ssl = true;
tinfo_.acceptTime = acceptTime_;
tinfo_.sslSetupTime = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - acceptTime_
);
tinfo_.sslSetupBytesRead = sock->getRawBytesReceived();
tinfo_.sslSetupBytesWritten = sock->getRawBytesWritten();
tinfo_.sslServerName = sock->getSSLServerName() ?
std::make_shared<std::string>(sock->getSSLServerName()) : nullptr;
tinfo_.sslCipher = sock->getNegotiatedCipherName() ?
std::make_shared<std::string>(sock->getNegotiatedCipherName()) : nullptr;
tinfo_.sslVersion = sock->getSSLVersion();
const char* sigAlgName = sock->getSSLCertSigAlgName();
tinfo_.sslCertSigAlgName =
std::make_shared<std::string>(sigAlgName ? sigAlgName : "");
tinfo_.sslCertSize = sock->getSSLCertSize();
tinfo_.sslResume = SSLUtil::getResumeState(sock);
tinfo_.sslClientCiphers = std::make_shared<std::string>();
sock->getSSLClientCiphers(*tinfo_.sslClientCiphers);
tinfo_.sslServerCiphers = std::make_shared<std::string>();
sock->getSSLServerCiphers(*tinfo_.sslServerCiphers);
tinfo_.sslClientComprMethods =
std::make_shared<std::string>(sock->getSSLClientComprMethods());
tinfo_.sslClientExts =
std::make_shared<std::string>(sock->getSSLClientExts());
tinfo_.sslClientSigAlgs =
std::make_shared<std::string>(sock->getSSLClientSigAlgs());
tinfo_.sslNextProtocol = std::make_shared<std::string>();
tinfo_.sslNextProtocol->assign(reinterpret_cast<const char*>(nextProto),
nextProtoLength);
acceptor_->updateSSLStats(
sock,
tinfo_.sslSetupTime,
SSLErrorEnum::NO_ERROR
);
auto nextProtocol = nextProto ?
std::string((const char*)nextProto, nextProtoLength) : empty_string;
// The callback will delete this.
callback_->connectionReady(
std::move(socket_),
std::move(nextProtocol),
SecureTransportType::TLS);
}
void SSLAcceptorHandshakeHelper::handshakeErr(
AsyncSSLSocket* sock,
const AsyncSocketException& ex) noexcept {
auto elapsedTime =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - acceptTime_);
VLOG(3) << "SSL handshake error after " << elapsedTime.count() <<
" ms; " << sock->getRawBytesReceived() << " bytes received & " <<
sock->getRawBytesWritten() << " bytes sent: " <<
ex.what();
acceptor_->updateSSLStats(sock, elapsedTime, sslError_);
auto sslEx = folly::make_exception_wrapper<SSLException>(
sslError_, elapsedTime, sock->getRawBytesReceived());
// The callback will delete this.
callback_->connectionError(sslEx);
}
}
|
Change SSLAcceptorHandshakeHelper.cpp to force IP address caching.
|
Change SSLAcceptorHandshakeHelper.cpp to force IP address caching.
Summary: Change SSLAcceptorHandshakeHelper.cpp to force IP address caching. Cached local and peer IP addresses improve SSL handshake failure diagnostics.
Reviewed By: afrind
Differential Revision: D2864220
fb-gh-sync-id: caf596b55c4cd4d21251b2edfa7864ee46060c6e
|
C++
|
apache-2.0
|
facebook/wangle,facebook/wangle,Dalzhim/wangle,Dalzhim/wangle,facebook/wangle
|
57ed22dfdf942fcdbcc7ff33381c26457cb988c4
|
nsjail.cc
|
nsjail.cc
|
/*
nsjail
-----------------------------------------
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "nsjail.h"
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <memory>
#include <vector>
#include "cmdline.h"
#include "logs.h"
#include "macros.h"
#include "net.h"
#include "sandbox.h"
#include "subproc.h"
#include "util.h"
namespace nsjail {
static __thread int sigFatal = 0;
static __thread bool showProc = false;
static void sigHandler(int sig) {
if (sig == SIGALRM || sig == SIGCHLD || sig == SIGPIPE) {
return;
}
if (sig == SIGUSR1 || sig == SIGQUIT) {
showProc = true;
return;
}
sigFatal = sig;
}
static bool setSigHandler(int sig) {
LOG_D("Setting sighandler for signal %s (%d)", util::sigName(sig).c_str(), sig);
sigset_t smask;
sigemptyset(&smask);
struct sigaction sa;
sa.sa_handler = sigHandler;
sa.sa_mask = smask;
sa.sa_flags = 0;
sa.sa_restorer = NULL;
if (sig == SIGTTIN || sig == SIGTTOU) {
sa.sa_handler = SIG_IGN;
}
if (sigaction(sig, &sa, NULL) == -1) {
PLOG_E("sigaction(%d)", sig);
return false;
}
return true;
}
static bool setSigHandlers(void) {
for (const auto& i : nssigs) {
if (!setSigHandler(i)) {
return false;
}
}
return true;
}
static bool setTimer(nsjconf_t* nsjconf) {
if (nsjconf->mode == MODE_STANDALONE_EXECVE) {
return true;
}
struct itimerval it = {
.it_interval =
{
.tv_sec = 1,
.tv_usec = 0,
},
.it_value =
{
.tv_sec = 1,
.tv_usec = 0,
},
};
if (setitimer(ITIMER_REAL, &it, NULL) == -1) {
PLOG_E("setitimer(ITIMER_REAL)");
return false;
}
return true;
}
static bool pipeTraffic(nsjconf_t* nsjconf, int listenfd) {
std::vector<struct pollfd> fds;
fds.reserve(nsjconf->pipes.size() * 3 + 1);
for (const auto& p : nsjconf->pipes) {
fds.push_back({
.fd = p.sock_fd,
.events = POLLIN | POLLOUT,
.revents = 0,
});
fds.push_back({
.fd = p.pipe_in,
.events = POLLOUT,
.revents = 0,
});
fds.push_back({
.fd = p.pipe_out,
.events = POLLIN,
.revents = 0,
});
}
fds.push_back({
.fd = listenfd,
.events = POLLIN,
.revents = 0,
});
LOG_D("Waiting for fd activity");
while (poll(fds.data(), fds.size(), -1) > 0) {
if (sigFatal > 0 || showProc) {
return false;
}
if (fds.back().revents != 0) {
LOG_D("New connection ready");
return true;
}
bool cleanup = false;
for (size_t i = 0; i < fds.size() - 1; ++i) {
if (fds[i].revents & POLLIN) {
fds[i].events &= ~POLLIN;
}
if (fds[i].revents & POLLOUT) {
fds[i].events &= ~POLLOUT;
}
}
for (size_t i = 0; i < fds.size() - 3; i += 3) {
const size_t pipe_no = i / 3;
int in, out;
const char* direction;
bool closed = false;
std::tuple<int, int, const char*> direction_map[] = {
std::make_tuple(i, i + 1, "in"),
std::make_tuple(i + 2, i, "out"),
};
for (const auto& entry : direction_map) {
std::tie(in, out, direction) = entry;
bool in_ready = (fds[in].events & POLLIN) == 0 ||
(fds[in].revents & POLLIN) == POLLIN;
bool out_ready = (fds[out].events & POLLOUT) == 0 ||
(fds[out].revents & POLLOUT) == POLLOUT;
if (in_ready && out_ready) {
LOG_D("#%zu piping data %s", pipe_no, direction);
ssize_t rv = splice(fds[in].fd, nullptr, fds[out].fd,
nullptr, 4096, SPLICE_F_NONBLOCK);
if (rv == -1 && errno != EAGAIN) {
PLOG_E("splice fd pair #%zu {%d, %d}\n", pipe_no,
fds[in].fd, fds[out].fd);
}
if (rv == 0) {
closed = true;
}
fds[in].events |= POLLIN;
fds[out].events |= POLLOUT;
}
if ((fds[in].revents & (POLLERR | POLLHUP)) != 0 ||
(fds[out].revents & (POLLERR | POLLHUP)) != 0) {
closed = true;
}
}
if (closed) {
LOG_D("#%zu connection closed", pipe_no);
cleanup = true;
close(nsjconf->pipes[pipe_no].sock_fd);
close(nsjconf->pipes[pipe_no].pipe_in);
close(nsjconf->pipes[pipe_no].pipe_out);
if (nsjconf->pipes[pipe_no].pid > 0) {
kill(nsjconf->pipes[pipe_no].pid, SIGKILL);
}
nsjconf->pipes[pipe_no] = {};
}
}
if (cleanup) {
break;
}
}
nsjconf->pipes.erase(std::remove(nsjconf->pipes.begin(), nsjconf->pipes.end(), pipemap_t{}),
nsjconf->pipes.end());
return false;
}
static int listenMode(nsjconf_t* nsjconf) {
int listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port);
if (listenfd == -1) {
return EXIT_FAILURE;
}
for (;;) {
if (sigFatal > 0) {
subproc::killAndReapAll(nsjconf, nsjconf->forward_signals ? sigFatal : SIGKILL);
logs::logStop(sigFatal);
close(listenfd);
return EXIT_SUCCESS;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
if (pipeTraffic(nsjconf, listenfd)) {
int connfd = net::acceptConn(listenfd);
if (connfd >= 0) {
int in[2];
int out[2];
if (pipe(in) != 0 || pipe(out) != 0) {
PLOG_E("pipe");
continue;
}
pid_t pid =
subproc::runChild(nsjconf, connfd, in[0], out[1], out[1]);
close(in[0]);
close(out[1]);
if (pid <= 0) {
close(in[1]);
close(out[0]);
close(connfd);
} else {
nsjconf->pipes.push_back({
.sock_fd = connfd,
.pipe_in = in[1],
.pipe_out = out[0],
.pid = pid,
});
}
}
}
subproc::reapProc(nsjconf);
}
}
static int standaloneMode(nsjconf_t* nsjconf) {
for (;;) {
if (subproc::runChild(nsjconf, /* netfd= */ -1, STDIN_FILENO, STDOUT_FILENO,
STDERR_FILENO) == -1) {
LOG_E("Couldn't launch the child process");
return 0xff;
}
for (;;) {
int child_status = subproc::reapProc(nsjconf);
if (subproc::countProc(nsjconf) == 0) {
if (nsjconf->mode == MODE_STANDALONE_ONCE) {
return child_status;
}
break;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
if (sigFatal > 0) {
subproc::killAndReapAll(nsjconf, nsjconf->forward_signals ? sigFatal : SIGKILL);
logs::logStop(sigFatal);
return (128 + sigFatal);
}
pause();
}
}
// not reached
}
std::unique_ptr<struct termios> getTC(int fd) {
std::unique_ptr<struct termios> trm(new struct termios);
if (ioctl(fd, TCGETS, trm.get()) == -1) {
PLOG_D("ioctl(fd=%d, TCGETS) failed", fd);
return nullptr;
}
LOG_D("Saved the current state of the TTY");
return trm;
}
void setTC(int fd, const struct termios* trm) {
if (!trm) {
return;
}
if (ioctl(fd, TCSETS, trm) == -1) {
PLOG_W("ioctl(fd=%d, TCSETS) failed", fd);
return;
}
if (tcflush(fd, TCIFLUSH) == -1) {
PLOG_W("tcflush(fd=%d, TCIFLUSH) failed", fd);
return;
}
}
} // namespace nsjail
int main(int argc, char* argv[]) {
std::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv);
std::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO);
if (!nsjconf) {
LOG_F("Couldn't parse cmdline options");
}
if (nsjconf->daemonize && (daemon(/* nochdir= */ 1, /* noclose= */ 0) == -1)) {
PLOG_F("daemon");
}
cmdline::logParams(nsjconf.get());
if (!nsjail::setSigHandlers()) {
LOG_F("nsjail::setSigHandlers() failed");
}
if (!nsjail::setTimer(nsjconf.get())) {
LOG_F("nsjail::setTimer() failed");
}
if (!sandbox::preparePolicy(nsjconf.get())) {
LOG_F("Couldn't prepare sandboxing policy");
}
int ret = 0;
if (nsjconf->mode == MODE_LISTEN_TCP) {
ret = nsjail::listenMode(nsjconf.get());
} else {
ret = nsjail::standaloneMode(nsjconf.get());
}
sandbox::closePolicy(nsjconf.get());
/* Try to restore the underlying console's params in case some program has changed it */
if (!nsjconf->daemonize) {
nsjail::setTC(STDIN_FILENO, trm.get());
}
LOG_D("Returning with %d", ret);
return ret;
}
|
/*
nsjail
-----------------------------------------
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "nsjail.h"
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <memory>
#include <vector>
#include "cmdline.h"
#include "logs.h"
#include "macros.h"
#include "net.h"
#include "sandbox.h"
#include "subproc.h"
#include "util.h"
namespace nsjail {
static __thread int sigFatal = 0;
static __thread bool showProc = false;
static void sigHandler(int sig) {
if (sig == SIGALRM || sig == SIGCHLD || sig == SIGPIPE) {
return;
}
if (sig == SIGUSR1 || sig == SIGQUIT) {
showProc = true;
return;
}
sigFatal = sig;
}
static bool setSigHandler(int sig) {
LOG_D("Setting sighandler for signal %s (%d)", util::sigName(sig).c_str(), sig);
sigset_t smask;
sigemptyset(&smask);
struct sigaction sa;
sa.sa_handler = sigHandler;
sa.sa_mask = smask;
sa.sa_flags = 0;
sa.sa_restorer = NULL;
if (sig == SIGTTIN || sig == SIGTTOU) {
sa.sa_handler = SIG_IGN;
}
if (sigaction(sig, &sa, NULL) == -1) {
PLOG_E("sigaction(%d)", sig);
return false;
}
return true;
}
static bool setSigHandlers(void) {
for (const auto& i : nssigs) {
if (!setSigHandler(i)) {
return false;
}
}
return true;
}
static bool setTimer(nsjconf_t* nsjconf) {
if (nsjconf->mode == MODE_STANDALONE_EXECVE) {
return true;
}
struct itimerval it = {
.it_interval =
{
.tv_sec = 1,
.tv_usec = 0,
},
.it_value =
{
.tv_sec = 1,
.tv_usec = 0,
},
};
if (setitimer(ITIMER_REAL, &it, NULL) == -1) {
PLOG_E("setitimer(ITIMER_REAL)");
return false;
}
return true;
}
static bool pipeTraffic(nsjconf_t* nsjconf, int listenfd) {
std::vector<struct pollfd> fds;
fds.reserve(nsjconf->pipes.size() * 3 + 1);
for (const auto& p : nsjconf->pipes) {
fds.push_back({
.fd = p.sock_fd,
.events = POLLIN | POLLOUT,
.revents = 0,
});
fds.push_back({
.fd = p.pipe_in,
.events = POLLOUT,
.revents = 0,
});
fds.push_back({
.fd = p.pipe_out,
.events = POLLIN,
.revents = 0,
});
}
fds.push_back({
.fd = listenfd,
.events = POLLIN,
.revents = 0,
});
LOG_D("Waiting for fd activity");
while (poll(fds.data(), fds.size(), -1) > 0) {
if (sigFatal > 0 || showProc) {
return false;
}
if (fds.back().revents != 0) {
LOG_D("New connection ready");
return true;
}
bool cleanup = false;
for (size_t i = 0; i < fds.size() - 1; ++i) {
if (fds[i].revents & POLLIN) {
fds[i].events &= ~POLLIN;
}
if (fds[i].revents & POLLOUT) {
fds[i].events &= ~POLLOUT;
}
}
for (size_t i = 0; i < fds.size() - 3; i += 3) {
const size_t pipe_no = i / 3;
int in, out;
const char* direction;
bool closed = false;
std::tuple<int, int, const char*> direction_map[] = {
std::make_tuple(i, i + 1, "in"),
std::make_tuple(i + 2, i, "out"),
};
for (const auto& entry : direction_map) {
std::tie(in, out, direction) = entry;
bool in_ready = (fds[in].events & POLLIN) == 0 ||
(fds[in].revents & POLLIN) == POLLIN;
bool out_ready = (fds[out].events & POLLOUT) == 0 ||
(fds[out].revents & POLLOUT) == POLLOUT;
if (in_ready && out_ready) {
LOG_D("#%zu piping data %s", pipe_no, direction);
ssize_t rv = splice(fds[in].fd, nullptr, fds[out].fd,
nullptr, 4096, SPLICE_F_NONBLOCK);
if (rv == -1 && errno != EAGAIN) {
PLOG_E("splice fd pair #%zu {%d, %d}\n", pipe_no,
fds[in].fd, fds[out].fd);
}
if (rv == 0) {
closed = true;
}
fds[in].events |= POLLIN;
fds[out].events |= POLLOUT;
}
if ((fds[in].revents & (POLLERR | POLLHUP)) != 0 ||
(fds[out].revents & (POLLERR | POLLHUP)) != 0) {
closed = true;
}
}
if (closed) {
LOG_D("#%zu connection closed", pipe_no);
cleanup = true;
close(nsjconf->pipes[pipe_no].sock_fd);
close(nsjconf->pipes[pipe_no].pipe_in);
close(nsjconf->pipes[pipe_no].pipe_out);
if (nsjconf->pipes[pipe_no].pid > 0) {
kill(nsjconf->pipes[pipe_no].pid, SIGKILL);
}
nsjconf->pipes[pipe_no] = {};
}
}
if (cleanup) {
break;
}
}
nsjconf->pipes.erase(std::remove(nsjconf->pipes.begin(), nsjconf->pipes.end(), pipemap_t{}),
nsjconf->pipes.end());
return false;
}
static int listenMode(nsjconf_t* nsjconf) {
int listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port);
if (listenfd == -1) {
return EXIT_FAILURE;
}
for (;;) {
if (sigFatal > 0) {
subproc::killAndReapAll(
nsjconf, nsjconf->forward_signals ? sigFatal : SIGKILL);
logs::logStop(sigFatal);
close(listenfd);
return EXIT_SUCCESS;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
if (pipeTraffic(nsjconf, listenfd)) {
int connfd = net::acceptConn(listenfd);
if (connfd >= 0) {
int in[2];
int out[2];
if (pipe(in) != 0 || pipe(out) != 0) {
PLOG_E("pipe");
continue;
}
pid_t pid =
subproc::runChild(nsjconf, connfd, in[0], out[1], out[1]);
close(in[0]);
close(out[1]);
if (pid <= 0) {
close(in[1]);
close(out[0]);
close(connfd);
} else {
nsjconf->pipes.push_back({
.sock_fd = connfd,
.pipe_in = in[1],
.pipe_out = out[0],
.pid = pid,
});
}
}
}
subproc::reapProc(nsjconf);
}
}
static int standaloneMode(nsjconf_t* nsjconf) {
for (;;) {
if (subproc::runChild(nsjconf, /* netfd= */ -1, STDIN_FILENO, STDOUT_FILENO,
STDERR_FILENO) == -1) {
LOG_E("Couldn't launch the child process");
return 0xff;
}
for (;;) {
int child_status = subproc::reapProc(nsjconf);
if (subproc::countProc(nsjconf) == 0) {
if (nsjconf->mode == MODE_STANDALONE_ONCE) {
return child_status;
}
break;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
if (sigFatal > 0) {
subproc::killAndReapAll(
nsjconf, nsjconf->forward_signals ? sigFatal : SIGKILL);
logs::logStop(sigFatal);
return (128 + sigFatal);
}
pause();
}
}
// not reached
}
std::unique_ptr<struct termios> getTC(int fd) {
std::unique_ptr<struct termios> trm(new struct termios);
if (ioctl(fd, TCGETS, trm.get()) == -1) {
PLOG_D("ioctl(fd=%d, TCGETS) failed", fd);
return nullptr;
}
LOG_D("Saved the current state of the TTY");
return trm;
}
void setTC(int fd, const struct termios* trm) {
if (!trm) {
return;
}
if (ioctl(fd, TCSETS, trm) == -1) {
PLOG_W("ioctl(fd=%d, TCSETS) failed", fd);
return;
}
if (tcflush(fd, TCIFLUSH) == -1) {
PLOG_W("tcflush(fd=%d, TCIFLUSH) failed", fd);
return;
}
}
} // namespace nsjail
int main(int argc, char* argv[]) {
std::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv);
std::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO);
if (!nsjconf) {
LOG_F("Couldn't parse cmdline options");
}
if (nsjconf->daemonize && (daemon(/* nochdir= */ 1, /* noclose= */ 0) == -1)) {
PLOG_F("daemon");
}
cmdline::logParams(nsjconf.get());
if (!nsjail::setSigHandlers()) {
LOG_F("nsjail::setSigHandlers() failed");
}
if (!nsjail::setTimer(nsjconf.get())) {
LOG_F("nsjail::setTimer() failed");
}
if (!sandbox::preparePolicy(nsjconf.get())) {
LOG_F("Couldn't prepare sandboxing policy");
}
int ret = 0;
if (nsjconf->mode == MODE_LISTEN_TCP) {
ret = nsjail::listenMode(nsjconf.get());
} else {
ret = nsjail::standaloneMode(nsjconf.get());
}
sandbox::closePolicy(nsjconf.get());
/* Try to restore the underlying console's params in case some program has changed it */
if (!nsjconf->daemonize) {
nsjail::setTC(STDIN_FILENO, trm.get());
}
LOG_D("Returning with %d", ret);
return ret;
}
|
make indent
|
make indent
|
C++
|
apache-2.0
|
google/nsjail,google/nsjail
|
097c7288724f35d5374e067d8781e04353dd5652
|
src/implicit_writer/main.cc
|
src/implicit_writer/main.cc
|
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "bootstrap.h"
#include "config.h"
#include "logger.h"
#include "utils.h"
namespace bpo = boost::program_options;
void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr_implicit_writer version is: " << AKTUALIZR_VERSION << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
bpo::options_description description("aktualizr_implicit_writer command line options");
// clang-format off
description.add_options()
("help,h", "help screen")
("version,v", "Current aktualizr_implicit_writer version")
("credentials,c", bpo::value<std::string>()->required(), "zipped credentials file")
("config-input,i", bpo::value<std::string>()->required(), "input sota.toml configuration file")
("config-output,o", bpo::value<std::string>()->required(), "output sota.toml configuration file")
("prefix,p", bpo::value<std::string>(), "prefix for root CA output path");
// clang-format on
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_info_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_SUCCESS);
} catch (const bpo::error &ex) {
check_info_options(description, vm);
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
int main(int argc, char *argv[]) {
loggerInit();
loggerSetSeverity(static_cast<LoggerLevels>(2));
bpo::variables_map commandline_map = parse_options(argc, argv);
std::string credentials_path = commandline_map["credentials"].as<std::string>();
std::string config_in_path = commandline_map["config-input"].as<std::string>();
std::string config_out_path = commandline_map["config-output"].as<std::string>();
std::string prefix = "";
if (commandline_map.count("prefix") != 0) {
prefix = commandline_map["prefix"].as<std::string>();
}
std::cout << "Reading config file: " << config_in_path << "\n";
Config config(config_in_path);
Bootstrap boot(credentials_path, "");
boost::filesystem::path ca_path(prefix);
ca_path /= config.tls.ca_file();
std::cout << "Writing root CA: " << ca_path << "\n";
boost::filesystem::create_directories(ca_path.parent_path());
Utils::writeFile(ca_path.string(), boot.getCa());
config.tls.server = Bootstrap::readServerUrl(credentials_path);
config.provision.server = config.tls.server;
config.uptane.repo_server = config.tls.server + "/repo";
config.uptane.director_server = config.tls.server + "/director";
config.uptane.ostree_server = config.tls.server + "/treehub";
std::cout << "Writing config file: " << config_out_path << "\n";
boost::filesystem::create_directories(boost::filesystem::path(config_out_path).parent_path());
config.writeToFile(config_out_path);
return 0;
}
|
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "bootstrap.h"
#include "config.h"
#include "logger.h"
#include "utils.h"
namespace bpo = boost::program_options;
void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr_implicit_writer version is: " << AKTUALIZR_VERSION << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
bpo::options_description description("aktualizr_implicit_writer command line options");
// clang-format off
description.add_options()
("help,h", "help screen")
("version,v", "Current aktualizr_implicit_writer version")
("credentials,c", bpo::value<std::string>()->required(), "zipped credentials file")
("config-input,i", bpo::value<std::string>()->required(), "input sota.toml configuration file")
("config-output,o", bpo::value<std::string>()->required(), "output sota.toml configuration file")
("prefix,p", bpo::value<std::string>(), "prefix for root CA output path")
("no-root-ca", "don't overwrite root CA path");
// clang-format on
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_info_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_SUCCESS);
} catch (const bpo::error &ex) {
check_info_options(description, vm);
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
int main(int argc, char *argv[]) {
loggerInit();
loggerSetSeverity(static_cast<LoggerLevels>(2));
bpo::variables_map commandline_map = parse_options(argc, argv);
std::string credentials_path = commandline_map["credentials"].as<std::string>();
std::string config_in_path = commandline_map["config-input"].as<std::string>();
std::string config_out_path = commandline_map["config-output"].as<std::string>();
bool no_root = (commandline_map.count("no-root-ca") != 0);
std::string prefix = "";
if (commandline_map.count("prefix") != 0) {
prefix = commandline_map["prefix"].as<std::string>();
}
std::cout << "Reading config file: " << config_in_path << "\n";
Config config(config_in_path);
Bootstrap boot(credentials_path, "");
boost::filesystem::path ca_path(prefix);
ca_path /= config.tls.ca_file();
if (!no_root) {
std::cout << "Writing root CA: " << ca_path << "\n";
boost::filesystem::create_directories(ca_path.parent_path());
Utils::writeFile(ca_path.string(), boot.getCa());
}
config.tls.server = Bootstrap::readServerUrl(credentials_path);
config.provision.server = config.tls.server;
config.uptane.repo_server = config.tls.server + "/repo";
config.uptane.director_server = config.tls.server + "/director";
config.uptane.ostree_server = config.tls.server + "/treehub";
std::cout << "Writing config file: " << config_out_path << "\n";
boost::filesystem::create_directories(boost::filesystem::path(config_out_path).parent_path());
config.writeToFile(config_out_path);
return 0;
}
|
Add option for implicit-writer to skip writing root certificate
|
Add option for implicit-writer to skip writing root certificate
|
C++
|
mpl-2.0
|
advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr
|
9c273307d8ba93da561faf3f9be71d0e0f291825
|
modules/jsonrpc/jsonrpc.cpp
|
modules/jsonrpc/jsonrpc.cpp
|
/*************************************************************************/
/* jsonrpc.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "jsonrpc.h"
#include "core/io/json.h"
JSONRPC::JSONRPC() {
}
JSONRPC::~JSONRPC() {
}
void JSONRPC::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_scope", "scope", "target"), &JSONRPC::set_scope);
ClassDB::bind_method(D_METHOD("process_action", "action", "recurse"), &JSONRPC::process_action, DEFVAL(false));
ClassDB::bind_method(D_METHOD("process_string", "action"), &JSONRPC::process_string);
ClassDB::bind_method(D_METHOD("make_request", "method", "params", "id"), &JSONRPC::make_request);
ClassDB::bind_method(D_METHOD("make_response", "result", "id"), &JSONRPC::make_response);
ClassDB::bind_method(D_METHOD("make_notification", "method", "params"), &JSONRPC::make_notification);
ClassDB::bind_method(D_METHOD("make_response_error", "code", "message", "id"), &JSONRPC::make_response_error, DEFVAL(Variant()));
BIND_ENUM_CONSTANT(PARSE_ERROR);
BIND_ENUM_CONSTANT(INVALID_REQUEST);
BIND_ENUM_CONSTANT(METHOD_NOT_FOUND);
BIND_ENUM_CONSTANT(INVALID_PARAMS);
BIND_ENUM_CONSTANT(INTERNAL_ERROR);
}
Dictionary JSONRPC::make_response_error(int p_code, const String &p_message, const Variant &p_id) const {
Dictionary dict;
dict["jsonrpc"] = "2.0";
Dictionary err;
err["code"] = p_code;
err["message"] = p_message;
dict["error"] = err;
dict["id"] = p_id;
return dict;
}
Dictionary JSONRPC::make_response(const Variant &p_value, const Variant &p_id) {
Dictionary dict;
dict["jsonrpc"] = "2.0";
dict["id"] = p_id;
dict["result"] = p_value;
return dict;
}
Dictionary JSONRPC::make_notification(const String &p_method, const Variant &p_params) {
Dictionary dict;
dict["jsonrpc"] = "2.0";
dict["method"] = p_method;
dict["params"] = p_params;
return dict;
}
Dictionary JSONRPC::make_request(const String &p_method, const Variant &p_params, const Variant &p_id) {
Dictionary dict;
dict["jsonrpc"] = "2.0";
dict["method"] = p_method;
dict["params"] = p_params;
dict["id"] = p_id;
return dict;
}
Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elements) {
Variant ret;
if (p_action.get_type() == Variant::DICTIONARY) {
Dictionary dict = p_action;
String method = dict.get("method", "");
Array args;
if (dict.has("params")) {
Variant params = dict.get("params", Variant());
if (params.get_type() == Variant::ARRAY) {
args = params;
} else {
args.push_back(params);
}
}
Object *object = this;
if (method_scopes.has(method.get_base_dir())) {
object = method_scopes[method.get_base_dir()];
method = method.get_file();
}
Variant id;
if (dict.has("id")) {
id = dict["id"];
}
if (object == nullptr || !object->has_method(method)) {
ret = make_response_error(JSONRPC::METHOD_NOT_FOUND, "Method not found: " + method, id);
} else {
Variant call_ret = object->callv(method, args);
if (id.get_type() != Variant::NIL) {
ret = make_response(call_ret, id);
}
}
} else if (p_action.get_type() == Variant::ARRAY && p_process_arr_elements) {
Array arr = p_action;
int size = arr.size();
if (size) {
Array arr_ret;
for (int i = 0; i < size; i++) {
const Variant &var = arr.get(i);
arr_ret.push_back(process_action(var));
}
ret = arr_ret;
} else {
ret = make_response_error(JSONRPC::INVALID_REQUEST, "Invalid Request");
}
} else {
ret = make_response_error(JSONRPC::INVALID_REQUEST, "Invalid Request");
}
return ret;
}
String JSONRPC::process_string(const String &p_input) {
if (p_input.empty()) {
return String();
}
Variant ret;
Variant input;
String err_message;
int err_line;
if (OK != JSON::parse(p_input, input, err_message, err_line)) {
ret = make_response_error(JSONRPC::PARSE_ERROR, "Parse error");
} else {
ret = process_action(input, true);
}
if (ret.get_type() == Variant::NIL) {
return "";
}
return JSON::print(ret);
}
void JSONRPC::set_scope(const String &p_scope, Object *p_obj) {
method_scopes[p_scope] = p_obj;
}
|
/*************************************************************************/
/* jsonrpc.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "jsonrpc.h"
#include "core/io/json.h"
JSONRPC::JSONRPC() {
}
JSONRPC::~JSONRPC() {
}
void JSONRPC::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_scope", "scope", "target"), &JSONRPC::set_scope);
ClassDB::bind_method(D_METHOD("process_action", "action", "recurse"), &JSONRPC::process_action, DEFVAL(false));
ClassDB::bind_method(D_METHOD("process_string", "action"), &JSONRPC::process_string);
ClassDB::bind_method(D_METHOD("make_request", "method", "params", "id"), &JSONRPC::make_request);
ClassDB::bind_method(D_METHOD("make_response", "result", "id"), &JSONRPC::make_response);
ClassDB::bind_method(D_METHOD("make_notification", "method", "params"), &JSONRPC::make_notification);
ClassDB::bind_method(D_METHOD("make_response_error", "code", "message", "id"), &JSONRPC::make_response_error, DEFVAL(Variant()));
BIND_ENUM_CONSTANT(PARSE_ERROR);
BIND_ENUM_CONSTANT(INVALID_REQUEST);
BIND_ENUM_CONSTANT(METHOD_NOT_FOUND);
BIND_ENUM_CONSTANT(INVALID_PARAMS);
BIND_ENUM_CONSTANT(INTERNAL_ERROR);
}
Dictionary JSONRPC::make_response_error(int p_code, const String &p_message, const Variant &p_id) const {
Dictionary dict;
dict["jsonrpc"] = "2.0";
Dictionary err;
err["code"] = p_code;
err["message"] = p_message;
dict["error"] = err;
dict["id"] = p_id;
return dict;
}
Dictionary JSONRPC::make_response(const Variant &p_value, const Variant &p_id) {
Dictionary dict;
dict["jsonrpc"] = "2.0";
dict["id"] = p_id;
dict["result"] = p_value;
return dict;
}
Dictionary JSONRPC::make_notification(const String &p_method, const Variant &p_params) {
Dictionary dict;
dict["jsonrpc"] = "2.0";
dict["method"] = p_method;
dict["params"] = p_params;
return dict;
}
Dictionary JSONRPC::make_request(const String &p_method, const Variant &p_params, const Variant &p_id) {
Dictionary dict;
dict["jsonrpc"] = "2.0";
dict["method"] = p_method;
dict["params"] = p_params;
dict["id"] = p_id;
return dict;
}
Variant JSONRPC::process_action(const Variant &p_action, bool p_process_arr_elements) {
Variant ret;
if (p_action.get_type() == Variant::DICTIONARY) {
Dictionary dict = p_action;
String method = dict.get("method", "");
if (method.begins_with("$/")) {
return ret;
}
Array args;
if (dict.has("params")) {
Variant params = dict.get("params", Variant());
if (params.get_type() == Variant::ARRAY) {
args = params;
} else {
args.push_back(params);
}
}
Object *object = this;
if (method_scopes.has(method.get_base_dir())) {
object = method_scopes[method.get_base_dir()];
method = method.get_file();
}
Variant id;
if (dict.has("id")) {
id = dict["id"];
}
if (object == nullptr || !object->has_method(method)) {
ret = make_response_error(JSONRPC::METHOD_NOT_FOUND, "Method not found: " + method, id);
} else {
Variant call_ret = object->callv(method, args);
if (id.get_type() != Variant::NIL) {
ret = make_response(call_ret, id);
}
}
} else if (p_action.get_type() == Variant::ARRAY && p_process_arr_elements) {
Array arr = p_action;
int size = arr.size();
if (size) {
Array arr_ret;
for (int i = 0; i < size; i++) {
const Variant &var = arr.get(i);
arr_ret.push_back(process_action(var));
}
ret = arr_ret;
} else {
ret = make_response_error(JSONRPC::INVALID_REQUEST, "Invalid Request");
}
} else {
ret = make_response_error(JSONRPC::INVALID_REQUEST, "Invalid Request");
}
return ret;
}
String JSONRPC::process_string(const String &p_input) {
if (p_input.empty()) {
return String();
}
Variant ret;
Variant input;
String err_message;
int err_line;
if (OK != JSON::parse(p_input, input, err_message, err_line)) {
ret = make_response_error(JSONRPC::PARSE_ERROR, "Parse error");
} else {
ret = process_action(input, true);
}
if (ret.get_type() == Variant::NIL) {
return "";
}
return JSON::print(ret);
}
void JSONRPC::set_scope(const String &p_scope, Object *p_obj) {
method_scopes[p_scope] = p_obj;
}
|
Make LSP ignore $/ messages
|
Make LSP ignore $/ messages
Fixes #38814
|
C++
|
mit
|
firefly2442/godot,ZuBsPaCe/godot,Faless/godot,DmitriySalnikov/godot,MarianoGnu/godot,DmitriySalnikov/godot,honix/godot,Zylann/godot,Zylann/godot,ZuBsPaCe/godot,sanikoyes/godot,josempans/godot,guilhermefelipecgs/godot,sanikoyes/godot,MarianoGnu/godot,firefly2442/godot,honix/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,Shockblast/godot,ZuBsPaCe/godot,Faless/godot,godotengine/godot,Faless/godot,Valentactive/godot,Shockblast/godot,josempans/godot,ZuBsPaCe/godot,vnen/godot,Zylann/godot,guilhermefelipecgs/godot,Zylann/godot,josempans/godot,sanikoyes/godot,godotengine/godot,Shockblast/godot,pkowal1982/godot,BastiaanOlij/godot,vnen/godot,Valentactive/godot,MarianoGnu/godot,pkowal1982/godot,pkowal1982/godot,BastiaanOlij/godot,pkowal1982/godot,vkbsb/godot,vkbsb/godot,vkbsb/godot,MarianoGnu/godot,BastiaanOlij/godot,firefly2442/godot,vnen/godot,Valentactive/godot,BastiaanOlij/godot,BastiaanOlij/godot,godotengine/godot,vnen/godot,guilhermefelipecgs/godot,honix/godot,sanikoyes/godot,vkbsb/godot,pkowal1982/godot,vkbsb/godot,akien-mga/godot,MarianoGnu/godot,Faless/godot,sanikoyes/godot,firefly2442/godot,guilhermefelipecgs/godot,akien-mga/godot,pkowal1982/godot,akien-mga/godot,Shockblast/godot,sanikoyes/godot,akien-mga/godot,josempans/godot,josempans/godot,MarianoGnu/godot,akien-mga/godot,sanikoyes/godot,Zylann/godot,DmitriySalnikov/godot,josempans/godot,vkbsb/godot,godotengine/godot,DmitriySalnikov/godot,josempans/godot,Faless/godot,Zylann/godot,guilhermefelipecgs/godot,vnen/godot,pkowal1982/godot,Valentactive/godot,ZuBsPaCe/godot,vkbsb/godot,vkbsb/godot,Shockblast/godot,firefly2442/godot,Shockblast/godot,guilhermefelipecgs/godot,MarianoGnu/godot,vnen/godot,Valentactive/godot,Shockblast/godot,honix/godot,firefly2442/godot,godotengine/godot,godotengine/godot,vnen/godot,DmitriySalnikov/godot,BastiaanOlij/godot,firefly2442/godot,sanikoyes/godot,ZuBsPaCe/godot,honix/godot,josempans/godot,DmitriySalnikov/godot,Valentactive/godot,guilhermefelipecgs/godot,BastiaanOlij/godot,ZuBsPaCe/godot,Faless/godot,Faless/godot,MarianoGnu/godot,Zylann/godot,firefly2442/godot,honix/godot,godotengine/godot,akien-mga/godot,godotengine/godot,BastiaanOlij/godot,akien-mga/godot,Valentactive/godot,akien-mga/godot,pkowal1982/godot,Valentactive/godot,DmitriySalnikov/godot,vnen/godot,Faless/godot,Shockblast/godot,Zylann/godot
|
cad16201f83a1a91b29781cff26e9e09158cae0e
|
extensions/openpower-pels/data_interface.cpp
|
extensions/openpower-pels/data_interface.cpp
|
/**
* Copyright © 2019 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "data_interface.hpp"
#include "util.hpp"
#include <fmt/format.h>
#include <fstream>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/State/Boot/Progress/server.hpp>
namespace openpower
{
namespace pels
{
namespace service_name
{
constexpr auto objectMapper = "xyz.openbmc_project.ObjectMapper";
constexpr auto vpdManager = "com.ibm.VPD.Manager";
constexpr auto ledGroupManager = "xyz.openbmc_project.LED.GroupManager";
} // namespace service_name
namespace object_path
{
constexpr auto objectMapper = "/xyz/openbmc_project/object_mapper";
constexpr auto systemInv = "/xyz/openbmc_project/inventory/system";
constexpr auto chassisInv = "/xyz/openbmc_project/inventory/system/chassis";
constexpr auto motherBoardInv =
"/xyz/openbmc_project/inventory/system/chassis/motherboard";
constexpr auto baseInv = "/xyz/openbmc_project/inventory";
constexpr auto bmcState = "/xyz/openbmc_project/state/bmc0";
constexpr auto chassisState = "/xyz/openbmc_project/state/chassis0";
constexpr auto hostState = "/xyz/openbmc_project/state/host0";
constexpr auto pldm = "/xyz/openbmc_project/pldm";
constexpr auto enableHostPELs =
"/xyz/openbmc_project/logging/send_event_logs_to_host";
constexpr auto vpdManager = "/com/ibm/VPD/Manager";
} // namespace object_path
namespace interface
{
constexpr auto dbusProperty = "org.freedesktop.DBus.Properties";
constexpr auto objectMapper = "xyz.openbmc_project.ObjectMapper";
constexpr auto invAsset = "xyz.openbmc_project.Inventory.Decorator.Asset";
constexpr auto bootProgress = "xyz.openbmc_project.State.Boot.Progress";
constexpr auto pldmRequester = "xyz.openbmc_project.PLDM.Requester";
constexpr auto enable = "xyz.openbmc_project.Object.Enable";
constexpr auto bmcState = "xyz.openbmc_project.State.BMC";
constexpr auto chassisState = "xyz.openbmc_project.State.Chassis";
constexpr auto hostState = "xyz.openbmc_project.State.Host";
constexpr auto invMotherboard =
"xyz.openbmc_project.Inventory.Item.Board.Motherboard";
constexpr auto viniRecordVPD = "com.ibm.ipzvpd.VINI";
constexpr auto locCode = "com.ibm.ipzvpd.Location";
constexpr auto compatible =
"xyz.openbmc_project.Configuration.IBMCompatibleSystem";
constexpr auto vpdManager = "com.ibm.VPD.Manager";
constexpr auto ledGroup = "xyz.openbmc_project.Led.Group";
constexpr auto operationalStatus =
"xyz.openbmc_project.State.Decorator.OperationalStatus";
} // namespace interface
using namespace sdbusplus::xyz::openbmc_project::State::Boot::server;
using sdbusplus::exception::SdBusError;
using namespace phosphor::logging;
DataInterface::DataInterface(sdbusplus::bus::bus& bus) : _bus(bus)
{
readBMCFWVersion();
readServerFWVersion();
readBMCFWVersionID();
// Watch the BootProgress property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::hostState, interface::bootProgress, "BootProgress",
*this, [this](const auto& value) {
auto status = Progress::convertProgressStagesFromString(
std::get<std::string>(value));
if ((status == Progress::ProgressStages::SystemInitComplete) ||
(status == Progress::ProgressStages::OSStart) ||
(status == Progress::ProgressStages::OSRunning))
{
setHostUp(true);
}
else
{
setHostUp(false);
}
}));
// Watch the host PEL enable property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::enableHostPELs, interface::enable, "Enabled", *this,
[this](const auto& value) {
this->_sendPELsToHost = std::get<bool>(value);
}));
// Watch the BMCState property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::bmcState, interface::bmcState, "CurrentBMCState",
*this, [this](const auto& value) {
this->_bmcState = std::get<std::string>(value);
}));
// Watch the chassis current and requested power state properties
_properties.emplace_back(std::make_unique<InterfaceWatcher<DataInterface>>(
bus, object_path::chassisState, interface::chassisState, *this,
[this](const auto& properties) {
auto state = properties.find("CurrentPowerState");
if (state != properties.end())
{
this->_chassisState = std::get<std::string>(state->second);
}
auto trans = properties.find("RequestedPowerTransition");
if (trans != properties.end())
{
this->_chassisTransition = std::get<std::string>(trans->second);
}
}));
// Watch the CurrentHostState property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::hostState, interface::hostState, "CurrentHostState",
*this, [this](const auto& value) {
this->_hostState = std::get<std::string>(value);
}));
}
DBusPropertyMap
DataInterface::getAllProperties(const std::string& service,
const std::string& objectPath,
const std::string& interface) const
{
DBusPropertyMap properties;
auto method = _bus.new_method_call(service.c_str(), objectPath.c_str(),
interface::dbusProperty, "GetAll");
method.append(interface);
auto reply = _bus.call(method);
reply.read(properties);
return properties;
}
void DataInterface::getProperty(const std::string& service,
const std::string& objectPath,
const std::string& interface,
const std::string& property,
DBusValue& value) const
{
auto method = _bus.new_method_call(service.c_str(), objectPath.c_str(),
interface::dbusProperty, "Get");
method.append(interface, property);
auto reply = _bus.call(method);
reply.read(value);
}
DBusPathList DataInterface::getPaths(const DBusInterfaceList& interfaces) const
{
auto method = _bus.new_method_call(
service_name::objectMapper, object_path::objectMapper,
interface::objectMapper, "GetSubTreePaths");
method.append(std::string{"/"}, 0, interfaces);
auto reply = _bus.call(method);
DBusPathList paths;
reply.read(paths);
return paths;
}
DBusService DataInterface::getService(const std::string& objectPath,
const std::string& interface) const
{
auto method = _bus.new_method_call(service_name::objectMapper,
object_path::objectMapper,
interface::objectMapper, "GetObject");
method.append(objectPath, std::vector<std::string>({interface}));
auto reply = _bus.call(method);
std::map<DBusService, DBusInterfaceList> response;
reply.read(response);
if (!response.empty())
{
return response.begin()->first;
}
return std::string{};
}
void DataInterface::readBMCFWVersion()
{
_bmcFWVersion =
phosphor::logging::util::getOSReleaseValue("VERSION").value_or("");
}
void DataInterface::readServerFWVersion()
{
// Not available yet
}
void DataInterface::readBMCFWVersionID()
{
_bmcFWVersionID =
phosphor::logging::util::getOSReleaseValue("VERSION_ID").value_or("");
}
std::string DataInterface::getMachineTypeModel() const
{
std::string model;
try
{
auto service = getService(object_path::systemInv, interface::invAsset);
if (!service.empty())
{
DBusValue value;
getProperty(service, object_path::systemInv, interface::invAsset,
"Model", value);
model = std::get<std::string>(value);
}
}
catch (const std::exception& e)
{
log<level::WARNING>(fmt::format("Failed reading Model property from "
"Interface: {} exception: {}",
interface::invAsset, e.what())
.c_str());
}
return model;
}
std::string DataInterface::getMachineSerialNumber() const
{
std::string sn;
try
{
auto service = getService(object_path::systemInv, interface::invAsset);
if (!service.empty())
{
DBusValue value;
getProperty(service, object_path::systemInv, interface::invAsset,
"SerialNumber", value);
sn = std::get<std::string>(value);
}
}
catch (const std::exception& e)
{
log<level::WARNING>(
fmt::format("Failed reading SerialNumber property from "
"Interface: {} exception: {}",
interface::invAsset, e.what())
.c_str());
}
return sn;
}
std::string DataInterface::getMotherboardCCIN() const
{
std::string ccin;
try
{
auto service =
getService(object_path::motherBoardInv, interface::viniRecordVPD);
if (!service.empty())
{
DBusValue value;
getProperty(service, object_path::motherBoardInv,
interface::viniRecordVPD, "CC", value);
auto cc = std::get<std::vector<uint8_t>>(value);
ccin = std::string{cc.begin(), cc.end()};
}
}
catch (const std::exception& e)
{
log<level::WARNING>(
fmt::format("Failed reading Motherboard CCIN property from "
"Interface: {} exception: {}",
interface::viniRecordVPD, e.what())
.c_str());
}
return ccin;
}
void DataInterface::getHWCalloutFields(const std::string& inventoryPath,
std::string& fruPartNumber,
std::string& ccin,
std::string& serialNumber) const
{
// For now, attempt to get all of the properties directly on the path
// passed in. In the future, may need to make use of an algorithm
// to figure out which inventory objects actually hold these
// interfaces in the case of non FRUs, or possibly another service
// will provide this info. Any missing interfaces will result
// in exceptions being thrown.
auto service = getService(inventoryPath, interface::viniRecordVPD);
auto properties =
getAllProperties(service, inventoryPath, interface::viniRecordVPD);
auto value = std::get<std::vector<uint8_t>>(properties["FN"]);
fruPartNumber = std::string{value.begin(), value.end()};
value = std::get<std::vector<uint8_t>>(properties["CC"]);
ccin = std::string{value.begin(), value.end()};
value = std::get<std::vector<uint8_t>>(properties["SN"]);
serialNumber = std::string{value.begin(), value.end()};
}
std::string
DataInterface::getLocationCode(const std::string& inventoryPath) const
{
auto service = getService(inventoryPath, interface::locCode);
DBusValue locCode;
getProperty(service, inventoryPath, interface::locCode, "LocationCode",
locCode);
return std::get<std::string>(locCode);
}
std::string
DataInterface::addLocationCodePrefix(const std::string& locationCode)
{
static const std::string locationCodePrefix{"Ufcs-"};
// Technically there are 2 location code prefixes, Ufcs and Umts, so
// if it already starts with a U then don't need to do anything.
if (locationCode.front() != 'U')
{
return locationCodePrefix + locationCode;
}
return locationCode;
}
std::string DataInterface::expandLocationCode(const std::string& locationCode,
uint16_t /*node*/) const
{
auto method =
_bus.new_method_call(service_name::vpdManager, object_path::vpdManager,
interface::vpdManager, "GetExpandedLocationCode");
method.append(addLocationCodePrefix(locationCode),
static_cast<uint16_t>(0));
auto reply = _bus.call(method);
std::string expandedLocationCode;
reply.read(expandedLocationCode);
return expandedLocationCode;
}
std::string
DataInterface::getInventoryFromLocCode(const std::string& locationCode,
uint16_t node, bool expanded) const
{
std::string methodName = expanded ? "GetFRUsByExpandedLocationCode"
: "GetFRUsByUnexpandedLocationCode";
auto method =
_bus.new_method_call(service_name::vpdManager, object_path::vpdManager,
interface::vpdManager, methodName.c_str());
if (expanded)
{
method.append(locationCode);
}
else
{
method.append(addLocationCodePrefix(locationCode), node);
}
auto reply = _bus.call(method);
std::vector<sdbusplus::message::object_path> entries;
reply.read(entries);
// Get the shortest entry from the paths received, as this
// would be the path furthest up the inventory hierarchy so
// would be the parent FRU. There is guaranteed to at least
// be one entry if the call didn't fail.
std::string shortest{entries[0]};
std::for_each(entries.begin(), entries.end(),
[&shortest](const auto& path) {
if (path.str.size() < shortest.size())
{
shortest = path;
}
});
return shortest;
}
void DataInterface::assertLEDGroup(const std::string& ledGroup,
bool value) const
{
DBusValue variant = value;
auto method =
_bus.new_method_call(service_name::ledGroupManager, ledGroup.c_str(),
interface::dbusProperty, "Set");
method.append(interface::ledGroup, "Asserted", variant);
_bus.call(method);
}
void DataInterface::setFunctional(const std::string& objectPath,
bool value) const
{
DBusValue variant = value;
auto service = getService(objectPath, interface::operationalStatus);
auto method = _bus.new_method_call(service.c_str(), objectPath.c_str(),
interface::dbusProperty, "Set");
method.append(interface::operationalStatus, "Functional", variant);
_bus.call(method);
}
std::vector<std::string> DataInterface::getSystemNames() const
{
DBusSubTree subtree;
DBusValue names;
auto method = _bus.new_method_call(service_name::objectMapper,
object_path::objectMapper,
interface::objectMapper, "GetSubTree");
method.append(std::string{"/"}, 0,
std::vector<std::string>{interface::compatible});
auto reply = _bus.call(method);
reply.read(subtree);
if (subtree.empty())
{
throw std::runtime_error("Compatible interface not on D-Bus");
}
const auto& object = *(subtree.begin());
const auto& path = object.first;
const auto& service = object.second.begin()->first;
getProperty(service, path, interface::compatible, "Names", names);
return std::get<std::vector<std::string>>(names);
}
} // namespace pels
} // namespace openpower
|
/**
* Copyright © 2019 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "data_interface.hpp"
#include "util.hpp"
#include <fmt/format.h>
#include <fstream>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/State/Boot/Progress/server.hpp>
namespace openpower
{
namespace pels
{
namespace service_name
{
constexpr auto objectMapper = "xyz.openbmc_project.ObjectMapper";
constexpr auto vpdManager = "com.ibm.VPD.Manager";
constexpr auto ledGroupManager = "xyz.openbmc_project.LED.GroupManager";
} // namespace service_name
namespace object_path
{
constexpr auto objectMapper = "/xyz/openbmc_project/object_mapper";
constexpr auto systemInv = "/xyz/openbmc_project/inventory/system";
constexpr auto chassisInv = "/xyz/openbmc_project/inventory/system/chassis";
constexpr auto motherBoardInv =
"/xyz/openbmc_project/inventory/system/chassis/motherboard";
constexpr auto baseInv = "/xyz/openbmc_project/inventory";
constexpr auto bmcState = "/xyz/openbmc_project/state/bmc0";
constexpr auto chassisState = "/xyz/openbmc_project/state/chassis0";
constexpr auto hostState = "/xyz/openbmc_project/state/host0";
constexpr auto pldm = "/xyz/openbmc_project/pldm";
constexpr auto enableHostPELs =
"/xyz/openbmc_project/logging/send_event_logs_to_host";
constexpr auto vpdManager = "/com/ibm/VPD/Manager";
} // namespace object_path
namespace interface
{
constexpr auto dbusProperty = "org.freedesktop.DBus.Properties";
constexpr auto objectMapper = "xyz.openbmc_project.ObjectMapper";
constexpr auto invAsset = "xyz.openbmc_project.Inventory.Decorator.Asset";
constexpr auto bootProgress = "xyz.openbmc_project.State.Boot.Progress";
constexpr auto pldmRequester = "xyz.openbmc_project.PLDM.Requester";
constexpr auto enable = "xyz.openbmc_project.Object.Enable";
constexpr auto bmcState = "xyz.openbmc_project.State.BMC";
constexpr auto chassisState = "xyz.openbmc_project.State.Chassis";
constexpr auto hostState = "xyz.openbmc_project.State.Host";
constexpr auto invMotherboard =
"xyz.openbmc_project.Inventory.Item.Board.Motherboard";
constexpr auto viniRecordVPD = "com.ibm.ipzvpd.VINI";
constexpr auto locCode = "com.ibm.ipzvpd.Location";
constexpr auto compatible =
"xyz.openbmc_project.Configuration.IBMCompatibleSystem";
constexpr auto vpdManager = "com.ibm.VPD.Manager";
constexpr auto ledGroup = "xyz.openbmc_project.Led.Group";
constexpr auto operationalStatus =
"xyz.openbmc_project.State.Decorator.OperationalStatus";
} // namespace interface
using namespace sdbusplus::xyz::openbmc_project::State::Boot::server;
using sdbusplus::exception::SdBusError;
using namespace phosphor::logging;
DataInterface::DataInterface(sdbusplus::bus::bus& bus) : _bus(bus)
{
readBMCFWVersion();
readServerFWVersion();
readBMCFWVersionID();
// Watch the BootProgress property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::hostState, interface::bootProgress, "BootProgress",
*this, [this](const auto& value) {
auto status = Progress::convertProgressStagesFromString(
std::get<std::string>(value));
if ((status == Progress::ProgressStages::SystemInitComplete) ||
(status == Progress::ProgressStages::OSStart) ||
(status == Progress::ProgressStages::OSRunning))
{
setHostUp(true);
}
else
{
setHostUp(false);
}
}));
// Watch the host PEL enable property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::enableHostPELs, interface::enable, "Enabled", *this,
[this](const auto& value) {
this->_sendPELsToHost = std::get<bool>(value);
}));
// Watch the BMCState property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::bmcState, interface::bmcState, "CurrentBMCState",
*this, [this](const auto& value) {
this->_bmcState = std::get<std::string>(value);
}));
// Watch the chassis current and requested power state properties
_properties.emplace_back(std::make_unique<InterfaceWatcher<DataInterface>>(
bus, object_path::chassisState, interface::chassisState, *this,
[this](const auto& properties) {
auto state = properties.find("CurrentPowerState");
if (state != properties.end())
{
this->_chassisState = std::get<std::string>(state->second);
}
auto trans = properties.find("RequestedPowerTransition");
if (trans != properties.end())
{
this->_chassisTransition = std::get<std::string>(trans->second);
}
}));
// Watch the CurrentHostState property
_properties.emplace_back(std::make_unique<PropertyWatcher<DataInterface>>(
bus, object_path::hostState, interface::hostState, "CurrentHostState",
*this, [this](const auto& value) {
this->_hostState = std::get<std::string>(value);
}));
}
DBusPropertyMap
DataInterface::getAllProperties(const std::string& service,
const std::string& objectPath,
const std::string& interface) const
{
DBusPropertyMap properties;
auto method = _bus.new_method_call(service.c_str(), objectPath.c_str(),
interface::dbusProperty, "GetAll");
method.append(interface);
auto reply = _bus.call(method);
reply.read(properties);
return properties;
}
void DataInterface::getProperty(const std::string& service,
const std::string& objectPath,
const std::string& interface,
const std::string& property,
DBusValue& value) const
{
auto method = _bus.new_method_call(service.c_str(), objectPath.c_str(),
interface::dbusProperty, "Get");
method.append(interface, property);
auto reply = _bus.call(method);
reply.read(value);
}
DBusPathList DataInterface::getPaths(const DBusInterfaceList& interfaces) const
{
auto method = _bus.new_method_call(
service_name::objectMapper, object_path::objectMapper,
interface::objectMapper, "GetSubTreePaths");
method.append(std::string{"/"}, 0, interfaces);
auto reply = _bus.call(method);
DBusPathList paths;
reply.read(paths);
return paths;
}
DBusService DataInterface::getService(const std::string& objectPath,
const std::string& interface) const
{
auto method = _bus.new_method_call(service_name::objectMapper,
object_path::objectMapper,
interface::objectMapper, "GetObject");
method.append(objectPath, std::vector<std::string>({interface}));
auto reply = _bus.call(method);
std::map<DBusService, DBusInterfaceList> response;
reply.read(response);
if (!response.empty())
{
return response.begin()->first;
}
return std::string{};
}
void DataInterface::readBMCFWVersion()
{
_bmcFWVersion =
phosphor::logging::util::getOSReleaseValue("VERSION").value_or("");
}
void DataInterface::readServerFWVersion()
{
auto value =
phosphor::logging::util::getOSReleaseValue("VERSION_ID").value_or("");
if ((value != "") && (value.find_last_of(')') != std::string::npos))
{
std::size_t pos = value.find_first_of('(') + 1;
_serverFWVersion = value.substr(pos, value.find_last_of(')') - pos);
}
}
void DataInterface::readBMCFWVersionID()
{
_bmcFWVersionID =
phosphor::logging::util::getOSReleaseValue("VERSION_ID").value_or("");
}
std::string DataInterface::getMachineTypeModel() const
{
std::string model;
try
{
auto service = getService(object_path::systemInv, interface::invAsset);
if (!service.empty())
{
DBusValue value;
getProperty(service, object_path::systemInv, interface::invAsset,
"Model", value);
model = std::get<std::string>(value);
}
}
catch (const std::exception& e)
{
log<level::WARNING>(fmt::format("Failed reading Model property from "
"Interface: {} exception: {}",
interface::invAsset, e.what())
.c_str());
}
return model;
}
std::string DataInterface::getMachineSerialNumber() const
{
std::string sn;
try
{
auto service = getService(object_path::systemInv, interface::invAsset);
if (!service.empty())
{
DBusValue value;
getProperty(service, object_path::systemInv, interface::invAsset,
"SerialNumber", value);
sn = std::get<std::string>(value);
}
}
catch (const std::exception& e)
{
log<level::WARNING>(
fmt::format("Failed reading SerialNumber property from "
"Interface: {} exception: {}",
interface::invAsset, e.what())
.c_str());
}
return sn;
}
std::string DataInterface::getMotherboardCCIN() const
{
std::string ccin;
try
{
auto service =
getService(object_path::motherBoardInv, interface::viniRecordVPD);
if (!service.empty())
{
DBusValue value;
getProperty(service, object_path::motherBoardInv,
interface::viniRecordVPD, "CC", value);
auto cc = std::get<std::vector<uint8_t>>(value);
ccin = std::string{cc.begin(), cc.end()};
}
}
catch (const std::exception& e)
{
log<level::WARNING>(
fmt::format("Failed reading Motherboard CCIN property from "
"Interface: {} exception: {}",
interface::viniRecordVPD, e.what())
.c_str());
}
return ccin;
}
void DataInterface::getHWCalloutFields(const std::string& inventoryPath,
std::string& fruPartNumber,
std::string& ccin,
std::string& serialNumber) const
{
// For now, attempt to get all of the properties directly on the path
// passed in. In the future, may need to make use of an algorithm
// to figure out which inventory objects actually hold these
// interfaces in the case of non FRUs, or possibly another service
// will provide this info. Any missing interfaces will result
// in exceptions being thrown.
auto service = getService(inventoryPath, interface::viniRecordVPD);
auto properties =
getAllProperties(service, inventoryPath, interface::viniRecordVPD);
auto value = std::get<std::vector<uint8_t>>(properties["FN"]);
fruPartNumber = std::string{value.begin(), value.end()};
value = std::get<std::vector<uint8_t>>(properties["CC"]);
ccin = std::string{value.begin(), value.end()};
value = std::get<std::vector<uint8_t>>(properties["SN"]);
serialNumber = std::string{value.begin(), value.end()};
}
std::string
DataInterface::getLocationCode(const std::string& inventoryPath) const
{
auto service = getService(inventoryPath, interface::locCode);
DBusValue locCode;
getProperty(service, inventoryPath, interface::locCode, "LocationCode",
locCode);
return std::get<std::string>(locCode);
}
std::string
DataInterface::addLocationCodePrefix(const std::string& locationCode)
{
static const std::string locationCodePrefix{"Ufcs-"};
// Technically there are 2 location code prefixes, Ufcs and Umts, so
// if it already starts with a U then don't need to do anything.
if (locationCode.front() != 'U')
{
return locationCodePrefix + locationCode;
}
return locationCode;
}
std::string DataInterface::expandLocationCode(const std::string& locationCode,
uint16_t /*node*/) const
{
auto method =
_bus.new_method_call(service_name::vpdManager, object_path::vpdManager,
interface::vpdManager, "GetExpandedLocationCode");
method.append(addLocationCodePrefix(locationCode),
static_cast<uint16_t>(0));
auto reply = _bus.call(method);
std::string expandedLocationCode;
reply.read(expandedLocationCode);
return expandedLocationCode;
}
std::string
DataInterface::getInventoryFromLocCode(const std::string& locationCode,
uint16_t node, bool expanded) const
{
std::string methodName = expanded ? "GetFRUsByExpandedLocationCode"
: "GetFRUsByUnexpandedLocationCode";
auto method =
_bus.new_method_call(service_name::vpdManager, object_path::vpdManager,
interface::vpdManager, methodName.c_str());
if (expanded)
{
method.append(locationCode);
}
else
{
method.append(addLocationCodePrefix(locationCode), node);
}
auto reply = _bus.call(method);
std::vector<sdbusplus::message::object_path> entries;
reply.read(entries);
// Get the shortest entry from the paths received, as this
// would be the path furthest up the inventory hierarchy so
// would be the parent FRU. There is guaranteed to at least
// be one entry if the call didn't fail.
std::string shortest{entries[0]};
std::for_each(entries.begin(), entries.end(),
[&shortest](const auto& path) {
if (path.str.size() < shortest.size())
{
shortest = path;
}
});
return shortest;
}
void DataInterface::assertLEDGroup(const std::string& ledGroup,
bool value) const
{
DBusValue variant = value;
auto method =
_bus.new_method_call(service_name::ledGroupManager, ledGroup.c_str(),
interface::dbusProperty, "Set");
method.append(interface::ledGroup, "Asserted", variant);
_bus.call(method);
}
void DataInterface::setFunctional(const std::string& objectPath,
bool value) const
{
DBusValue variant = value;
auto service = getService(objectPath, interface::operationalStatus);
auto method = _bus.new_method_call(service.c_str(), objectPath.c_str(),
interface::dbusProperty, "Set");
method.append(interface::operationalStatus, "Functional", variant);
_bus.call(method);
}
std::vector<std::string> DataInterface::getSystemNames() const
{
DBusSubTree subtree;
DBusValue names;
auto method = _bus.new_method_call(service_name::objectMapper,
object_path::objectMapper,
interface::objectMapper, "GetSubTree");
method.append(std::string{"/"}, 0,
std::vector<std::string>{interface::compatible});
auto reply = _bus.call(method);
reply.read(subtree);
if (subtree.empty())
{
throw std::runtime_error("Compatible interface not on D-Bus");
}
const auto& object = *(subtree.begin());
const auto& path = object.first;
const auto& service = object.second.begin()->first;
getProperty(service, path, interface::compatible, "Names", names);
return std::get<std::vector<std::string>>(names);
}
} // namespace pels
} // namespace openpower
|
Update serverFWRelVer in ext user header section
|
PEL: Update serverFWRelVer in ext user header section
The Extended User Header section has a field for server
firmware version. Get this field updated from os-release.
Test: Verified PEL tool output for ext user header section
Signed-off-by: Sumit Kumar <[email protected]>
Change-Id: I24cf7a44d71f8afaac3f1d1073fe2a5e13d46628
|
C++
|
apache-2.0
|
openbmc/phosphor-logging,openbmc/phosphor-logging,openbmc/phosphor-logging,openbmc/phosphor-logging
|
9e3c336ecf977fd80cb1e0550141c82e931ddb35
|
src/logger.cc
|
src/logger.cc
|
/*
* Copyright (C) 2016,2017 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "logger.h"
#include <ctime> // for time_t
#include <functional> // for ref
#include <iostream> // for cerr
#include <regex> // for regex_replace, regex
#include <stdarg.h> // for va_list, va_end, va_start
#include <stdexcept> // for out_of_range
#include <stdio.h> // for fileno, vsnprintf, stderr
#include <system_error> // for system_error
#include <unistd.h> // for isatty
#include "datetime.h" // for to_string
#include "exception.h" // for traceback
#include "utils.h" // for get_thread_name
#define BUFFER_SIZE (500 * 1024)
#define STACKED_INDENT "<indent>"
std::atomic<uint64_t> logger_info_hook;
const std::regex filter_re("\033\\[[;\\d]*m");
std::mutex Log::stack_mtx;
std::unordered_map<std::thread::id, unsigned> Log::stack_levels;
int Log::log_level = DEFAULT_LOG_LEVEL;
std::vector<std::unique_ptr<Logger>> Log::handlers;
const char *priorities[] = {
EMERG_COL "█" NO_COL, // LOG_EMERG 0 = System is unusable
ALERT_COL "▉" NO_COL, // LOG_ALERT 1 = Action must be taken immediately
CRIT_COL "▊" NO_COL, // LOG_CRIT 2 = Critical conditions
ERR_COL "▋" NO_COL, // LOG_ERR 3 = Error conditions
WARNING_COL "▌" NO_COL, // LOG_WARNING 4 = Warning conditions
NOTICE_COL "▍" NO_COL, // LOG_NOTICE 5 = Normal but significant condition
INFO_COL "▎" NO_COL, // LOG_INFO 6 = Informational
DEBUG_COL "▏" NO_COL, // LOG_DEBUG 7 = Debug-level messages
NO_COL, // VERBOSE > 7 = Verbose messages
};
static inline int
validated_priority(int priority) {
if (priority < 0) {
priority = -priority;
}
if (priority > LOG_DEBUG + 1) {
priority = LOG_DEBUG + 1;
}
return priority;
}
void
println(bool with_endl, const char *format, va_list argptr, const void* obj, bool info)
{
std::string str(Log::str_format(false, LOG_DEBUG, "", "", 0, "", "", obj, format, argptr, info));
Log::log(LOG_DEBUG, str, 0, info, with_endl);
}
LogWrapper
_log(bool cleanup, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const void*, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
auto ret = _log(cleanup, stacked, wakeup, async, priority, std::string(), file, line, suffix, prefix, obj, format, argptr);
va_end(argptr);
return ret;
}
LogWrapper
_log(bool cleanup, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
return Log::log(cleanup, stacked, wakeup, async, priority, exc, file, line, suffix, prefix, obj, format, argptr);
}
LogWrapper::LogWrapper(LogWrapper&& o)
: log(std::move(o.log))
{
o.log.reset();
}
LogWrapper&
LogWrapper::operator=(LogWrapper&& o)
{
log = std::move(o.log);
o.log.reset();
return *this;
}
LogWrapper::LogWrapper(LogType log_)
: log(log_) { }
LogWrapper::~LogWrapper()
{
if (log) {
log->cleanup();
}
log.reset();
}
bool
LogWrapper::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
return log->unlog(priority, file, line, suffix, prefix, obj, format, argptr);
}
bool
LogWrapper::clear()
{
return log->clear();
}
long double
LogWrapper::age()
{
return log->age();
}
LogType
LogWrapper::release()
{
auto ret = log;
log.reset();
return ret;
}
void
StreamLogger::log(int priority, const std::string& str, bool with_priority, bool with_endl)
{
ofs << std::regex_replace((with_priority ? priorities[validated_priority(priority)] : "") + str, filter_re, "");
if (with_endl) {
ofs << std::endl;
}
}
void
StderrLogger::log(int priority, const std::string& str, bool with_priority, bool with_endl)
{
if (isatty(fileno(stderr))) {
std::cerr << (with_priority ? priorities[validated_priority(priority)] : "") + str;
} else {
std::cerr << std::regex_replace((with_priority ? priorities[validated_priority(priority)] : "") + str, filter_re, "");
}
if (with_endl) {
std::cerr << std::endl;
}
}
SysLog::SysLog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void
SysLog::log(int priority, const std::string& str, bool with_priority, bool)
{
syslog(priority, "%s", std::regex_replace((with_priority ? priorities[validated_priority(priority)] : "") + str, filter_re, "").c_str());
}
Log::Log(const std::string& str, bool clean_, bool stacked_, bool async_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)
: ScheduledTask(created_at_),
stack_level(0),
stacked(stacked_),
clean(clean_),
str_start(str),
async(async_),
priority(priority_),
cleaned(false)
{
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
thread_id = std::this_thread::get_id();
try {
stack_level = ++stack_levels.at(thread_id);
} catch (const std::out_of_range&) {
stack_levels[thread_id] = 0;
}
}
}
Log::~Log()
{
cleanup();
}
void
Log::cleanup()
{
unsigned long long c = 0;
cleared_at.compare_exchange_strong(c, clean ? time_point_to_ullong(std::chrono::system_clock::now()) : 0);
if (!cleaned.exchange(true)) {
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
if (stack_levels.at(thread_id)-- == 0) {
stack_levels.erase(thread_id);
}
}
}
}
long double
Log::age()
{
auto now = (cleared_at > created_at) ? time_point_from_ullong(cleared_at) : std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(now - time_point_from_ullong(created_at)).count();
}
/*
* https://isocpp.org/wiki/faq/ctors#static-init-order
* Avoid the "static initialization order fiasco"
*/
Scheduler&
Log::scheduler()
{
static Scheduler scheduler("LOG");
return scheduler;
}
void
Log::finish(int wait)
{
scheduler().finish(wait);
}
void
Log::join()
{
scheduler().join();
}
void
Log::run()
{
L_INFO_HOOK_LOG("Log::run", this, "Log::run()");
auto msg = str_start;
auto log_age = age();
if (log_age > 2e8) {
msg += " ~" + delta_string(log_age, true);
}
Log::log(priority, msg, stack_level * 2);
}
std::string
Log::str_format(bool stacked, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr, bool info)
{
char* buffer = new char[BUFFER_SIZE];
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
std::string msg(buffer);
std::string result;
if (info && validated_priority(priority) <= LOG_DEBUG) {
auto iso8601 = "[" + Datetime::to_string(std::chrono::system_clock::now()) + "]";
auto tid = " (" + get_thread_name() + ")";
result = iso8601 + tid;
#ifdef LOG_OBJ_ADDRESS
if (obj) {
snprintf(buffer, BUFFER_SIZE, " [%p]", obj);
result += buffer;
}
#else
(void)obj;
#endif
result += " ";
#ifdef LOG_LOCATION
result += std::string(file) + ":" + std::to_string(line) + ": ";
#endif
}
if (stacked) {
result += STACKED_INDENT;
}
result += prefix + msg + suffix;
delete []buffer;
if (priority < 0) {
if (exc.empty()) {
result += DARK_GREY + traceback(file, line) + NO_COL;
} else {
result += NO_COL + exc + NO_COL;
}
}
return result;
}
LogWrapper
Log::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
if (priority > log_level) {
return LogWrapper(std::make_shared<Log>("", clean, stacked, async, priority, std::chrono::system_clock::now()));
}
std::string str(str_format(stacked, priority, exc, file, line, suffix, prefix, obj, format, argptr, true)); // TODO: Slow!
return print(str, clean, stacked, wakeup, async, priority);
}
LogWrapper
Log::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
auto ret = log(clean, stacked, wakeup, async, priority, exc, file, line, suffix, prefix, obj, format, argptr);
va_end(argptr);
return ret;
}
bool
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
if (!clear()) {
if (priority > log_level) {
return false;
}
std::string str(str_format(stacked, priority, std::string(), file, line, suffix, prefix, obj, format, argptr, true));
print(str, false, stacked, 0, async, priority, time_point_from_ullong(created_at));
return true;
}
return false;
}
bool
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
auto ret = unlog(priority, file, line, suffix, prefix, obj, format, argptr);
va_end(argptr);
return ret;
}
LogWrapper
Log::add(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
auto l_ptr = std::make_shared<Log>(str, clean, stacked, async, priority, created_at);
scheduler().add(l_ptr, wakeup);
return LogWrapper(l_ptr);
}
void
Log::log(int priority, std::string str, int indent, bool with_priority, bool with_endl)
{
static std::mutex log_mutex;
std::lock_guard<std::mutex> lk(log_mutex);
auto needle = str.find(STACKED_INDENT);
if (needle != std::string::npos) {
str.replace(needle, sizeof(STACKED_INDENT) - 1, std::string(indent, ' '));
}
for (auto& handler : handlers) {
handler->log(priority, str, with_priority, with_endl);
}
}
LogWrapper
Log::print(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
if (priority > log_level) {
return LogWrapper(std::make_shared<Log>(str, clean, stacked, async, priority, created_at));
}
if (async || wakeup > std::chrono::system_clock::now()) {
return add(str, clean, stacked, wakeup, async, priority, created_at);
} else {
auto l_ptr = std::make_shared<Log>(str, clean, stacked, async, priority, created_at);
log(priority, str, l_ptr->stack_level * 2);
return LogWrapper(l_ptr);
}
}
|
/*
* Copyright (C) 2016,2017 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "logger.h"
#include <ctime> // for time_t
#include <functional> // for ref
#include <iostream> // for cerr
#include <regex> // for regex_replace, regex
#include <stdarg.h> // for va_list, va_end, va_start
#include <stdexcept> // for out_of_range
#include <stdio.h> // for fileno, vsnprintf, stderr
#include <system_error> // for system_error
#include <unistd.h> // for isatty
#include "datetime.h" // for to_string
#include "exception.h" // for traceback
#include "utils.h" // for get_thread_name
#define BUFFER_SIZE (500 * 1024)
#define STACKED_INDENT "<indent>"
std::atomic<uint64_t> logger_info_hook;
const std::regex filter_re("\033\\[[;\\d]*m", std::regex::optimize);
std::mutex Log::stack_mtx;
std::unordered_map<std::thread::id, unsigned> Log::stack_levels;
int Log::log_level = DEFAULT_LOG_LEVEL;
std::vector<std::unique_ptr<Logger>> Log::handlers;
const char *priorities[] = {
EMERG_COL "█" NO_COL, // LOG_EMERG 0 = System is unusable
ALERT_COL "▉" NO_COL, // LOG_ALERT 1 = Action must be taken immediately
CRIT_COL "▊" NO_COL, // LOG_CRIT 2 = Critical conditions
ERR_COL "▋" NO_COL, // LOG_ERR 3 = Error conditions
WARNING_COL "▌" NO_COL, // LOG_WARNING 4 = Warning conditions
NOTICE_COL "▍" NO_COL, // LOG_NOTICE 5 = Normal but significant condition
INFO_COL "▎" NO_COL, // LOG_INFO 6 = Informational
DEBUG_COL "▏" NO_COL, // LOG_DEBUG 7 = Debug-level messages
NO_COL, // VERBOSE > 7 = Verbose messages
};
static inline int
validated_priority(int priority) {
if (priority < 0) {
priority = -priority;
}
if (priority > LOG_DEBUG + 1) {
priority = LOG_DEBUG + 1;
}
return priority;
}
void
println(bool with_endl, const char *format, va_list argptr, const void* obj, bool info)
{
std::string str(Log::str_format(false, LOG_DEBUG, "", "", 0, "", "", obj, format, argptr, info));
Log::log(LOG_DEBUG, str, 0, info, with_endl);
}
LogWrapper
_log(bool cleanup, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const void*, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
auto ret = _log(cleanup, stacked, wakeup, async, priority, std::string(), file, line, suffix, prefix, obj, format, argptr);
va_end(argptr);
return ret;
}
LogWrapper
_log(bool cleanup, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
return Log::log(cleanup, stacked, wakeup, async, priority, exc, file, line, suffix, prefix, obj, format, argptr);
}
LogWrapper::LogWrapper(LogWrapper&& o)
: log(std::move(o.log))
{
o.log.reset();
}
LogWrapper&
LogWrapper::operator=(LogWrapper&& o)
{
log = std::move(o.log);
o.log.reset();
return *this;
}
LogWrapper::LogWrapper(LogType log_)
: log(log_) { }
LogWrapper::~LogWrapper()
{
if (log) {
log->cleanup();
}
log.reset();
}
bool
LogWrapper::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
return log->unlog(priority, file, line, suffix, prefix, obj, format, argptr);
}
bool
LogWrapper::clear()
{
return log->clear();
}
long double
LogWrapper::age()
{
return log->age();
}
LogType
LogWrapper::release()
{
auto ret = log;
log.reset();
return ret;
}
void
StreamLogger::log(int priority, const std::string& str, bool with_priority, bool with_endl)
{
ofs << std::regex_replace((with_priority ? priorities[validated_priority(priority)] : "") + str, filter_re, "");
if (with_endl) {
ofs << std::endl;
}
}
void
StderrLogger::log(int priority, const std::string& str, bool with_priority, bool with_endl)
{
if (isatty(fileno(stderr))) {
std::cerr << (with_priority ? priorities[validated_priority(priority)] : "") + str;
} else {
std::cerr << std::regex_replace((with_priority ? priorities[validated_priority(priority)] : "") + str, filter_re, "");
}
if (with_endl) {
std::cerr << std::endl;
}
}
SysLog::SysLog(const char *ident, int option, int facility)
{
openlog(ident, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void
SysLog::log(int priority, const std::string& str, bool with_priority, bool)
{
syslog(priority, "%s", std::regex_replace((with_priority ? priorities[validated_priority(priority)] : "") + str, filter_re, "").c_str());
}
Log::Log(const std::string& str, bool clean_, bool stacked_, bool async_, int priority_, std::chrono::time_point<std::chrono::system_clock> created_at_)
: ScheduledTask(created_at_),
stack_level(0),
stacked(stacked_),
clean(clean_),
str_start(str),
async(async_),
priority(priority_),
cleaned(false)
{
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
thread_id = std::this_thread::get_id();
try {
stack_level = ++stack_levels.at(thread_id);
} catch (const std::out_of_range&) {
stack_levels[thread_id] = 0;
}
}
}
Log::~Log()
{
cleanup();
}
void
Log::cleanup()
{
unsigned long long c = 0;
cleared_at.compare_exchange_strong(c, clean ? time_point_to_ullong(std::chrono::system_clock::now()) : 0);
if (!cleaned.exchange(true)) {
if (stacked) {
std::lock_guard<std::mutex> lk(stack_mtx);
if (stack_levels.at(thread_id)-- == 0) {
stack_levels.erase(thread_id);
}
}
}
}
long double
Log::age()
{
auto now = (cleared_at > created_at) ? time_point_from_ullong(cleared_at) : std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(now - time_point_from_ullong(created_at)).count();
}
/*
* https://isocpp.org/wiki/faq/ctors#static-init-order
* Avoid the "static initialization order fiasco"
*/
Scheduler&
Log::scheduler()
{
static Scheduler scheduler("LOG");
return scheduler;
}
void
Log::finish(int wait)
{
scheduler().finish(wait);
}
void
Log::join()
{
scheduler().join();
}
void
Log::run()
{
L_INFO_HOOK_LOG("Log::run", this, "Log::run()");
auto msg = str_start;
auto log_age = age();
if (log_age > 2e8) {
msg += " ~" + delta_string(log_age, true);
}
Log::log(priority, msg, stack_level * 2);
}
std::string
Log::str_format(bool stacked, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void* obj, const char *format, va_list argptr, bool info)
{
char* buffer = new char[BUFFER_SIZE];
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
std::string msg(buffer);
std::string result;
if (info && validated_priority(priority) <= LOG_DEBUG) {
auto iso8601 = "[" + Datetime::to_string(std::chrono::system_clock::now()) + "]";
auto tid = " (" + get_thread_name() + ")";
result = iso8601 + tid;
#ifdef LOG_OBJ_ADDRESS
if (obj) {
snprintf(buffer, BUFFER_SIZE, " [%p]", obj);
result += buffer;
}
#else
(void)obj;
#endif
result += " ";
#ifdef LOG_LOCATION
result += std::string(file) + ":" + std::to_string(line) + ": ";
#endif
}
if (stacked) {
result += STACKED_INDENT;
}
result += prefix + msg + suffix;
delete []buffer;
if (priority < 0) {
if (exc.empty()) {
result += DARK_GREY + traceback(file, line) + NO_COL;
} else {
result += NO_COL + exc + NO_COL;
}
}
return result;
}
LogWrapper
Log::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
if (priority > log_level) {
return LogWrapper(std::make_shared<Log>("", clean, stacked, async, priority, std::chrono::system_clock::now()));
}
std::string str(str_format(stacked, priority, exc, file, line, suffix, prefix, obj, format, argptr, true)); // TODO: Slow!
return print(str, clean, stacked, wakeup, async, priority);
}
LogWrapper
Log::log(bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, const std::string& exc, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
auto ret = log(clean, stacked, wakeup, async, priority, exc, file, line, suffix, prefix, obj, format, argptr);
va_end(argptr);
return ret;
}
bool
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, va_list argptr)
{
if (!clear()) {
if (priority > log_level) {
return false;
}
std::string str(str_format(stacked, priority, std::string(), file, line, suffix, prefix, obj, format, argptr, true));
print(str, false, stacked, 0, async, priority, time_point_from_ullong(created_at));
return true;
}
return false;
}
bool
Log::unlog(int priority, const char *file, int line, const char *suffix, const char *prefix, const void *obj, const char *format, ...)
{
va_list argptr;
va_start(argptr, format);
auto ret = unlog(priority, file, line, suffix, prefix, obj, format, argptr);
va_end(argptr);
return ret;
}
LogWrapper
Log::add(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
auto l_ptr = std::make_shared<Log>(str, clean, stacked, async, priority, created_at);
scheduler().add(l_ptr, wakeup);
return LogWrapper(l_ptr);
}
void
Log::log(int priority, std::string str, int indent, bool with_priority, bool with_endl)
{
static std::mutex log_mutex;
std::lock_guard<std::mutex> lk(log_mutex);
auto needle = str.find(STACKED_INDENT);
if (needle != std::string::npos) {
str.replace(needle, sizeof(STACKED_INDENT) - 1, std::string(indent, ' '));
}
for (auto& handler : handlers) {
handler->log(priority, str, with_priority, with_endl);
}
}
LogWrapper
Log::print(const std::string& str, bool clean, bool stacked, std::chrono::time_point<std::chrono::system_clock> wakeup, bool async, int priority, std::chrono::time_point<std::chrono::system_clock> created_at)
{
if (priority > log_level) {
return LogWrapper(std::make_shared<Log>(str, clean, stacked, async, priority, created_at));
}
if (async || wakeup > std::chrono::system_clock::now()) {
return add(str, clean, stacked, wakeup, async, priority, created_at);
} else {
auto l_ptr = std::make_shared<Log>(str, clean, stacked, async, priority, created_at);
log(priority, str, l_ptr->stack_level * 2);
return LogWrapper(l_ptr);
}
}
|
Add flag std::regex::optimize in logger regex
|
Add flag std::regex::optimize in logger regex
|
C++
|
mit
|
Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand
|
7368e7722f53e3dfa913cca3584da93146af81d1
|
research/implementations/matching/fastest.cpp
|
research/implementations/matching/fastest.cpp
|
#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#include <omp.h>
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define ll long long
using namespace std;
class Graph {
public:
Graph(int _N) {
N = _N;
viz.assign(N, 0);
L.assign(N, -1);
R.assign(N, -1);
edges.assign(N, vector<int>());
}
void addEdge(int x, int y) {
edges[x].push_back(y);
}
void pop_vertex(int x) {
edges[x].pop_back();
}
bool pairup(int node) {
if (viz[node]) {
return 0;
}
viz[node] = 1;
for (auto vec: edges[node]) {
if (R[vec] == -1) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
for (auto vec: edges[node]) {
if (pairup(R[vec])) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
return 0;
}
int maxMatch(int last_node) {
int change = 1;
while(change) {
change = 0;
#pragma omp parallel for
for (int i = 0; i <= last_node; ++i) {
viz[i] = 0;
}
change |= pairup(L[last_node]);
}
return L[last_node]!=-1;
}
void write() {
for (int i = 0; i < N; ++i) {
for (auto vertex: edges[i]) {
cout << vertex + 1 << " " ;
}
cout << "\n";
}
}
vector<int> L, R;
vector<vector<int>> edges;
vector<int> viz;
int N;
};
class Solver{
public:
Solver(int _N) {
N = _N;
edge_c.assign(1<<N,set<int>());
mark.assign(1<<N, 0);
edge_mask.assign(N, 0);
SOL = 0;
}
void gen_canceling_sets() {
for (int conf1 = 0; conf1 < (1 << N); ++conf1) {
for (int conf2 = 0; conf2 < (1 << N); ++conf2) {
int inter = conf1 & conf2;
if (inter == conf1 || inter == conf2) {
edge_c[conf1].insert(conf2);
edge_c[conf2].insert(conf1);
}
}
}
for (int conf1 = 1; conf1 < (1 << N) - 1; ++conf1) {
candidates.insert(conf1);
}
}
int check_sets_intersect(const vector<int>& edges, Graph& G) {
/*
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
if ( (edges[i] & edges[j]) == 0) {
return 0;
}
}
}*/
vector<int> tmp(edges);
sort(tmp.begin(), tmp.end());
unique_matchings.insert(tmp);
//G.write();
return 1;
}
void back(int k, Graph& G, set<int> select) {
if (k == N) {
// do i really care about this?
//SOL += check_sets_intersect(edge_mask, G);
} else {
set<int> cl_select(select);
for (auto conf: cl_select) {
for (int bit = 0; bit < N; ++bit) {
if (conf & (1 << bit)) {
edge_mask[bit] |= (1 << k);
G.addEdge(k, bit);
}
}
if (!G.maxMatch(k)) {
cout << "NO MAX MATCH\n";
G.write();
}
vector<int> to_erase;
for (set<int>::iterator temp_it = edge_c[conf].begin(); \
temp_it != edge_c[conf].end(); ++temp_it) {
auto tmpconf = *temp_it;
set<int>::iterator it = select.find(tmpconf);
if (it != select.end()) {
to_erase.push_back(tmpconf);
select.erase(it);
}
}
back(k + 1, G, select);
for (auto tmpconf: to_erase) {
select.insert(tmpconf);
}
for (int bit = 0; bit < N; ++bit) {
if (conf & (1 << bit)) {
edge_mask[bit] ^= (1 << k);
G.pop_vertex(k);
}
}
}
}
}
void solve() {
gen_canceling_sets();
Graph G(N);
cout << "finished pre_processing\n";
back(0, G, candidates);
cout << "found " << unique_matchings.size() << " matchings\n";
}
vector<set<int>> edge_c;
vector<int> edge_mask;
vector<int> mark;
set<int> candidates;
set<vector<int>> unique_matchings;
int N;
int SOL;
};
int main() {
ifstream cin("test.in");
ofstream cout("test.out");
int N; cin >> N;
Solver S(N);
S.solve();
return 0;
}
|
#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#include <omp.h>
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define ll long long
using namespace std;
class Graph {
public:
Graph(int _N) {
N = _N;
viz.assign(N, 0);
L.assign(N, -1);
R.assign(N, -1);
edges.assign(N, vector<int>());
}
Graph(const Graph &other): L(other.L), R(other.R){
N = other.N;
viz.assign(N, 0);
L.assign(N, -1);
R.assign(N, -1);
edges.assign(N, vector<int>());
for (int i = 0; i < N; ++i) {
L[i] = other.L[i];
R[i] = other.R[i];
edges[i].assign(other.edges[i].size(), 0);
std::copy(other.edges[i].begin(), other.edges[i].end(), edges[i].begin());
}
}
Graph operator=( Graph rhs ) {
Graph G(rhs);
return G;
}
void addEdge(int x, int y) {
edges[x].push_back(y);
}
void pop_vertex(int x) {
edges[x].pop_back();
}
bool pairup(int node) {
if (viz[node]) {
return 0;
}
viz[node] = 1;
for (auto vec: edges[node]) {
if (R[vec] == -1) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
for (auto vec: edges[node]) {
if (pairup(R[vec])) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
return 0;
}
int maxMatch(int last_node) {
int change = 1;
while(change) {
change = 0;
for (int i = 0; i <= last_node; ++i) {
viz[i] = 0;
}
change |= pairup(last_node);
}
return L[last_node] != -1;
}
void write() {
for (int i = 0; i < N; ++i) {
cout << i << "-> ";
for (auto vertex: edges[i]) {
cout << vertex + 1 << " " ;
}
cout << "\n";
}
}
vector<int> L, R;
vector<vector<int>> edges;
vector<int> viz;
int N;
};
class Solver{
public:
Solver(int _N) {
N = _N;
edge_c.assign(1<<N,set<int>());
mark.assign(1<<N, 0);
edge_mask.assign(N, 0);
SOL = 0;
}
void gen_canceling_sets() {
for (int conf1 = 0; conf1 < (1 << N); ++conf1) {
for (int conf2 = 0; conf2 < (1 << N); ++conf2) {
int inter = conf1 & conf2;
if (inter == conf1 || inter == conf2) {
edge_c[conf1].insert(conf2);
edge_c[conf2].insert(conf1);
}
}
}
for (int conf1 = 1; conf1 < (1 << N) - 1; ++conf1) {
candidates.insert(conf1);
}
}
int check_sets_intersect(const vector<int>& edges, Graph& G) {
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
if ( (edges[i] & edges[j]) == 0) {
return 0;
}
}
}
vector<int> tmp(edges);
sort(tmp.begin(), tmp.end());
if (unique_matchings.find(tmp) == unique_matchings.end()) {
unique_matchings.insert(tmp);
G.write();
cerr << "\n";
}
return 1;
}
void back(int k, Graph G, set<int> select) {
G.write();
cout << "#########\n";
if (k == N) {
// do i really care about this?
SOL += check_sets_intersect(edge_mask, G);
} else {
vector <int> vec_select(select.begin(), select.end());
#pragma omp parallel for private(select) firstprivate(G)
for (int i = 0; i < vec_select.size(); ++i) {
int conf = vec_select[i];
for (int bit = 0; bit < N; ++bit) {
if (conf & (1 << bit)) {
edge_mask[bit] |= (1 << k);
G.addEdge(k, bit);
}
}
if (!G.maxMatch(k)) {
cout << "NO MAX MATCH\n";
G.write();
}
vector<int> to_erase;
for (set<int>::iterator temp_it = edge_c[conf].begin(); \
temp_it != edge_c[conf].end(); ++temp_it) {
auto tmpconf = *temp_it;
set<int>::iterator it = select.find(tmpconf);
if (it != select.end()) {
to_erase.push_back(tmpconf);
select.erase(it);
}
}
back(k + 1, G, select);
for (auto tmpconf: to_erase) {
select.insert(tmpconf);
}
for (int bit = 0; bit < N; ++bit) {
if (conf & (1 << bit)) {
edge_mask[bit] ^= (1 << k);
G.pop_vertex(k);
}
}
}
}
}
void solve() {
gen_canceling_sets();
cout << "finished pre_processing\n";
Graph G(N);
//G.addEdge(1, 2);
back(0, G, candidates);
//Graph B(G);
//B.write();
cout << "found " << unique_matchings.size() << " matchings\n";
}
vector<set<int>> edge_c;
vector<int> edge_mask;
vector<int> mark;
set<int> candidates;
set<vector<int>> unique_matchings;
int N;
int SOL;
};
int main() {
ifstream cin("test.in");
ofstream cout("test.out");
int N; cin >> N;
Solver S(N);
S.solve();
return 0;
}
|
work in progress
|
work in progress
|
C++
|
mit
|
rdragos/work,rdragos/work,rdragos/work,rdragos/work,rdragos/work,rdragos/work,rdragos/work,rdragos/work
|
0d39dece4479e471c35dc8387b30022a67169344
|
tlsf_cpp/test/test_tlsf.cpp
|
tlsf_cpp/test/test_tlsf.cpp
|
// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <vector>
#include <utility>
#include "gtest/gtest.h"
#ifdef __GNUC__
#include <cxxabi.h>
#include <execinfo.h>
#include <malloc.h>
#endif
#include "rclcpp/strategies/allocator_memory_strategy.hpp"
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/u_int32.hpp"
#include "tlsf_cpp/tlsf.hpp"
#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif
// TODO(jacquelinekay) improve this ignore rule (dogfooding or no allocations)
static const size_t num_rmw_tokens = 7;
static const char * rmw_tokens[num_rmw_tokens] = {
"librmw", "dds", "DDS", "dcps", "DCPS", "fastrtps", "opensplice"
};
static const size_t iterations = 1;
static bool verbose = false;
static bool ignore_middleware_tokens = true;
static bool test_init = false;
static bool fail = false;
inline bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames = 15);
/// Declare a function pointer into which we will store the default malloc.
static void * (* prev_malloc_hook)(size_t, const void *);
// Use pragma to ignore a warning for using __malloc_hook, which is deprecated (but still awesome).
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
static void * testing_malloc(size_t size, const void * caller)
{
(void)caller;
// Set the malloc implementation to the default malloc hook so that we can call it implicitly
// to initialize a string, otherwise this function will loop infinitely.
__malloc_hook = prev_malloc_hook;
if (test_init) {
fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens);
}
// Execute the requested malloc.
void * mem = std::malloc(size);
// Set the malloc hook back to this function, so that we can intercept future mallocs.
__malloc_hook = testing_malloc;
return mem;
}
/// Function to be called when the malloc hook is initialized.
void init_malloc_hook()
{
// Store the default malloc.
prev_malloc_hook = __malloc_hook;
// Set our custom malloc to the malloc hook.
__malloc_hook = testing_malloc;
}
#pragma GCC diagnostic pop
/// Set the hook for malloc initialize so that init_malloc_hook gets called.
void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook;
/** Check a demangled stack backtrace of the caller function for the given tokens.
** Adapted from: https://panthema.net/2008/0901-stacktrace-demangled
**/
bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames)
{
#ifdef __GNUC__
bool match = false;
// storage array for stack trace address data
void * addrlist[max_frames + 1];
// retrieve current stack addresses
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void *));
if (addrlen == 0) {
fprintf(stderr, "WARNING: stack trace empty, possibly corrupt\n");
return false;
}
// resolve addresses into strings containing "filename(function+address)",
// this array must be free()-ed
char ** symbollist = backtrace_symbols(addrlist, addrlen);
// initialize string string which will be filled with the demangled function name
// allocate string which will be filled with the demangled function name
size_t funcnamesize = 256;
char * funcname = static_cast<char *>(std::malloc(funcnamesize));
if (verbose) {
fprintf(stderr, ">>>> stack trace:\n");
}
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 1; i < addrlen; i++) {
char * begin_name = 0, * begin_offset = 0, * end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
for (char * p = symbollist[i]; *p; ++p) {
if (*p == '(') {
begin_name = p;
} else if (*p == '+') {
begin_offset = p;
} else if (*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset &&
begin_name < begin_offset)
{
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
int status;
char * ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status);
if (status == 0) {
funcname = ret; // use possibly realloc()-ed string
for (size_t j = 0; j < num_tokens; ++j) {
if (strstr(symbollist[i],
tokens[j]) != nullptr || strstr(funcname, tokens[j]) != nullptr)
{
match = true;
break;
}
}
if (verbose) {
fprintf(stderr, " %s : %s+%s\n", symbollist[i], funcname, begin_offset);
}
} else {
// demangling failed. Output function name as a C function with
// no arguments.
for (size_t j = 0; j < num_tokens; j++) {
if (strstr(symbollist[i],
tokens[j]) != nullptr || strstr(begin_name, tokens[j]) != nullptr)
{
match = true;
break;
}
}
if (verbose) {
fprintf(stderr, " %s : %s()+%s\n", symbollist[i], begin_name, begin_offset);
}
}
} else {
// couldn't parse the line? print the whole line.
for (size_t j = 0; j < num_tokens; j++) {
if (strstr(symbollist[i], tokens[j]) != nullptr) {
match = true;
break;
}
}
if (verbose) {
fprintf(stderr, " %s\n", symbollist[i]);
}
}
}
free(funcname);
free(symbollist);
if (!ignore_middleware_tokens) {
return false;
}
return match;
#else
return true;
#endif // __GNUC__
}
void * operator new(std::size_t size)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
__malloc_hook = prev_malloc_hook;
if (test_init) {
// Check the stacktrace to see the call originated in librmw or a DDS implementation
fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens);
}
void * ptr = std::malloc(size);
__malloc_hook = testing_malloc;
#pragma GCC diagnostic pop
return ptr;
}
void operator delete(void * ptr) noexcept
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
__malloc_hook = prev_malloc_hook;
if (ptr != nullptr) {
if (test_init) {
// Check the stacktrace to see the call originated in librmw or a DDS implementation
fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens);
}
std::free(ptr);
ptr = nullptr;
}
__malloc_hook = testing_malloc;
#pragma GCC diagnostic pop
}
// In C++14, (some) compilers emit a warning when the user has overridden
// the unsized version of delete but not the sized version.
// see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3536.html
// "The workaround is to define a sized version that simply calls the unsized
// version."
void operator delete(void * ptr, size_t sz) noexcept
{
(void)sz; // unused parameter, since we're passing this to unsized delete
operator delete(ptr);
}
template<typename T = void>
using TLSFAllocator = tlsf_heap_allocator<T>;
using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy;
class CLASSNAME (AllocatorTest, RMW_IMPLEMENTATION) : public ::testing::Test
{
protected:
std::string test_name_;
rclcpp::Node::SharedPtr node_;
rclcpp::executors::SingleThreadedExecutor::SharedPtr executor_;
rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy_;
rclcpp::Publisher<
std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr publisher_;
rclcpp::message_memory_strategy::MessageMemoryStrategy<
std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr msg_memory_strategy_;
std::shared_ptr<TLSFAllocator<void>> alloc;
rclcpp::SubscriptionOptionsWithAllocator<TLSFAllocator<void>> subscription_options_;
rclcpp::PublisherOptionsWithAllocator<TLSFAllocator<void>> publisher_options_;
bool intra_process_;
using UInt32Allocator = TLSFAllocator<std_msgs::msg::UInt32>;
using UInt32Deleter = rclcpp::allocator::Deleter<UInt32Allocator, std_msgs::msg::UInt32>;
void initialize(bool intra_process, const std::string & name)
{
test_name_ = name;
intra_process_ = intra_process;
auto context = rclcpp::contexts::default_context::get_global_default_context();
auto options = rclcpp::NodeOptions()
.context(context)
.use_global_arguments(true)
.use_intra_process_comms(intra_process);
node_ = rclcpp::Node::make_shared(name, options);
alloc = std::make_shared<TLSFAllocator<void>>();
subscription_options_.allocator = alloc;
publisher_options_.allocator = alloc;
msg_memory_strategy_ = std::make_shared<
rclcpp::message_memory_strategy::MessageMemoryStrategy<
std_msgs::msg::UInt32, TLSFAllocator<void>>>(alloc);
publisher_ = node_->create_publisher<std_msgs::msg::UInt32>(name, 10, publisher_options_);
memory_strategy_ =
std::make_shared<AllocatorMemoryStrategy<TLSFAllocator<void>>>(alloc);
rclcpp::executor::ExecutorArgs args;
args.memory_strategy = memory_strategy_;
executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(args);
executor_->add_node(node_);
}
CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() {
}
~CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() {
}
};
TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), type_traits_test) {
using UInt32TLSFAllocator = TLSFAllocator<std_msgs::msg::UInt32>;
using UInt32TLSFDeleter = rclcpp::allocator::Deleter<UInt32TLSFAllocator, std_msgs::msg::UInt32>;
auto cb_tlsf = [](std_msgs::msg::UInt32::UniquePtrWithDeleter<UInt32TLSFDeleter> msg) -> void
{
(void) msg;
};
static_assert(
std::is_same<
std_msgs::msg::UInt32,
rclcpp::subscription_traits::has_message_type<decltype(cb_tlsf)>::type>::value,
"tlsf unique ptr failed");
using UInt32VoidAllocator = std::allocator<std_msgs::msg::UInt32>;
using UInt32VoidDeleter = rclcpp::allocator::Deleter<UInt32VoidAllocator, std_msgs::msg::UInt32>;
auto cb_void = [](std_msgs::msg::UInt32::UniquePtrWithDeleter<UInt32VoidDeleter> msg) -> void
{
(void) msg;
};
static_assert(
std::is_same<
std_msgs::msg::UInt32,
rclcpp::subscription_traits::has_message_type<decltype(cb_void)>::type>::value,
"void unique ptr failed");
}
/**
// TODO(wjwwood): re-enable this test when the allocator has been added back to the
// intra-process manager.
// See: https://github.com/ros2/realtime_support/pull/80#issuecomment-545419570
TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), allocator_unique_ptr) {
initialize(true, "allocator_unique_ptr");
size_t counter = 0;
auto callback =
[&counter](std::unique_ptr<std_msgs::msg::UInt32, UInt32Deleter> msg) -> void
{
EXPECT_EQ(counter, msg->data);
counter++;
};
static_assert(
std::is_same<
std_msgs::msg::UInt32,
rclcpp::subscription_traits::has_message_type<decltype(callback)>::type>::value,
"passing a std::unique_ptr of test_msgs::msg::Empty has message type Empty");
auto subscriber = node_->create_subscription<std_msgs::msg::UInt32>(
"allocator_unique_ptr", 10, callback, subscription_options_, msg_memory_strategy_);
TLSFAllocator<std_msgs::msg::UInt32> msg_alloc;
// After test_initialization, global new should only be called from within TLSFAllocator.
test_init = true;
for (uint32_t i = 0; i < iterations; i++) {
auto msg = std::unique_ptr<std_msgs::msg::UInt32, UInt32Deleter>(
std::allocator_traits<UInt32Allocator>::allocate(msg_alloc, 1));
msg->data = i;
publisher_->publish(std::move(msg));
rclcpp::sleep_for(std::chrono::milliseconds(1));
executor_->spin_some();
}
test_init = false;
EXPECT_FALSE(fail);
fail = false;
}
*/
void print_help()
{
printf("--all-tokens: Do not ignore middleware tokens.\n");
printf("--verbose: Report stack traces and allocation statistics.\n");
}
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
// argc and argv are modified by InitGoogleTest
std::vector<std::string> args(argv + 1, argv + argc);
if (std::find(args.begin(), args.end(), "--help") != args.end()) {
print_help();
return 0;
}
verbose = std::find(args.begin(), args.end(), "--verbose") != args.end();
ignore_middleware_tokens = std::find(args.begin(), args.end(), "--all-tokens") == args.end();
return RUN_ALL_TESTS();
}
|
// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <vector>
#include <utility>
#include "gtest/gtest.h"
#ifdef __GNUC__
#include <cxxabi.h>
#include <execinfo.h>
#include <malloc.h>
#endif
#include "rclcpp/strategies/allocator_memory_strategy.hpp"
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/u_int32.hpp"
#include "tlsf_cpp/tlsf.hpp"
#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif
// TODO(jacquelinekay) improve this ignore rule (dogfooding or no allocations)
static const size_t num_rmw_tokens = 7;
static const char * rmw_tokens[num_rmw_tokens] = {
"librmw", "dds", "DDS", "dcps", "DCPS", "fastrtps", "opensplice"
};
// TODO(wjwwood): uncomment this variable when the allocator has been added back to the
// intra-process manager.
// See: https://github.com/ros2/realtime_support/pull/80#issuecomment-545419570
// static const size_t iterations = 1;
static bool verbose = false;
static bool ignore_middleware_tokens = true;
static bool test_init = false;
static bool fail = false;
inline bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames = 15);
/// Declare a function pointer into which we will store the default malloc.
static void * (* prev_malloc_hook)(size_t, const void *);
// Use pragma to ignore a warning for using __malloc_hook, which is deprecated (but still awesome).
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
static void * testing_malloc(size_t size, const void * caller)
{
(void)caller;
// Set the malloc implementation to the default malloc hook so that we can call it implicitly
// to initialize a string, otherwise this function will loop infinitely.
__malloc_hook = prev_malloc_hook;
if (test_init) {
fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens);
}
// Execute the requested malloc.
void * mem = std::malloc(size);
// Set the malloc hook back to this function, so that we can intercept future mallocs.
__malloc_hook = testing_malloc;
return mem;
}
/// Function to be called when the malloc hook is initialized.
void init_malloc_hook()
{
// Store the default malloc.
prev_malloc_hook = __malloc_hook;
// Set our custom malloc to the malloc hook.
__malloc_hook = testing_malloc;
}
#pragma GCC diagnostic pop
/// Set the hook for malloc initialize so that init_malloc_hook gets called.
void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook;
/** Check a demangled stack backtrace of the caller function for the given tokens.
** Adapted from: https://panthema.net/2008/0901-stacktrace-demangled
**/
bool check_stacktrace(const char ** tokens, size_t num_tokens, size_t max_frames)
{
#ifdef __GNUC__
bool match = false;
// storage array for stack trace address data
void * addrlist[max_frames + 1];
// retrieve current stack addresses
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void *));
if (addrlen == 0) {
fprintf(stderr, "WARNING: stack trace empty, possibly corrupt\n");
return false;
}
// resolve addresses into strings containing "filename(function+address)",
// this array must be free()-ed
char ** symbollist = backtrace_symbols(addrlist, addrlen);
// initialize string string which will be filled with the demangled function name
// allocate string which will be filled with the demangled function name
size_t funcnamesize = 256;
char * funcname = static_cast<char *>(std::malloc(funcnamesize));
if (verbose) {
fprintf(stderr, ">>>> stack trace:\n");
}
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 1; i < addrlen; i++) {
char * begin_name = 0, * begin_offset = 0, * end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
for (char * p = symbollist[i]; *p; ++p) {
if (*p == '(') {
begin_name = p;
} else if (*p == '+') {
begin_offset = p;
} else if (*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset &&
begin_name < begin_offset)
{
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
int status;
char * ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status);
if (status == 0) {
funcname = ret; // use possibly realloc()-ed string
for (size_t j = 0; j < num_tokens; ++j) {
if (strstr(symbollist[i],
tokens[j]) != nullptr || strstr(funcname, tokens[j]) != nullptr)
{
match = true;
break;
}
}
if (verbose) {
fprintf(stderr, " %s : %s+%s\n", symbollist[i], funcname, begin_offset);
}
} else {
// demangling failed. Output function name as a C function with
// no arguments.
for (size_t j = 0; j < num_tokens; j++) {
if (strstr(symbollist[i],
tokens[j]) != nullptr || strstr(begin_name, tokens[j]) != nullptr)
{
match = true;
break;
}
}
if (verbose) {
fprintf(stderr, " %s : %s()+%s\n", symbollist[i], begin_name, begin_offset);
}
}
} else {
// couldn't parse the line? print the whole line.
for (size_t j = 0; j < num_tokens; j++) {
if (strstr(symbollist[i], tokens[j]) != nullptr) {
match = true;
break;
}
}
if (verbose) {
fprintf(stderr, " %s\n", symbollist[i]);
}
}
}
free(funcname);
free(symbollist);
if (!ignore_middleware_tokens) {
return false;
}
return match;
#else
return true;
#endif // __GNUC__
}
void * operator new(std::size_t size)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
__malloc_hook = prev_malloc_hook;
if (test_init) {
// Check the stacktrace to see the call originated in librmw or a DDS implementation
fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens);
}
void * ptr = std::malloc(size);
__malloc_hook = testing_malloc;
#pragma GCC diagnostic pop
return ptr;
}
void operator delete(void * ptr) noexcept
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
__malloc_hook = prev_malloc_hook;
if (ptr != nullptr) {
if (test_init) {
// Check the stacktrace to see the call originated in librmw or a DDS implementation
fail |= !check_stacktrace(rmw_tokens, num_rmw_tokens);
}
std::free(ptr);
ptr = nullptr;
}
__malloc_hook = testing_malloc;
#pragma GCC diagnostic pop
}
// In C++14, (some) compilers emit a warning when the user has overridden
// the unsized version of delete but not the sized version.
// see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3536.html
// "The workaround is to define a sized version that simply calls the unsized
// version."
void operator delete(void * ptr, size_t sz) noexcept
{
(void)sz; // unused parameter, since we're passing this to unsized delete
operator delete(ptr);
}
template<typename T = void>
using TLSFAllocator = tlsf_heap_allocator<T>;
using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy;
class CLASSNAME (AllocatorTest, RMW_IMPLEMENTATION) : public ::testing::Test
{
protected:
std::string test_name_;
rclcpp::Node::SharedPtr node_;
rclcpp::executors::SingleThreadedExecutor::SharedPtr executor_;
rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy_;
rclcpp::Publisher<
std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr publisher_;
rclcpp::message_memory_strategy::MessageMemoryStrategy<
std_msgs::msg::UInt32, TLSFAllocator<void>>::SharedPtr msg_memory_strategy_;
std::shared_ptr<TLSFAllocator<void>> alloc;
rclcpp::SubscriptionOptionsWithAllocator<TLSFAllocator<void>> subscription_options_;
rclcpp::PublisherOptionsWithAllocator<TLSFAllocator<void>> publisher_options_;
bool intra_process_;
using UInt32Allocator = TLSFAllocator<std_msgs::msg::UInt32>;
using UInt32Deleter = rclcpp::allocator::Deleter<UInt32Allocator, std_msgs::msg::UInt32>;
void initialize(bool intra_process, const std::string & name)
{
test_name_ = name;
intra_process_ = intra_process;
auto context = rclcpp::contexts::default_context::get_global_default_context();
auto options = rclcpp::NodeOptions()
.context(context)
.use_global_arguments(true)
.use_intra_process_comms(intra_process);
node_ = rclcpp::Node::make_shared(name, options);
alloc = std::make_shared<TLSFAllocator<void>>();
subscription_options_.allocator = alloc;
publisher_options_.allocator = alloc;
msg_memory_strategy_ = std::make_shared<
rclcpp::message_memory_strategy::MessageMemoryStrategy<
std_msgs::msg::UInt32, TLSFAllocator<void>>>(alloc);
publisher_ = node_->create_publisher<std_msgs::msg::UInt32>(name, 10, publisher_options_);
memory_strategy_ =
std::make_shared<AllocatorMemoryStrategy<TLSFAllocator<void>>>(alloc);
rclcpp::executor::ExecutorArgs args;
args.memory_strategy = memory_strategy_;
executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(args);
executor_->add_node(node_);
}
CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() {
}
~CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION)() {
}
};
TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), type_traits_test) {
using UInt32TLSFAllocator = TLSFAllocator<std_msgs::msg::UInt32>;
using UInt32TLSFDeleter = rclcpp::allocator::Deleter<UInt32TLSFAllocator, std_msgs::msg::UInt32>;
auto cb_tlsf = [](std_msgs::msg::UInt32::UniquePtrWithDeleter<UInt32TLSFDeleter> msg) -> void
{
(void) msg;
};
static_assert(
std::is_same<
std_msgs::msg::UInt32,
rclcpp::subscription_traits::has_message_type<decltype(cb_tlsf)>::type>::value,
"tlsf unique ptr failed");
using UInt32VoidAllocator = std::allocator<std_msgs::msg::UInt32>;
using UInt32VoidDeleter = rclcpp::allocator::Deleter<UInt32VoidAllocator, std_msgs::msg::UInt32>;
auto cb_void = [](std_msgs::msg::UInt32::UniquePtrWithDeleter<UInt32VoidDeleter> msg) -> void
{
(void) msg;
};
static_assert(
std::is_same<
std_msgs::msg::UInt32,
rclcpp::subscription_traits::has_message_type<decltype(cb_void)>::type>::value,
"void unique ptr failed");
}
/**
// TODO(wjwwood): re-enable this test when the allocator has been added back to the
// intra-process manager.
// See: https://github.com/ros2/realtime_support/pull/80#issuecomment-545419570
TEST_F(CLASSNAME(AllocatorTest, RMW_IMPLEMENTATION), allocator_unique_ptr) {
initialize(true, "allocator_unique_ptr");
size_t counter = 0;
auto callback =
[&counter](std::unique_ptr<std_msgs::msg::UInt32, UInt32Deleter> msg) -> void
{
EXPECT_EQ(counter, msg->data);
counter++;
};
static_assert(
std::is_same<
std_msgs::msg::UInt32,
rclcpp::subscription_traits::has_message_type<decltype(callback)>::type>::value,
"passing a std::unique_ptr of test_msgs::msg::Empty has message type Empty");
auto subscriber = node_->create_subscription<std_msgs::msg::UInt32>(
"allocator_unique_ptr", 10, callback, subscription_options_, msg_memory_strategy_);
TLSFAllocator<std_msgs::msg::UInt32> msg_alloc;
// After test_initialization, global new should only be called from within TLSFAllocator.
test_init = true;
for (uint32_t i = 0; i < iterations; i++) {
auto msg = std::unique_ptr<std_msgs::msg::UInt32, UInt32Deleter>(
std::allocator_traits<UInt32Allocator>::allocate(msg_alloc, 1));
msg->data = i;
publisher_->publish(std::move(msg));
rclcpp::sleep_for(std::chrono::milliseconds(1));
executor_->spin_some();
}
test_init = false;
EXPECT_FALSE(fail);
fail = false;
}
*/
void print_help()
{
printf("--all-tokens: Do not ignore middleware tokens.\n");
printf("--verbose: Report stack traces and allocation statistics.\n");
}
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
// argc and argv are modified by InitGoogleTest
std::vector<std::string> args(argv + 1, argv + argc);
if (std::find(args.begin(), args.end(), "--help") != args.end()) {
print_help();
return 0;
}
verbose = std::find(args.begin(), args.end(), "--verbose") != args.end();
ignore_middleware_tokens = std::find(args.begin(), args.end(), "--all-tokens") == args.end();
return RUN_ALL_TESTS();
}
|
Fix clang thread safety warning (#86)
|
Fix clang thread safety warning (#86)
Signed-off-by: Anas Abou Allaban <[email protected]>
|
C++
|
apache-2.0
|
jacquelinekay/rttest,jacquelinekay/rttest,jacquelinekay/rttest
|
acf9af4fc1cf790a4033724373603ff8f3115a9a
|
include/visionaray/math/detail/matrix4x3.inl
|
include/visionaray/math/detail/matrix4x3.inl
|
// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include "../config.h"
namespace MATH_NAMESPACE
{
//--------------------------------------------------------------------------------------------------
// matrix4x3 members
//
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(
vector<3, T> const& c0,
vector<3, T> const& c1,
vector<3, T> const& c2,
vector<3, T> const& c3
)
: col0(c0)
, col1(c1)
, col2(c2)
, col3(c3)
{
}
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(
T const& m00, T const& m10, T const& m20,
T const& m01, T const& m11, T const& m21,
T const& m02, T const& m12, T const& m22,
T const& m03, T const& m13, T const& m23
)
: col0(m00, m10, m20)
, col1(m01, m11, m21)
, col2(m02, m12, m22)
, col3(m03, m13, m23)
{
}
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(matrix<3, 3, T> const& m, vector<3, T> const& c3)
: col0(m.col0)
, col1(m.col1)
, col2(m.col2)
, col3(c3)
{
}
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(T const data[12])
: col0(&data[0])
, col1(&data[3])
, col2(&data[6])
, col3(&data[9])
{
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>::matrix(matrix<4, 3, U> const& rhs)
: col0(rhs.col0)
, col1(rhs.col1)
, col2(rhs.col2)
, col3(rhs.col3)
{
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>& matrix<4, 3, T>::operator=(matrix<4, 3, U> const& rhs)
{
col0 = rhs.col0;
col1 = rhs.col1;
col2 = rhs.col2;
col3 = rhs.col3;
return *this;
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>::matrix(matrix<3, 3, U> const& rhs)
: col0(rhs.col0)
, col1(rhs.col1)
, col2(rhs.col2)
, col3(vector<3, T>(U(0.0)))
{
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>& matrix<4, 3, T>::operator=(matrix<3, 3, U> const& rhs)
{
col0 = rhs.col0;
col1 = rhs.col1;
col2 = rhs.col2;
col3 = vector<3, T>(U(0.0));
return *this;
}
template <typename T>
MATH_FUNC
inline T* matrix<4, 3, T>::data()
{
return reinterpret_cast<T*>(this);
}
template <typename T>
MATH_FUNC
inline T const* matrix<4, 3, T>::data() const
{
return reinterpret_cast<T const*>(this);
}
template <typename T>
MATH_FUNC
inline vector<3, T>& matrix<4, 3, T>::operator()(size_t col)
{
return *(reinterpret_cast<vector<3, T>*>(this) + col);
}
template <typename T>
MATH_FUNC
inline vector<3, T> const& matrix<4, 3, T>::operator()(size_t col) const
{
return *(reinterpret_cast<vector<3, T> const*>(this) + col);
}
template <typename T>
MATH_FUNC
inline T& matrix<4, 3, T>::operator()(size_t row, size_t col)
{
return (operator()(col))[row];
}
template <typename T>
MATH_FUNC
inline T const& matrix<4, 3, T>::operator()(size_t row, size_t col) const
{
return (operator()(col))[row];
}
//--------------------------------------------------------------------------------------------------
// Basic arithmetic
//
template <typename T>
MATH_FUNC
inline vector<3, T> operator*(matrix<4, 3, T> const& m, vector<4, T> const& v)
{
return vector<3, T>(
m(0, 0) * v.x + m(1, 0) * v.y + m(2, 0) * v.z + m(3, 0) * v.w,
m(0, 1) * v.x + m(1, 1) * v.y + m(2, 1) * v.z + m(3, 1) * v.w,
m(0, 2) * v.x + m(1, 2) * v.y + m(2, 2) * v.z + m(3, 2) * v.w
);
}
template <typename T>
MATH_FUNC
inline vector<4, T> operator*(vector<3, T> const& v, matrix<4, 3, T> const& m)
{
return vector<4, T>(
v.x * m(0, 0) + v.y * m(0, 1) + v.z * m(0, 2),
v.x * m(1, 0) + v.y * m(1, 1) + v.z * m(1, 2),
v.x * m(2, 0) + v.y * m(2, 1) + v.z * m(2, 2),
v.x * m(3, 0) + v.y * m(3, 1) + v.z * m(3, 2)
);
}
//--------------------------------------------------------------------------------------------------
// Comparisons
//
template <typename T>
MATH_FUNC
inline bool operator==(matrix<4, 3, T> const& a, matrix<4, 3, T> const& b)
{
return a(0) == b(0) && a(1) == b(1) && a(2) == b(2) && a(3) == b(3);
}
template <typename T>
MATH_FUNC
inline bool operator!=(matrix<4, 3, T> const& a, matrix<4, 3, T> const& b)
{
return !(a == b);
}
//--------------------------------------------------------------------------------------------------
// Geometric functions
//
// Return top-left 3x3 matrix
template <typename T>
MATH_FUNC
inline matrix<3, 3, T> top_left(matrix<4, 3, T> const& m)
{
matrix<3, 3, T> result;
for (unsigned y = 0; y < 3; ++y)
{
for (unsigned x = 0; x < 3; ++x)
{
result(x, y) = m(y, x);
}
}
return result;
}
//-------------------------------------------------------------------------------------------------
// Misc.
//
template <typename M, typename T>
MATH_FUNC
matrix<4, 3, T> select(M const& m, matrix<4, 3, T> const& u, matrix<4, 3, T> const& v)
{
return matrix<4, 3, T>(
select(m, u.col0, v.col0),
select(m, u.col1, v.col1),
select(m, u.col2, v.col2),
select(m, u.col3, v.col3)
);
}
namespace simd
{
//-------------------------------------------------------------------------------------------------
// SIMD conversions
//
// unpack -------------------------------------------------
template <
typename T,
typename = typename std::enable_if<is_simd_vector<T>::value>::type
>
MATH_FUNC
inline array<matrix<4, 3, element_type_t<T>>, num_elements<T>::value> unpack(matrix<4, 3, T> const& m)
{
using U = element_type_t<T>;
U const* c0x = reinterpret_cast<U const*>(&m.col0.x);
U const* c1x = reinterpret_cast<U const*>(&m.col1.x);
U const* c2x = reinterpret_cast<U const*>(&m.col2.x);
U const* c3x = reinterpret_cast<U const*>(&m.col3.x);
U const* c0y = reinterpret_cast<U const*>(&m.col0.y);
U const* c1y = reinterpret_cast<U const*>(&m.col1.y);
U const* c2y = reinterpret_cast<U const*>(&m.col2.y);
U const* c3y = reinterpret_cast<U const*>(&m.col3.y);
U const* c0z = reinterpret_cast<U const*>(&m.col0.z);
U const* c1z = reinterpret_cast<U const*>(&m.col1.z);
U const* c2z = reinterpret_cast<U const*>(&m.col2.z);
U const* c3z = reinterpret_cast<U const*>(&m.col3.z);
array<matrix<4, 3, U>, num_elements<T>::value> result;
for (int i = 0; i < num_elements<T>::value; ++i)
{
result[i].col0.x = c0x[i];
result[i].col0.y = c0y[i];
result[i].col0.z = c0z[i];
result[i].col1.x = c1x[i];
result[i].col1.y = c1y[i];
result[i].col1.z = c1z[i];
result[i].col2.x = c2x[i];
result[i].col2.y = c2y[i];
result[i].col2.z = c2z[i];
result[i].col3.x = c3x[i];
result[i].col3.y = c3y[i];
result[i].col3.z = c3z[i];
}
return result;
}
} // simd
} // MATH_NAMESPACE
|
// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include "../config.h"
namespace MATH_NAMESPACE
{
//--------------------------------------------------------------------------------------------------
// matrix4x3 members
//
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(
vector<3, T> const& c0,
vector<3, T> const& c1,
vector<3, T> const& c2,
vector<3, T> const& c3
)
: col0(c0)
, col1(c1)
, col2(c2)
, col3(c3)
{
}
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(
T const& m00, T const& m10, T const& m20,
T const& m01, T const& m11, T const& m21,
T const& m02, T const& m12, T const& m22,
T const& m03, T const& m13, T const& m23
)
: col0(m00, m10, m20)
, col1(m01, m11, m21)
, col2(m02, m12, m22)
, col3(m03, m13, m23)
{
}
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(matrix<3, 3, T> const& m, vector<3, T> const& c3)
: col0(m.col0)
, col1(m.col1)
, col2(m.col2)
, col3(c3)
{
}
template <typename T>
MATH_FUNC
inline matrix<4, 3, T>::matrix(T const data[12])
: col0(&data[0])
, col1(&data[3])
, col2(&data[6])
, col3(&data[9])
{
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>::matrix(matrix<4, 3, U> const& rhs)
: col0(rhs.col0)
, col1(rhs.col1)
, col2(rhs.col2)
, col3(rhs.col3)
{
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>& matrix<4, 3, T>::operator=(matrix<4, 3, U> const& rhs)
{
col0 = rhs.col0;
col1 = rhs.col1;
col2 = rhs.col2;
col3 = rhs.col3;
return *this;
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>::matrix(matrix<3, 3, U> const& rhs)
: col0(rhs.col0)
, col1(rhs.col1)
, col2(rhs.col2)
, col3(vector<3, T>(U(0.0)))
{
}
template <typename T>
template <typename U>
MATH_FUNC
inline matrix<4, 3, T>& matrix<4, 3, T>::operator=(matrix<3, 3, U> const& rhs)
{
col0 = rhs.col0;
col1 = rhs.col1;
col2 = rhs.col2;
col3 = vector<3, T>(U(0.0));
return *this;
}
template <typename T>
MATH_FUNC
inline T* matrix<4, 3, T>::data()
{
return reinterpret_cast<T*>(this);
}
template <typename T>
MATH_FUNC
inline T const* matrix<4, 3, T>::data() const
{
return reinterpret_cast<T const*>(this);
}
template <typename T>
MATH_FUNC
inline vector<3, T>& matrix<4, 3, T>::operator()(size_t col)
{
return *(reinterpret_cast<vector<3, T>*>(this) + col);
}
template <typename T>
MATH_FUNC
inline vector<3, T> const& matrix<4, 3, T>::operator()(size_t col) const
{
return *(reinterpret_cast<vector<3, T> const*>(this) + col);
}
template <typename T>
MATH_FUNC
inline T& matrix<4, 3, T>::operator()(size_t row, size_t col)
{
return (operator()(col))[row];
}
template <typename T>
MATH_FUNC
inline T const& matrix<4, 3, T>::operator()(size_t row, size_t col) const
{
return (operator()(col))[row];
}
//--------------------------------------------------------------------------------------------------
// Basic arithmetic
//
template <typename T>
MATH_FUNC
inline vector<3, T> operator*(matrix<4, 3, T> const& m, vector<4, T> const& v)
{
return vector<3, T>(
m(0, 0) * v.x + m(0, 1) * v.y + m(0, 2) * v.z + m(0, 3) * v.w,
m(1, 0) * v.x + m(1, 1) * v.y + m(1, 2) * v.z + m(1, 3) * v.w,
m(2, 0) * v.x + m(2, 1) * v.y + m(2, 2) * v.z + m(2, 3) * v.w
);
}
template <typename T>
MATH_FUNC
inline vector<4, T> operator*(vector<3, T> const& v, matrix<4, 3, T> const& m)
{
return vector<4, T>(
v.x * m(0, 0) + v.y * m(1, 0) + v.z * m(2, 0),
v.x * m(0, 1) + v.y * m(1, 1) + v.z * m(2, 1),
v.x * m(0, 2) + v.y * m(1, 2) + v.z * m(2, 2),
v.x * m(0, 3) + v.y * m(1, 3) + v.z * m(2, 3)
);
}
//--------------------------------------------------------------------------------------------------
// Comparisons
//
template <typename T>
MATH_FUNC
inline bool operator==(matrix<4, 3, T> const& a, matrix<4, 3, T> const& b)
{
return a(0) == b(0) && a(1) == b(1) && a(2) == b(2) && a(3) == b(3);
}
template <typename T>
MATH_FUNC
inline bool operator!=(matrix<4, 3, T> const& a, matrix<4, 3, T> const& b)
{
return !(a == b);
}
//--------------------------------------------------------------------------------------------------
// Geometric functions
//
// Return top-left 3x3 matrix
template <typename T>
MATH_FUNC
inline matrix<3, 3, T> top_left(matrix<4, 3, T> const& m)
{
matrix<3, 3, T> result;
for (unsigned y = 0; y < 3; ++y)
{
for (unsigned x = 0; x < 3; ++x)
{
result(x, y) = m(y, x);
}
}
return result;
}
//-------------------------------------------------------------------------------------------------
// Misc.
//
template <typename M, typename T>
MATH_FUNC
matrix<4, 3, T> select(M const& m, matrix<4, 3, T> const& u, matrix<4, 3, T> const& v)
{
return matrix<4, 3, T>(
select(m, u.col0, v.col0),
select(m, u.col1, v.col1),
select(m, u.col2, v.col2),
select(m, u.col3, v.col3)
);
}
namespace simd
{
//-------------------------------------------------------------------------------------------------
// SIMD conversions
//
// unpack -------------------------------------------------
template <
typename T,
typename = typename std::enable_if<is_simd_vector<T>::value>::type
>
MATH_FUNC
inline array<matrix<4, 3, element_type_t<T>>, num_elements<T>::value> unpack(matrix<4, 3, T> const& m)
{
using U = element_type_t<T>;
U const* c0x = reinterpret_cast<U const*>(&m.col0.x);
U const* c1x = reinterpret_cast<U const*>(&m.col1.x);
U const* c2x = reinterpret_cast<U const*>(&m.col2.x);
U const* c3x = reinterpret_cast<U const*>(&m.col3.x);
U const* c0y = reinterpret_cast<U const*>(&m.col0.y);
U const* c1y = reinterpret_cast<U const*>(&m.col1.y);
U const* c2y = reinterpret_cast<U const*>(&m.col2.y);
U const* c3y = reinterpret_cast<U const*>(&m.col3.y);
U const* c0z = reinterpret_cast<U const*>(&m.col0.z);
U const* c1z = reinterpret_cast<U const*>(&m.col1.z);
U const* c2z = reinterpret_cast<U const*>(&m.col2.z);
U const* c3z = reinterpret_cast<U const*>(&m.col3.z);
array<matrix<4, 3, U>, num_elements<T>::value> result;
for (int i = 0; i < num_elements<T>::value; ++i)
{
result[i].col0.x = c0x[i];
result[i].col0.y = c0y[i];
result[i].col0.z = c0z[i];
result[i].col1.x = c1x[i];
result[i].col1.y = c1y[i];
result[i].col1.z = c1z[i];
result[i].col2.x = c2x[i];
result[i].col2.y = c2y[i];
result[i].col2.z = c2z[i];
result[i].col3.x = c3x[i];
result[i].col3.y = c3y[i];
result[i].col3.z = c3z[i];
}
return result;
}
} // simd
} // MATH_NAMESPACE
|
Fix mat4x3 / vector multiplication
|
Fix mat4x3 / vector multiplication
|
C++
|
mit
|
szellmann/visionaray,szellmann/visionaray
|
b74c90a5f8f48864ccdb03923ac01f4f26117254
|
Berlin/modules/Drawing/PostScript/DrawingKit.cc
|
Berlin/modules/Drawing/PostScript/DrawingKit.cc
|
/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <[email protected]>
* Copyright (C) 2002 Nick Lewycky <[email protected]>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Fresco/config.hh>
#include <Fresco/Traversal.hh>
#include <Fresco/Transform.hh>
#include <Fresco/Region.hh>
#include <Fresco/Raster.hh>
#include <Berlin/ImplVar.hh>
#include <Berlin/TransformImpl.hh>
#include <Berlin/RegionImpl.hh>
#include <Berlin/Console.hh>
#include "DrawingKit.hh"
#include <sstream>
#include <iostream>
#include <fstream>
using namespace Prague;
using namespace Fresco;
PostScript::DrawingKit::DrawingKit(const std::string &id, const Fresco::Kit::PropertySeq &p)
: KitImpl(id, p),
_os(new std::filebuf())
{
_os.precision(5);
}
PostScript::DrawingKit::~DrawingKit()
{
}
KitImpl *PostScript::DrawingKit::clone(const Fresco::Kit::PropertySeq &p)
{
DrawingKit *kit = new DrawingKit(repo_id(), p);
kit->init();
return kit;
}
void PostScript::DrawingKit::start_traversal(Traversal_ptr traversal)
{
_os.clear();
static_cast<std::filebuf *>(_os.rdbuf())->open("berlin-output.ps", std::ios::out);
Region_var allocation = traversal->current_allocation();
Transform_var transformation = traversal->current_transformation();
RegionImpl region(allocation, transformation);
// FIXME: figure out what is wrong with the resolution,
// the problems seems to be in the coordinate system used,
// not PS...
// -stefan
double xfactor = resolution(xaxis);
double yfactor = resolution(yaxis);
_os << "%!PS-Adobe-3.0 EPSF-3.0" << std::endl;
_os << "%%BoundingBox: "
<< region.lower.x*resolution(xaxis)*xfactor << ' '
<< (region.lower.y - region.upper.y)*resolution(yaxis)*yfactor << ' '
<< (region.upper.x - region.lower.x)*resolution(xaxis)*xfactor << ' '
<< region.lower.y*resolution(yaxis)*yfactor << std::endl;
_os << "%%LanguageLevel: 2" << std::endl;
_os << "%%Creator: Fresco" << std::endl;
_os << "/Times-Roman findfont 12 scalefont setfont" << std::endl;
_os << "0 0 0 setrgbcolor" << std::endl;
_os << resolution(xaxis) << " " << -resolution(yaxis) << " scale" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::finish_traversal()
{
_os << "%%EOF" << std::endl;
static_cast<std::filebuf *>(_os.rdbuf())->close();
}
Fresco::Unistring *PostScript::DrawingKit::font_family() { return new Unistring(Unicode::to_CORBA(Babylon::String("Times Roman")));}
Fresco::Unistring *PostScript::DrawingKit::font_subfamily() { return new Unistring();}
Fresco::Unistring *PostScript::DrawingKit::font_fullname() { return new Unistring(Unicode::to_CORBA(Babylon::String("Times Roman")));}
Fresco::Unistring *PostScript::DrawingKit::font_style() { return new Unistring(Unicode::to_CORBA(Babylon::String("Regular")));}
Fresco::DrawingKit::FontMetrics PostScript::DrawingKit::font_metrics() { return Fresco::DrawingKit::FontMetrics();}
Fresco::DrawingKit::GlyphMetrics PostScript::DrawingKit::glyph_metrics(Fresco::Unichar) { return Fresco::DrawingKit::GlyphMetrics();}
CORBA::Any *PostScript::DrawingKit::get_font_attribute(const Fresco::Unistring &) { return new CORBA::Any();}
void PostScript::DrawingKit::set_transformation(Transform_ptr t)
{
if (CORBA::is_nil(t)) _tr->load_identity();
else _tr = Transform::_duplicate(t);
//set_clipping(_cl);
}
void PostScript::DrawingKit::set_clipping(Region_ptr r)
{
#if 0
_os << "%set_clipping" << std::endl;
_cl = Region::_duplicate(r);
if (CORBA::is_nil(_cl))
{
_os << "initclip" << std::endl;
_os << std::endl; // disallowed in EPS
} else {
Vertex lower, upper;
_cl->bounds(lower, upper);
//_tr->transform_vertex(lower);
//_tr->transform_vertex(upper);
_os << lower.x << " " << lower.y << " " << upper.x - lower.x << " "
<< upper.x - lower.x << " rectclip" << std::endl;
}
_os << std::endl;
#endif
}
void PostScript::DrawingKit::set_foreground(const Color &c)
{
_fg = c;
_os << "%set_foreground" << std::endl;
_os << (_fg.red*_lt.red) << ' ' << (_fg.green*_lt.green) << ' ' << (_fg.blue*_lt.blue) << " setrgbcolor" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_lighting(const Color &c)
{
_lt = c;
_os << "%set_lighting" << std::endl;
_os << (_fg.red*_lt.red) << ' ' << (_fg.green*_lt.green) << ' ' << (_fg.blue*_lt.blue) << " setrgbcolor" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_point_size(Coord s)
{
_ps = s;
}
void PostScript::DrawingKit::set_line_width(Coord w)
{
_lw = w;
_os << "%set_line_width" << std::endl;
_os << _lw*resolution(xaxis) << " setlinewidth" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_line_endstyle(Fresco::DrawingKit::Endstyle style)
{
_es = style;
switch (_es) {
case Fresco::DrawingKit::butt: _os << 0; break; //.< Butt
case Fresco::DrawingKit::round: _os << 1; break; //.< Round
case Fresco::DrawingKit::cap: _os << 2; break; //.< Square
}
_os << " setlinecap" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_surface_fillstyle(Fresco::DrawingKit::Fillstyle style)
{
_fs = style;
}
void PostScript::DrawingKit::set_texture(Raster_ptr t)
{
}
void PostScript::DrawingKit::draw_path(const Path &path)
{
_os << "%draw_path" << std::endl;
_os << "newpath" << std::endl;
Vertex v = path.nodes[path.nodes.length()-1];
vertex(v, " moveto");
for (unsigned long i = 1; i < path.nodes.length(); i++) {
v = path.nodes[i];
vertex(v, " lineto");
}
_os << "closepath";
if (_fs == Fresco::DrawingKit::solid)
_os << " fill" << std::endl;
else
_os << " stroke" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::draw_rectangle(const Vertex &lower, const Vertex &upper)
{
_os << "%draw_rectangle" << std::endl;
_os << "newpath" << std::endl;
Vertex v;
v.x = lower.x; v.y = lower.y; v.z = 0;
vertex(v, " moveto");
v.x = lower.x; v.y = upper.y; v.z = 0;
vertex(v, " lineto");
v.x = upper.x; v.y = upper.y; v.z = 0;
vertex(v, " lineto");
v.x = upper.x; v.y = lower.y; v.z = 0;
vertex(v, " lineto");
v.x = lower.x; v.y = lower.y; v.z = 0;
vertex(v, " lineto");
_os << "closepath";
if (_fs == Fresco::DrawingKit::solid)
_os << " fill" << std::endl;
else
_os << " stroke" << std::endl;
_os << std::endl;
}
inline void PostScript::DrawingKit::vertex(const Vertex &x, char *c) {
Vertex v = x;
_tr->transform_vertex(v);
_os << v.x*resolution(xaxis) << ' ' << v.y*resolution(yaxis) << c << std::endl;
}
void PostScript::DrawingKit::draw_quadric(const Fresco::DrawingKit::Quadric, Fresco::Coord, Fresco::Coord)
{
}
void PostScript::DrawingKit::draw_ellipse(const Vertex &lower, const Vertex &upper)
{
}
void PostScript::DrawingKit::draw_image(Raster_ptr raster)
{
Raster_var r = Raster::_duplicate(raster);
_os << "%draw_image" << std::endl;
Fresco::Transform::Matrix matrix;
_tr->store_matrix(matrix);
Vertex o; _tr->transform_vertex(o);
o.x *= (matrix[0][0]+matrix[1][0]) * resolution(xaxis);
o.y *= (matrix[0][1]+matrix[1][1]) * resolution(yaxis);
_os << r->header().width << " " << r->header().height << " "
<< r->header().depth << std::endl;
_os << "[ " << matrix[0][0]*resolution(xaxis)
<< " " << matrix[0][1]*resolution(xaxis)
<< " " << matrix[1][0]*resolution(yaxis)
<< " " << matrix[1][1]*resolution(yaxis)
<< " " << 0-o.x*resolution(xaxis) << " "
<< 0-o.y*resolution(yaxis) << " ]" << std::endl;
_os << "{<" << std::endl;
Raster::Index i;
for (i.y = 0; i.y < r->header().height; i.y++) {
for (i.x = 0; i.x < r->header().width; i.x++) {
Color c;
char color[7];
r->store_pixel(i, c);
sprintf(color, "%02x%02x%02x", (int)(c.red*255), (int)(c.green*255), (int)(c.blue*255));
_os << color;
}
_os << std::endl;
}
_os << ">}" << std::endl;
_os << "false 3 colorimage" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_font_size(CORBA::ULong s)
{
_os << "%set_font_size" << std::endl;
_os << s << " scalefont" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_font_weight(CORBA::ULong w) {}
void PostScript::DrawingKit::set_font_family(const Unistring &f) {}
void PostScript::DrawingKit::set_font_subfamily(const Unistring &sf) {}
void PostScript::DrawingKit::set_font_fullname(const Unistring &fn) {}
void PostScript::DrawingKit::set_font_style(const Unistring &s) {}
void PostScript::DrawingKit::set_font_attribute(const NVPair & nvp) {}
void PostScript::DrawingKit::allocate_text(const Unistring &s, Graphic::Requisition &req) {}
void PostScript::DrawingKit::draw_text(const Unistring &us) {}
void PostScript::DrawingKit::allocate_char(Unichar c, Graphic::Requisition &req)
{
int width = 10;
int height = 20;
req.x.natural = req.x.minimum = req.x.maximum = width*10.;
req.x.defined = true;
req.x.align = 0.;
req.y.natural = req.y.minimum = req.y.maximum = height*10.;
req.y.defined = true;
req.y.align = 1.;
}
void PostScript::DrawingKit::draw_char(Unichar c)
{
_os << "%draw_char" << std::endl;
_os << "gsave" << std::endl;
Fresco::Transform::Matrix matrix;
_tr->store_matrix(matrix);
_os << matrix[0][3]*resolution(xaxis) << " " << matrix[1][3]*resolution(yaxis) << " moveto" << std::endl;
_os << "[ " << matrix[0][0] << " " << 0.-matrix[0][1] << " " << matrix[1][0] << " " << 0.-matrix[1][1] << " 0 0 ] concat" << std::endl;
_os << 1./resolution(xaxis) << " " << 1./resolution(yaxis) << " scale" << std::endl;
char x[2];
sprintf(x, "%02x", (int)c);
_os << "<" << x << "> show" << std::endl;
_os << "grestore" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::copy_drawable(Drawable_ptr d, PixelCoord x, PixelCoord y, PixelCoord w, PixelCoord h) {}
extern "C" KitImpl *load()
{
static std::string properties[] = {"implementation", "DrawingKit"};
return create_kit<PostScript::DrawingKit> ("IDL:fresco.org/Fresco/DrawingKit:1.0", properties, 2);
}
|
/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <[email protected]>
* Copyright (C) 2002 Nick Lewycky <[email protected]>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Fresco/config.hh>
#include <Fresco/Traversal.hh>
#include <Fresco/Transform.hh>
#include <Fresco/Region.hh>
#include <Fresco/Raster.hh>
#include <Berlin/ImplVar.hh>
#include <Berlin/TransformImpl.hh>
#include <Berlin/RegionImpl.hh>
#include <Berlin/Console.hh>
#include "DrawingKit.hh"
#include <sstream>
#include <iostream>
#include <fstream>
using namespace Prague;
using namespace Fresco;
PostScript::DrawingKit::DrawingKit(const std::string &id, const Fresco::Kit::PropertySeq &p)
: KitImpl(id, p),
_os(new std::filebuf())
{
_os.precision(5);
}
PostScript::DrawingKit::~DrawingKit()
{
}
KitImpl *PostScript::DrawingKit::clone(const Fresco::Kit::PropertySeq &p)
{
DrawingKit *kit = new DrawingKit(repo_id(), p);
kit->init();
return kit;
}
void PostScript::DrawingKit::start_traversal(Traversal_ptr traversal)
{
_os.clear();
static_cast<std::filebuf *>(_os.rdbuf())->open("berlin-output.ps", std::ios::out);
Region_var allocation = traversal->current_allocation();
Transform_var transformation = traversal->current_transformation();
RegionImpl region(allocation, transformation);
// FIXME: figure out what is wrong with the resolution,
// the problems seems to be in the coordinate system used,
// not PS...
// -stefan
double xfactor = resolution(xaxis);
double yfactor = resolution(yaxis);
_os << "%!PS-Adobe-3.0 EPSF-3.0" << std::endl;
_os << "%%BoundingBox: "
<< region.lower.x*resolution(xaxis)*xfactor << ' '
<< (region.lower.y - region.upper.y)*resolution(yaxis)*yfactor << ' '
<< (region.upper.x - region.lower.x)*resolution(xaxis)*xfactor << ' '
<< region.lower.y*resolution(yaxis)*yfactor << std::endl;
_os << "%%LanguageLevel: 2" << std::endl;
_os << "%%Creator: Fresco" << std::endl;
_os << "/Times-Roman findfont 12 scalefont setfont" << std::endl;
_os << "0 0 0 setrgbcolor" << std::endl;
_os << resolution(xaxis) << " " << -resolution(yaxis) << " scale" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::finish_traversal()
{
_os << "%%EOF" << std::endl;
static_cast<std::filebuf *>(_os.rdbuf())->close();
}
Fresco::Unistring *PostScript::DrawingKit::font_family() { return new Unistring(Unicode::to_CORBA(Babylon::String("Times Roman")));}
Fresco::Unistring *PostScript::DrawingKit::font_subfamily() { return new Unistring();}
Fresco::Unistring *PostScript::DrawingKit::font_fullname() { return new Unistring(Unicode::to_CORBA(Babylon::String("Times Roman")));}
Fresco::Unistring *PostScript::DrawingKit::font_style() { return new Unistring(Unicode::to_CORBA(Babylon::String("Regular")));}
Fresco::DrawingKit::FontMetrics PostScript::DrawingKit::font_metrics() { return Fresco::DrawingKit::FontMetrics();}
Fresco::DrawingKit::GlyphMetrics PostScript::DrawingKit::glyph_metrics(Fresco::Unichar) { return Fresco::DrawingKit::GlyphMetrics();}
CORBA::Any *PostScript::DrawingKit::get_font_attribute(const Fresco::Unistring &) { return new CORBA::Any();}
void PostScript::DrawingKit::set_transformation(Transform_ptr t)
{
if (CORBA::is_nil(t)) _tr->load_identity();
else _tr = Transform::_duplicate(t);
//set_clipping(_cl);
}
void PostScript::DrawingKit::set_clipping(Region_ptr r)
{
#if 0
_os << "%set_clipping" << std::endl;
_cl = Region::_duplicate(r);
if (CORBA::is_nil(_cl))
{
_os << "initclip" << std::endl;
_os << std::endl; // disallowed in EPS
} else {
Vertex lower, upper;
_cl->bounds(lower, upper);
//_tr->transform_vertex(lower);
//_tr->transform_vertex(upper);
_os << lower.x << " " << lower.y << " " << upper.x - lower.x << " "
<< upper.x - lower.x << " rectclip" << std::endl;
}
_os << std::endl;
#endif
}
void PostScript::DrawingKit::set_foreground(const Color &c)
{
_fg = c;
_os << "%set_foreground" << std::endl;
_os << (_fg.red*_lt.red) << ' ' << (_fg.green*_lt.green) << ' ' << (_fg.blue*_lt.blue) << " setrgbcolor" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_lighting(const Color &c)
{
_lt = c;
_os << "%set_lighting" << std::endl;
_os << (_fg.red*_lt.red) << ' ' << (_fg.green*_lt.green) << ' ' << (_fg.blue*_lt.blue) << " setrgbcolor" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_point_size(Coord s)
{
_ps = s;
}
void PostScript::DrawingKit::set_line_width(Coord w)
{
_lw = w;
_os << "%set_line_width" << std::endl;
_os << _lw*resolution(xaxis) << " setlinewidth" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_line_endstyle(Fresco::DrawingKit::Endstyle style)
{
_es = style;
switch (_es) {
case Fresco::DrawingKit::butt: _os << 0; break; //.< Butt
case Fresco::DrawingKit::round: _os << 1; break; //.< Round
case Fresco::DrawingKit::cap: _os << 2; break; //.< Square
}
_os << " setlinecap" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_surface_fillstyle(Fresco::DrawingKit::Fillstyle style)
{
_fs = style;
}
void PostScript::DrawingKit::set_texture(Raster_ptr t)
{
}
void PostScript::DrawingKit::draw_path(const Path &path)
{
_os << "%draw_path" << std::endl;
_os << "newpath" << std::endl;
Vertex v = path.nodes[path.nodes.length()-1];
vertex(v, " moveto");
for (unsigned long i = 1; i < path.nodes.length(); i++) {
v = path.nodes[i];
vertex(v, " lineto");
}
_os << "closepath";
if (_fs == Fresco::DrawingKit::solid)
_os << " fill" << std::endl;
else
_os << " stroke" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::draw_rectangle(const Vertex &lower, const Vertex &upper)
{
_os << "%draw_rectangle" << std::endl;
_os << "newpath" << std::endl;
Vertex v;
v.x = lower.x; v.y = lower.y; v.z = 0;
vertex(v, " moveto");
v.x = lower.x; v.y = upper.y; v.z = 0;
vertex(v, " lineto");
v.x = upper.x; v.y = upper.y; v.z = 0;
vertex(v, " lineto");
v.x = upper.x; v.y = lower.y; v.z = 0;
vertex(v, " lineto");
v.x = lower.x; v.y = lower.y; v.z = 0;
vertex(v, " lineto");
_os << "closepath";
if (_fs == Fresco::DrawingKit::solid)
_os << " fill" << std::endl;
else
_os << " stroke" << std::endl;
_os << std::endl;
}
inline void PostScript::DrawingKit::vertex(const Vertex &x, char *c) {
Vertex v = x;
_tr->transform_vertex(v);
_os << v.x*resolution(xaxis) << ' ' << v.y*resolution(yaxis) << c << std::endl;
}
void PostScript::DrawingKit::draw_quadric(const Fresco::DrawingKit::Quadric, Fresco::Coord, Fresco::Coord)
{
}
void PostScript::DrawingKit::draw_ellipse(const Vertex &lower, const Vertex &upper)
{
}
void PostScript::DrawingKit::draw_image(Raster_ptr raster)
{
Raster_var r = Raster::_duplicate(raster);
_os << "%draw_image" << std::endl;
Fresco::Transform::Matrix matrix;
_tr->store_matrix(matrix);
Vertex o; _tr->transform_vertex(o);
o.x *= (matrix[0][0]+matrix[1][0]) * resolution(xaxis);
o.y *= (matrix[0][1]+matrix[1][1]) * resolution(yaxis);
_os << r->header().width << " " << r->header().height << " "
<< r->header().depth << std::endl;
_os << "[ " << matrix[0][0]*resolution(xaxis)
<< " " << matrix[0][1]*resolution(xaxis)
<< " " << matrix[1][0]*resolution(yaxis)
<< " " << matrix[1][1]*resolution(yaxis)
<< " " << 0-o.x*resolution(xaxis) << " "
<< 0-o.y*resolution(yaxis) << " ]" << std::endl;
_os << "{<" << std::endl;
Raster::Index i;
for (i.y = 0; i.y < r->header().height; i.y++) {
for (i.x = 0; i.x < r->header().width; i.x++) {
Color c;
char color[7];
r->store_pixel(i, c);
sprintf(color, "%02x%02x%02x", (int)(c.red*255), (int)(c.green*255), (int)(c.blue*255));
_os << color;
}
_os << std::endl;
}
_os << ">}" << std::endl;
_os << "false 3 colorimage" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_font_size(CORBA::ULong s)
{
_os << "%set_font_size" << std::endl;
_os << s << " scalefont" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::set_font_weight(CORBA::ULong w) {}
void PostScript::DrawingKit::set_font_family(const Unistring &f) {}
void PostScript::DrawingKit::set_font_subfamily(const Unistring &sf) {}
void PostScript::DrawingKit::set_font_fullname(const Unistring &fn) {}
void PostScript::DrawingKit::set_font_style(const Unistring &s) {}
void PostScript::DrawingKit::set_font_attribute(const NVPair & nvp) {}
void PostScript::DrawingKit::allocate_text(const Unistring &s, Graphic::Requisition &req) {}
void PostScript::DrawingKit::draw_text(const Unistring &us) {}
void PostScript::DrawingKit::allocate_char(Unichar c, Graphic::Requisition &req)
{
int width = 10;
int height = 20;
req.x.natural = req.x.minimum = req.x.maximum = width*10.;
req.x.defined = true;
req.x.align = 0.;
req.y.natural = req.y.minimum = req.y.maximum = height*10.;
req.y.defined = true;
req.y.align = 1.;
}
void PostScript::DrawingKit::draw_char(Unichar c)
{
_os << "%draw_char" << std::endl;
_os << "gsave" << std::endl;
Fresco::Transform::Matrix matrix;
_tr->store_matrix(matrix);
_os << matrix[0][3]*resolution(xaxis) << " " << matrix[1][3]*resolution(yaxis) << " moveto" << std::endl;
_os << "[ " << matrix[0][0] << " " << 0.-matrix[0][1] << " " << matrix[1][0] << " " << 0.-matrix[1][1] << " 0 0 ] concat" << std::endl;
_os << 1./resolution(xaxis) << " " << 1./resolution(yaxis) << " scale" << std::endl;
char x[2];
sprintf(x, "%02x", (int)c);
_os << "<" << x << "> show" << std::endl;
_os << "grestore" << std::endl;
_os << std::endl;
}
void PostScript::DrawingKit::copy_drawable(Drawable_ptr d, PixelCoord x, PixelCoord y, PixelCoord w, PixelCoord h) {}
extern "C" KitImpl *load()
{
static std::string properties[] = {"implementation", "PSDrawingKit"};
return create_kit<PostScript::DrawingKit> ("IDL:fresco.org/Fresco/DrawingKit:1.0", properties, 2);
}
|
Fix wrong property in PSDK.
|
Fix wrong property in PSDK.
|
C++
|
lgpl-2.1
|
stefanseefeld/fresco,stefanseefeld/fresco,stefanseefeld/fresco,stefanseefeld/fresco,stefanseefeld/fresco
|
a05e58166f4a92cb25f5283845ef261b272fc489
|
tutorials/proof/ProofTests.C
|
tutorials/proof/ProofTests.C
|
#define ProofTests_cxx
//////////////////////////////////////////////////////////
//
// Auxilliary TSelector used to test PROOF functionality
//
//////////////////////////////////////////////////////////
#include "ProofTests.h"
#include <TEnv.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TMath.h>
#include <TString.h>
#include <TSystem.h>
#include <TParameter.h>
//_____________________________________________________________________________
ProofTests::ProofTests()
{
// Constructor
fTestType = 0;
fStat = 0;
}
//_____________________________________________________________________________
ProofTests::~ProofTests()
{
// Destructor
}
//_____________________________________________________________________________
void ProofTests::ParseInput()
{
// This function sets some control member variables based on the input list
// content. Called by Begin and SlaveBegin.
// Determine the test type
TNamed *ntype = dynamic_cast<TNamed*>(fInput->FindObject("ProofTests_Type"));
if (ntype) {
if (!strcmp(ntype->GetTitle(), "InputData")) {
fTestType = 0;
} else if (!strcmp(ntype->GetTitle(), "PackTest1")) {
fTestType = 1;
} else if (!strcmp(ntype->GetTitle(), "PackTest2")) {
fTestType = 2;
} else {
Warning("ParseInput", "unknown type: '%s'", ntype->GetTitle());
}
}
Info("ParseInput", "test type: %d (from '%s')", fTestType, ntype ? ntype->GetTitle() : "undef");
}
//_____________________________________________________________________________
void ProofTests::Begin(TTree * /*tree*/)
{
// The Begin() function is called at the start of the query.
// When running with PROOF Begin() is only called on the client.
// The tree argument is deprecated (on PROOF 0 is passed).
}
//_____________________________________________________________________________
void ProofTests::SlaveBegin(TTree * /*tree*/)
{
// The SlaveBegin() function is called after the Begin() function.
// When running with PROOF SlaveBegin() is called on each slave server.
// The tree argument is deprecated (on PROOF 0 is passed).
TString option = GetOption();
// Fill relevant members
ParseInput();
// Output histo
fStat = new TH1I("TestStat", "Test results", 20, .5, 20.5);
fOutput->Add(fStat);
// We were started
fStat->Fill(1.);
// Depends on the test
if (fTestType == 0) {
// Retrieve objects from the input list and copy them to the output
// H1
TList *h1list = dynamic_cast<TList*>(fInput->FindObject("h1list"));
if (h1list) {
// Retrieve objects from the input list and copy them to the output
TH1F *h1 = dynamic_cast<TH1F*>(h1list->FindObject("h1data"));
if (h1) {
TParameter<Double_t> *h1avg = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1avg"));
TParameter<Double_t> *h1rms = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1rms"));
if (h1avg && h1rms) {
if (TMath::Abs(h1avg->GetVal() - h1->GetMean()) < 0.0001) {
if (TMath::Abs(h1rms->GetVal() - h1->GetRMS()) < 0.0001) {
fStat->Fill(2.);
}
}
} else {
Info("SlaveBegin", "%d: info 'h1avg' or 'h1rms' not found!", fTestType);
}
} else {
Info("SlaveBegin", "%d: input histo 'h1data' not found!", fTestType);
}
} else {
Info("SlaveBegin", "%d: input list 'h1list' not found!", fTestType);
}
// H2
TList *h2list = dynamic_cast<TList*>(fInput->FindObject("h2list"));
if (h2list) {
// Retrieve objects from the input list and copy them to the output
TH1F *h2 = dynamic_cast<TH1F*>(h2list->FindObject("h2data"));
if (h2) {
TParameter<Double_t> *h2avg = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2avg"));
TParameter<Double_t> *h2rms = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2rms"));
if (h2avg && h2rms) {
if (TMath::Abs(h2avg->GetVal() - h2->GetMean()) < 0.0001) {
if (TMath::Abs(h2rms->GetVal() - h2->GetRMS()) < 0.0001) {
fStat->Fill(3.);
}
}
} else {
Info("SlaveBegin", "%d: info 'h2avg' or 'h2rms' not found!", fTestType);
}
} else {
Info("SlaveBegin", "%d: input histo 'h2data' not found!", fTestType);
}
} else {
Info("SlaveBegin", "%d: input list 'h2list' not found!", fTestType);
}
TNamed *iob = dynamic_cast<TNamed*>(fInput->FindObject("InputObject"));
if (iob) {
fStat->Fill(4.);
} else {
Info("SlaveBegin", "%d: input histo 'InputObject' not found!", fTestType);
}
} else if (fTestType == 1) {
// We should find in the input list the name of a test variable which should exist
// at this point in the gEnv table
TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
if (nm) {
if (gEnv->Lookup(nm->GetTitle())) fStat->Fill(2.);
} else {
Info("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
}
} else if (fTestType == 2) {
// We should find in the input list the list of names of test variables which should exist
// at this point in the gEnv table
TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
if (nm) {
TString nms(nm->GetTitle()), nam;
Int_t from = 0;
while (nms.Tokenize(nam, from, ",")) {
if (gEnv->Lookup(nam)) {
Double_t xx = gEnv->GetValue(nam, -1.);
if (xx > 1.) fStat->Fill(xx);
}
}
} else {
Info("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
}
}
}
//_____________________________________________________________________________
Bool_t ProofTests::Process(Long64_t)
{
// The Process() function is called for each entry in the tree (or possibly
// keyed object in the case of PROOF) to be processed. The entry argument
// specifies which entry in the currently loaded tree is to be processed.
// It can be passed to either ProofTests::GetEntry() or TBranch::GetEntry()
// to read either all or the required parts of the data. When processing
// keyed objects with PROOF, the object is already loaded and is available
// via the fObject pointer.
//
// This function should contain the "body" of the analysis. It can contain
// simple or elaborate selection criteria, run algorithms on the data
// of the event and typically fill histograms.
//
// The processing can be stopped by calling Abort().
//
// Use fStatus to set the return value of TTree::Process().
//
// The return value is currently not used.
return kTRUE;
}
//_____________________________________________________________________________
void ProofTests::SlaveTerminate()
{
// The SlaveTerminate() function is called after all entries or objects
// have been processed. When running with PROOF SlaveTerminate() is called
// on each slave server.
}
//_____________________________________________________________________________
void ProofTests::Terminate()
{
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
}
|
#define ProofTests_cxx
//////////////////////////////////////////////////////////
//
// Auxilliary TSelector used to test PROOF functionality
//
//////////////////////////////////////////////////////////
#include "ProofTests.h"
#include <TEnv.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TMath.h>
#include <TString.h>
#include <TSystem.h>
#include <TParameter.h>
//_____________________________________________________________________________
ProofTests::ProofTests()
{
// Constructor
fTestType = 0;
fStat = 0;
}
//_____________________________________________________________________________
ProofTests::~ProofTests()
{
// Destructor
}
//_____________________________________________________________________________
void ProofTests::ParseInput()
{
// This function sets some control member variables based on the input list
// content. Called by Begin and SlaveBegin.
// Determine the test type
TNamed *ntype = dynamic_cast<TNamed*>(fInput->FindObject("ProofTests_Type"));
if (ntype) {
if (!strcmp(ntype->GetTitle(), "InputData")) {
fTestType = 0;
} else if (!strcmp(ntype->GetTitle(), "PackTest1")) {
fTestType = 1;
} else if (!strcmp(ntype->GetTitle(), "PackTest2")) {
fTestType = 2;
} else {
Warning("ParseInput", "unknown type: '%s'", ntype->GetTitle());
}
}
Info("ParseInput", "test type: %d (from '%s')", fTestType, ntype ? ntype->GetTitle() : "undef");
}
//_____________________________________________________________________________
void ProofTests::Begin(TTree * /*tree*/)
{
// The Begin() function is called at the start of the query.
// When running with PROOF Begin() is only called on the client.
// The tree argument is deprecated (on PROOF 0 is passed).
}
//_____________________________________________________________________________
void ProofTests::SlaveBegin(TTree * /*tree*/)
{
// The SlaveBegin() function is called after the Begin() function.
// When running with PROOF SlaveBegin() is called on each slave server.
// The tree argument is deprecated (on PROOF 0 is passed).
TString option = GetOption();
// Fill relevant members
ParseInput();
// Output histo
fStat = new TH1I("TestStat", "Test results", 20, .5, 20.5);
fOutput->Add(fStat);
// We were started
fStat->Fill(1.);
// Depends on the test
if (fTestType == 0) {
// Retrieve objects from the input list and copy them to the output
// H1
TList *h1list = dynamic_cast<TList*>(fInput->FindObject("h1list"));
if (h1list) {
// Retrieve objects from the input list and copy them to the output
TH1F *h1 = dynamic_cast<TH1F*>(h1list->FindObject("h1data"));
if (h1) {
TParameter<Double_t> *h1avg = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1avg"));
TParameter<Double_t> *h1rms = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1rms"));
if (h1avg && h1rms) {
if (TMath::Abs(h1avg->GetVal() - h1->GetMean()) < 0.0001) {
if (TMath::Abs(h1rms->GetVal() - h1->GetRMS()) < 0.0001) {
fStat->Fill(2.);
}
}
} else {
Warning("SlaveBegin", "%d: info 'h1avg' or 'h1rms' not found!", fTestType);
}
} else {
Warning("SlaveBegin", "%d: input histo 'h1data' not found!", fTestType);
}
} else {
Warning("SlaveBegin", "%d: input list 'h1list' not found!", fTestType);
}
// H2
TList *h2list = dynamic_cast<TList*>(fInput->FindObject("h2list"));
if (h2list) {
// Retrieve objects from the input list and copy them to the output
TH1F *h2 = dynamic_cast<TH1F*>(h2list->FindObject("h2data"));
if (h2) {
TParameter<Double_t> *h2avg = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2avg"));
TParameter<Double_t> *h2rms = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2rms"));
if (h2avg && h2rms) {
if (TMath::Abs(h2avg->GetVal() - h2->GetMean()) < 0.0001) {
if (TMath::Abs(h2rms->GetVal() - h2->GetRMS()) < 0.0001) {
fStat->Fill(3.);
}
}
} else {
Warning("SlaveBegin", "%d: info 'h2avg' or 'h2rms' not found!", fTestType);
}
} else {
Warning("SlaveBegin", "%d: input histo 'h2data' not found!", fTestType);
}
} else {
Warning("SlaveBegin", "%d: input list 'h2list' not found!", fTestType);
}
TNamed *iob = dynamic_cast<TNamed*>(fInput->FindObject("InputObject"));
if (iob) {
fStat->Fill(4.);
} else {
Warning("SlaveBegin", "%d: input histo 'InputObject' not found!", fTestType);
}
} else if (fTestType == 1) {
// We should find in the input list the name of a test variable which should exist
// at this point in the gEnv table
TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
if (nm) {
if (gEnv->Lookup(nm->GetTitle())) fStat->Fill(2.);
} else {
Warning("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
}
} else if (fTestType == 2) {
// We should find in the input list the list of names of test variables which should exist
// at this point in the gEnv table
TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
if (nm) {
TString nms(nm->GetTitle()), nam;
Int_t from = 0;
while (nms.Tokenize(nam, from, ",")) {
if (gEnv->Lookup(nam)) {
Double_t xx = gEnv->GetValue(nam, -1.);
if (xx > 1.) fStat->Fill(xx);
} else {
Warning("SlaveBegin", "RC-env '%s' not found!", nam.Data());
}
}
} else {
Warning("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
}
}
}
//_____________________________________________________________________________
Bool_t ProofTests::Process(Long64_t)
{
// The Process() function is called for each entry in the tree (or possibly
// keyed object in the case of PROOF) to be processed. The entry argument
// specifies which entry in the currently loaded tree is to be processed.
// It can be passed to either ProofTests::GetEntry() or TBranch::GetEntry()
// to read either all or the required parts of the data. When processing
// keyed objects with PROOF, the object is already loaded and is available
// via the fObject pointer.
//
// This function should contain the "body" of the analysis. It can contain
// simple or elaborate selection criteria, run algorithms on the data
// of the event and typically fill histograms.
//
// The processing can be stopped by calling Abort().
//
// Use fStatus to set the return value of TTree::Process().
//
// The return value is currently not used.
return kTRUE;
}
//_____________________________________________________________________________
void ProofTests::SlaveTerminate()
{
// The SlaveTerminate() function is called after all entries or objects
// have been processed. When running with PROOF SlaveTerminate() is called
// on each slave server.
}
//_____________________________________________________________________________
void ProofTests::Terminate()
{
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
}
|
Improve on debug statements
|
Improve on debug statements
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@45572 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
mkret2/root,gganis/root,jrtomps/root,mattkretz/root,esakellari/my_root_for_test,dfunke/root,esakellari/root,lgiommi/root,mhuwiler/rootauto,vukasinmilosevic/root,olifre/root,davidlt/root,krafczyk/root,mhuwiler/rootauto,cxx-hep/root-cern,beniz/root,CristinaCristescu/root,zzxuanyuan/root,thomaskeck/root,krafczyk/root,krafczyk/root,vukasinmilosevic/root,omazapa/root-old,esakellari/my_root_for_test,dfunke/root,root-mirror/root,bbockelm/root,simonpf/root,jrtomps/root,karies/root,Y--/root,bbockelm/root,mhuwiler/rootauto,sirinath/root,agarciamontoro/root,davidlt/root,buuck/root,lgiommi/root,esakellari/root,georgtroska/root,georgtroska/root,dfunke/root,CristinaCristescu/root,bbockelm/root,arch1tect0r/root,beniz/root,root-mirror/root,perovic/root,nilqed/root,sawenzel/root,simonpf/root,arch1tect0r/root,arch1tect0r/root,buuck/root,krafczyk/root,alexschlueter/cern-root,davidlt/root,sawenzel/root,bbockelm/root,esakellari/my_root_for_test,beniz/root,satyarth934/root,krafczyk/root,satyarth934/root,gbitzes/root,smarinac/root,veprbl/root,dfunke/root,pspe/root,thomaskeck/root,pspe/root,karies/root,simonpf/root,BerserkerTroll/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,satyarth934/root,omazapa/root,omazapa/root-old,pspe/root,0x0all/ROOT,veprbl/root,davidlt/root,mkret2/root,root-mirror/root,gganis/root,root-mirror/root,dfunke/root,beniz/root,BerserkerTroll/root,agarciamontoro/root,abhinavmoudgil95/root,cxx-hep/root-cern,bbockelm/root,jrtomps/root,Y--/root,sirinath/root,buuck/root,omazapa/root,root-mirror/root,mkret2/root,buuck/root,0x0all/ROOT,pspe/root,smarinac/root,zzxuanyuan/root,sawenzel/root,cxx-hep/root-cern,esakellari/root,georgtroska/root,beniz/root,beniz/root,sawenzel/root,mhuwiler/rootauto,krafczyk/root,smarinac/root,krafczyk/root,evgeny-boger/root,olifre/root,veprbl/root,Y--/root,georgtroska/root,satyarth934/root,smarinac/root,CristinaCristescu/root,davidlt/root,Duraznos/root,root-mirror/root,mattkretz/root,perovic/root,pspe/root,mattkretz/root,Y--/root,omazapa/root-old,mhuwiler/rootauto,abhinavmoudgil95/root,sirinath/root,esakellari/my_root_for_test,dfunke/root,bbockelm/root,agarciamontoro/root,gbitzes/root,0x0all/ROOT,omazapa/root-old,omazapa/root-old,davidlt/root,davidlt/root,karies/root,nilqed/root,omazapa/root,gganis/root,simonpf/root,mattkretz/root,thomaskeck/root,omazapa/root,buuck/root,bbockelm/root,smarinac/root,zzxuanyuan/root,esakellari/my_root_for_test,Duraznos/root,smarinac/root,omazapa/root-old,dfunke/root,nilqed/root,karies/root,zzxuanyuan/root,BerserkerTroll/root,0x0all/ROOT,jrtomps/root,karies/root,olifre/root,vukasinmilosevic/root,krafczyk/root,nilqed/root,esakellari/root,Y--/root,esakellari/root,BerserkerTroll/root,sbinet/cxx-root,gganis/root,thomaskeck/root,lgiommi/root,lgiommi/root,thomaskeck/root,vukasinmilosevic/root,Duraznos/root,evgeny-boger/root,omazapa/root-old,0x0all/ROOT,nilqed/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,gganis/root,olifre/root,zzxuanyuan/root-compressor-dummy,lgiommi/root,mkret2/root,zzxuanyuan/root,gbitzes/root,arch1tect0r/root,buuck/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,0x0all/ROOT,vukasinmilosevic/root,Duraznos/root,georgtroska/root,Y--/root,Y--/root,buuck/root,veprbl/root,zzxuanyuan/root,CristinaCristescu/root,omazapa/root-old,jrtomps/root,root-mirror/root,karies/root,gbitzes/root,root-mirror/root,cxx-hep/root-cern,perovic/root,bbockelm/root,perovic/root,zzxuanyuan/root-compressor-dummy,beniz/root,lgiommi/root,lgiommi/root,perovic/root,gganis/root,0x0all/ROOT,arch1tect0r/root,gganis/root,thomaskeck/root,bbockelm/root,georgtroska/root,jrtomps/root,thomaskeck/root,mkret2/root,mkret2/root,davidlt/root,buuck/root,olifre/root,nilqed/root,nilqed/root,abhinavmoudgil95/root,evgeny-boger/root,esakellari/root,omazapa/root-old,Duraznos/root,Duraznos/root,sbinet/cxx-root,esakellari/root,pspe/root,mattkretz/root,thomaskeck/root,sirinath/root,satyarth934/root,simonpf/root,alexschlueter/cern-root,sirinath/root,agarciamontoro/root,jrtomps/root,gganis/root,BerserkerTroll/root,sbinet/cxx-root,cxx-hep/root-cern,0x0all/ROOT,sirinath/root,omazapa/root,perovic/root,perovic/root,sbinet/cxx-root,pspe/root,mkret2/root,sbinet/cxx-root,karies/root,CristinaCristescu/root,Y--/root,evgeny-boger/root,root-mirror/root,root-mirror/root,pspe/root,zzxuanyuan/root,karies/root,veprbl/root,pspe/root,esakellari/root,evgeny-boger/root,esakellari/my_root_for_test,zzxuanyuan/root,lgiommi/root,simonpf/root,perovic/root,karies/root,beniz/root,sirinath/root,agarciamontoro/root,arch1tect0r/root,mattkretz/root,esakellari/root,sawenzel/root,georgtroska/root,BerserkerTroll/root,BerserkerTroll/root,mattkretz/root,Y--/root,olifre/root,esakellari/my_root_for_test,karies/root,gbitzes/root,gbitzes/root,gganis/root,omazapa/root,arch1tect0r/root,mhuwiler/rootauto,sawenzel/root,Duraznos/root,sbinet/cxx-root,agarciamontoro/root,abhinavmoudgil95/root,thomaskeck/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,nilqed/root,Duraznos/root,cxx-hep/root-cern,sawenzel/root,jrtomps/root,veprbl/root,BerserkerTroll/root,sawenzel/root,karies/root,mhuwiler/rootauto,esakellari/my_root_for_test,omazapa/root,simonpf/root,sirinath/root,esakellari/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,thomaskeck/root,evgeny-boger/root,simonpf/root,simonpf/root,esakellari/root,gganis/root,BerserkerTroll/root,vukasinmilosevic/root,cxx-hep/root-cern,Duraznos/root,pspe/root,jrtomps/root,sirinath/root,smarinac/root,satyarth934/root,beniz/root,abhinavmoudgil95/root,agarciamontoro/root,CristinaCristescu/root,dfunke/root,nilqed/root,davidlt/root,cxx-hep/root-cern,olifre/root,perovic/root,sbinet/cxx-root,root-mirror/root,Duraznos/root,olifre/root,vukasinmilosevic/root,sbinet/cxx-root,arch1tect0r/root,Duraznos/root,mkret2/root,mhuwiler/rootauto,alexschlueter/cern-root,buuck/root,gbitzes/root,zzxuanyuan/root,CristinaCristescu/root,bbockelm/root,vukasinmilosevic/root,georgtroska/root,0x0all/ROOT,olifre/root,nilqed/root,gbitzes/root,jrtomps/root,CristinaCristescu/root,perovic/root,veprbl/root,zzxuanyuan/root,pspe/root,gbitzes/root,olifre/root,abhinavmoudgil95/root,agarciamontoro/root,abhinavmoudgil95/root,alexschlueter/cern-root,gbitzes/root,evgeny-boger/root,satyarth934/root,zzxuanyuan/root,BerserkerTroll/root,vukasinmilosevic/root,veprbl/root,dfunke/root,sbinet/cxx-root,alexschlueter/cern-root,sawenzel/root,sawenzel/root,arch1tect0r/root,mattkretz/root,BerserkerTroll/root,olifre/root,smarinac/root,arch1tect0r/root,vukasinmilosevic/root,mattkretz/root,omazapa/root,davidlt/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,arch1tect0r/root,georgtroska/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,gbitzes/root,omazapa/root,veprbl/root,lgiommi/root,krafczyk/root,mhuwiler/rootauto,esakellari/my_root_for_test,Y--/root,mkret2/root,sirinath/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,beniz/root,Y--/root,alexschlueter/cern-root,mattkretz/root,mattkretz/root,omazapa/root-old,davidlt/root,smarinac/root,zzxuanyuan/root,abhinavmoudgil95/root,esakellari/my_root_for_test,simonpf/root,omazapa/root,alexschlueter/cern-root,buuck/root,sawenzel/root,perovic/root,vukasinmilosevic/root,sbinet/cxx-root,omazapa/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,sirinath/root,lgiommi/root,satyarth934/root,buuck/root,agarciamontoro/root,sbinet/cxx-root,evgeny-boger/root,abhinavmoudgil95/root,dfunke/root,CristinaCristescu/root,krafczyk/root,evgeny-boger/root,dfunke/root,agarciamontoro/root,georgtroska/root,mkret2/root,abhinavmoudgil95/root,veprbl/root,nilqed/root,lgiommi/root,gganis/root,smarinac/root,simonpf/root,omazapa/root-old,evgeny-boger/root,mkret2/root,beniz/root,agarciamontoro/root,bbockelm/root,veprbl/root
|
02c12230e45252acee5d04dbeaa5973d21b64e19
|
src/model.cpp
|
src/model.cpp
|
// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
@brief Inplementation of Simulation class
*/
#include "model.hpp"
#include <cstdlib>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/coroutine2/coroutine.hpp>
#define EIGEN_NO_DEBUG
#include "Eigen/Core"
#include <cxxwtils/iostr.hpp>
#include <cxxwtils/getopt.hpp>
#include <cxxwtils/prandom.hpp>
#include <cxxwtils/os.hpp>
#include <cxxwtils/gz.hpp>
#include <cxxwtils/eigen.hpp>
namespace lmpp {
namespace bmath = boost::math;
namespace fs = boost::filesystem;
namespace po = boost::program_options;
inline po::options_description general_desc() {HERE;
po::options_description description("General");
description.add_options()
("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "print this help")
("verbose,v", po::value<bool>()->default_value(false)->implicit_value(true), "verbose output")
("test", po::value<int>()->default_value(0)->implicit_value(1));
return description;
}
po::options_description Model::options_desc() {HERE;
po::options_description description("Simulation");
description.add_options()
("write,w", po::value<bool>(&WRITE_TO_FILES)->default_value(WRITE_TO_FILES)->implicit_value(true))
("out_dir,o", po::value<std::string>(&OUT_DIR)->default_value(OUT_DIR))
("seed", po::value<unsigned int>(&SEED)->default_value(SEED));
return description;
}
po::options_description Model::positional_desc() {HERE;
po::options_description description("Positional");
description.add_options()
("epsilon", po::value(&epsilon_)->default_value(epsilon_))
("threshold", po::value(&threshold_)->default_value(threshold_));
return description;
}
void Model::help_and_exit() {HERE;
auto description = general_desc();
description.add(options_desc());
// do not print positional arguments as options
std::cout << "Usage: tumopp [options] nsam howmany\n" << std::endl;
description.print(std::cout);
throw wtl::ExitSuccess();
}
//! Unit test for each class
inline void test(const int flg) {HERE;
switch (flg) {
case 0:
break;
case 1:
throw wtl::ExitSuccess();
default:
throw std::runtime_error("Unknown argument for --test");
}
}
Model::Model(const std::vector<std::string>& arguments) {HERE;
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.precision(15);
std::cerr.precision(6);
COMMAND_ARGS = wtl::str_join(arguments, " ");
OUT_DIR = wtl::strftime("tumopp_%Y%m%d_%H%M_") + std::to_string(::getpid());
auto description = general_desc();
description.add(options_desc());
description.add(positional_desc());
po::positional_options_description positional;
positional.add("nsam", 1)
.add("howmany", 1);
po::variables_map vm;
po::store(po::command_line_parser(arguments).
options(description).
positional(positional).run(), vm);
if (vm["help"].as<bool>()) {help_and_exit();}
po::notify(vm);
wtl::sfmt().seed(SEED);
// CONFIG_STRING = wtl::flags_into_string(vm);
if (vm["verbose"].as<bool>()) {
std::cerr << wtl::iso8601datetime() << std::endl;
std::cerr << CONFIG_STRING << std::endl;
}
test(vm["test"].as<int>());
OUT_DIR = fs::system_complete(OUT_DIR).string();
}
inline double normal_cdf(const double x, const double mean, const double sd, const bool complement=false) {
if (complement) {
return bmath::cdf(bmath::complement(bmath::normal(mean, sd), x));
} else {
return bmath::cdf(bmath::normal(mean, sd), x);
}
}
inline double Model::normal_ccdf(double score, const double sd) {
return normal_cdf(threshold_, score += epsilon_, sd, true);
}
inline bool equals_one(double x) {
return std::fabs(x - 1.0) < std::numeric_limits<double>::epsilon();
}
class SimplexIterator;
class Simplex {
public:
typedef Eigen::VectorXd value_type;
typedef SimplexIterator iterator;
Simplex() = delete;
Simplex(const size_t n):
dimensions_(n),
axis_(Eigen::VectorXd::LinSpaced(steps_, 0.0, 1.0)),
ptrs_(dimensions_, axis_.data()) {}
// const value_type& value() const {return {3};}
value_type value() const {return value_type(3);}
iterator begin();
iterator end();
Simplex& operator++() {
// auto end = axis_.data() + steps_;
value_type value(dimensions_);
for (size_t i=0; i<dimensions_; ++i) {
// for (; ptrs_[i] < end; ++ptrs_[i]) {
//
// }
value[i] = *ptrs_[i];
}
return *this;
}
// bool sum1() const {
// return equals_one(value_.sum());
// // return value_.minCoeff() > 0.0;
// }
private:
double dimensions_ = 0;
size_t steps_ = 4;
Eigen::VectorXd axis_;
std::vector<double*> ptrs_;
};
class SimplexIterator: public std::iterator<std::forward_iterator_tag, double> {
public:
SimplexIterator(Simplex* x): ptr_(x) {}
Simplex& operator*() const {
return *ptr_;
}
Simplex* operator->() const {
return ptr_;
}
SimplexIterator& operator++() {
ptr_->operator++();
return *this;
}
bool operator!= (const SimplexIterator& it) const {
return (ptr_ != it.ptr_);
}
private:
Simplex* ptr_;
};
SimplexIterator Simplex::begin() {return SimplexIterator(this);}
SimplexIterator Simplex::end() {return SimplexIterator(this);}
template <class T>
inline void nested_loop(const T& range, size_t nest=3, T current={}) {
if (current.empty()) current.assign(nest, 0);
if (--nest > 0) {
for (const auto& x: range) {
current[nest] = x;
nested_loop(range, nest, current);
}
} else {
for (const auto& x: range) {
current[nest] = x;
std::cout << current << std::endl;
}
}
}
template <>
inline void nested_loop<Eigen::VectorXd>(const Eigen::VectorXd& range, size_t nest, Eigen::VectorXd current) {
if (current.size() == 0) current.resize(nest);
auto end = range.data() + range.size();
if (--nest > 0) {
for (auto p=range.data(); p<end; ++p) {
current[nest] = *p;
nested_loop(range, nest, current);
}
} else {
for (auto p=range.data(); p<end; ++p) {
current[nest] = *p;
std::cout << wtl::eigen::as_vector(current) << std::endl;
}
}
}
template <class T> inline
typename boost::coroutines2::coroutine<T>::pull_type
generate(const T& range, size_t nest=3, T current={}) {
if (current.empty()) current.assign(nest, 0);
typedef boost::coroutines2::coroutine<T> coro_t;
return typename coro_t::pull_type([&](typename coro_t::push_type& yield){
if (--nest > 0) {
for (const auto& x: range) {
current[nest] = x;
nested_loop(range, nest, current);
}
} else {
for (const auto& x: range) {
current[nest] = x;
yield(current);
}
}
});
}
void Model::genotype2score() {HERE;
Simplex v(3);
auto it = v.begin();
std::cout << it->value() << std::endl;
++it;
std::cout << it->value() << std::endl;
size_t dimensions = 2;
size_t num_samples = 4;
Eigen::VectorXd parameter(dimensions);
Eigen::MatrixXd genotype(num_samples, dimensions);
parameter << 0.3, 0.4;
genotype << 0, 0,
1, 0,
0, 1,
1, 1;
std::cout << genotype * parameter << std::endl;
std::cout << normal_ccdf(0.1, 0.5) << std::endl;
std::cout << normal_ccdf(0.3, 0.5) << std::endl;
std::cout << normal_ccdf(0.4, 0.5) << std::endl;
std::cout << normal_ccdf(0.5, 0.5) << std::endl;
std::cout << normal_ccdf(0.7, 0.5) << std::endl;
}
void Model::run() {HERE;
genotype2score();
Eigen::VectorXd vxd = Eigen::VectorXd::LinSpaced(3, 0.0, 1.0);
// nested_loop(vxd, 3);
auto gen = generate(wtl::eigen::as_vector(vxd), 3);
for (auto x: gen) {
std::cout << x << std::endl;
}
}
void Model::write() const {HERE;
auto mat = Eigen::Matrix3d::Random();
std::ofstream("test.tsv") << mat.format(wtl::eigen::tsv());
std::cout << wtl::eigen::read_matrix<double>("test.tsv").format(wtl::eigen::tsv()) << std::endl;
if (WRITE_TO_FILES) {
derr("mkdir && cd to " << OUT_DIR << std::endl);
fs::create_directory(OUT_DIR);
wtl::cd(OUT_DIR);
wtl::Fout{"program_options.conf"} << CONFIG_STRING;
std::cerr << wtl::iso8601datetime() << std::endl;
}
}
} // namespace tumopp
|
// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
@brief Inplementation of Simulation class
*/
#include "model.hpp"
#include <cstdlib>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/coroutine2/coroutine.hpp>
#define EIGEN_NO_DEBUG
#include "Eigen/Core"
#include <cxxwtils/iostr.hpp>
#include <cxxwtils/getopt.hpp>
#include <cxxwtils/prandom.hpp>
#include <cxxwtils/os.hpp>
#include <cxxwtils/gz.hpp>
#include <cxxwtils/eigen.hpp>
namespace lmpp {
namespace bmath = boost::math;
namespace fs = boost::filesystem;
namespace po = boost::program_options;
inline po::options_description general_desc() {HERE;
po::options_description description("General");
description.add_options()
("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "print this help")
("verbose,v", po::value<bool>()->default_value(false)->implicit_value(true), "verbose output")
("test", po::value<int>()->default_value(0)->implicit_value(1));
return description;
}
po::options_description Model::options_desc() {HERE;
po::options_description description("Simulation");
description.add_options()
("write,w", po::value<bool>(&WRITE_TO_FILES)->default_value(WRITE_TO_FILES)->implicit_value(true))
("out_dir,o", po::value<std::string>(&OUT_DIR)->default_value(OUT_DIR))
("seed", po::value<unsigned int>(&SEED)->default_value(SEED));
return description;
}
po::options_description Model::positional_desc() {HERE;
po::options_description description("Positional");
description.add_options()
("epsilon", po::value(&epsilon_)->default_value(epsilon_))
("threshold", po::value(&threshold_)->default_value(threshold_));
return description;
}
void Model::help_and_exit() {HERE;
auto description = general_desc();
description.add(options_desc());
// do not print positional arguments as options
std::cout << "Usage: tumopp [options] nsam howmany\n" << std::endl;
description.print(std::cout);
throw wtl::ExitSuccess();
}
//! Unit test for each class
inline void test(const int flg) {HERE;
switch (flg) {
case 0:
break;
case 1:
throw wtl::ExitSuccess();
default:
throw std::runtime_error("Unknown argument for --test");
}
}
Model::Model(const std::vector<std::string>& arguments) {HERE;
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.precision(15);
std::cerr.precision(6);
COMMAND_ARGS = wtl::str_join(arguments, " ");
OUT_DIR = wtl::strftime("tumopp_%Y%m%d_%H%M_") + std::to_string(::getpid());
auto description = general_desc();
description.add(options_desc());
description.add(positional_desc());
po::positional_options_description positional;
positional.add("nsam", 1)
.add("howmany", 1);
po::variables_map vm;
po::store(po::command_line_parser(arguments).
options(description).
positional(positional).run(), vm);
if (vm["help"].as<bool>()) {help_and_exit();}
po::notify(vm);
wtl::sfmt().seed(SEED);
// CONFIG_STRING = wtl::flags_into_string(vm);
if (vm["verbose"].as<bool>()) {
std::cerr << wtl::iso8601datetime() << std::endl;
std::cerr << CONFIG_STRING << std::endl;
}
test(vm["test"].as<int>());
OUT_DIR = fs::system_complete(OUT_DIR).string();
}
inline double normal_cdf(const double x, const double mean, const double sd, const bool complement=false) {
if (complement) {
return bmath::cdf(bmath::complement(bmath::normal(mean, sd), x));
} else {
return bmath::cdf(bmath::normal(mean, sd), x);
}
}
inline double Model::normal_ccdf(double score, const double sd) {
return normal_cdf(threshold_, score += epsilon_, sd, true);
}
inline bool equals_one(double x) {
return std::fabs(x - 1.0) < std::numeric_limits<double>::epsilon();
}
template <class value_type>
class BruteForce {
public:
typedef boost::coroutines2::coroutine<value_type> coro_t;
BruteForce() = delete;
BruteForce(const value_type& axis, const size_t dimensions):
dimensions_(dimensions),
level_(dimensions),
current_(dimensions),
axis_(axis) {}
typename coro_t::pull_type generate() {
return typename coro_t::pull_type([this](typename coro_t::push_type& yield){source(yield);});
}
private:
void source(typename coro_t::push_type& yield) {
if (--level_ > 0) {
for (const auto x: axis_) {
current_[level_] = x;
source(yield);
}
++level_;
} else {
for (const auto x: axis_) {
current_[level_] = x;
yield(value_type(current_));
}
++level_;
}
}
const double dimensions_;
size_t level_;
value_type current_;
value_type axis_;
};
template <class T>
BruteForce<T> brute_force(const T& axis, const size_t dimensions) {
return BruteForce<T>(axis, dimensions);
}
class SimplexIterator;
class Simplex {
public:
typedef std::vector<double> value_type;
typedef SimplexIterator iterator;
typedef boost::coroutines2::coroutine<value_type> coro_t;
Simplex() = delete;
Simplex(const value_type& axis, const size_t dimensions): bf_(axis, dimensions) {}
iterator begin();
iterator end();
Simplex& operator++() {
return *this;
}
private:
BruteForce<value_type> bf_;
};
class SimplexIterator: public std::iterator<std::forward_iterator_tag, double> {
public:
SimplexIterator(Simplex* x): ptr_(x) {}
Simplex& operator*() const {
return *ptr_;
}
Simplex* operator->() const {
return ptr_;
}
SimplexIterator& operator++() {
ptr_->operator++();
return *this;
}
bool operator!= (const SimplexIterator& it) const {
return (ptr_ != it.ptr_);
}
private:
Simplex* ptr_;
};
SimplexIterator Simplex::begin() {return SimplexIterator(this);}
SimplexIterator Simplex::end() {return SimplexIterator(this);}
template <class T>
inline void nested_loop(const T& range, size_t nest=3, T current={}) {
if (current.empty()) current.assign(nest, 0);
if (--nest > 0) {
for (const auto& x: range) {
current[nest] = x;
nested_loop(range, nest, current);
}
} else {
for (const auto& x: range) {
current[nest] = x;
std::cout << current << std::endl;
}
}
}
template <>
inline void nested_loop<Eigen::VectorXd>(const Eigen::VectorXd& range, size_t nest, Eigen::VectorXd current) {
if (current.size() == 0) current.resize(nest);
auto end = range.data() + range.size();
if (--nest > 0) {
for (auto p=range.data(); p<end; ++p) {
current[nest] = *p;
nested_loop(range, nest, current);
}
} else {
for (auto p=range.data(); p<end; ++p) {
current[nest] = *p;
std::cout << wtl::eigen::as_vector(current) << std::endl;
}
}
}
void Model::genotype2score() {HERE;
size_t dimensions = 2;
size_t num_samples = 4;
Eigen::VectorXd parameter(dimensions);
Eigen::MatrixXd genotype(num_samples, dimensions);
parameter << 0.3, 0.4;
genotype << 0, 0,
1, 0,
0, 1,
1, 1;
std::cout << genotype * parameter << std::endl;
std::cout << normal_ccdf(0.1, 0.5) << std::endl;
std::cout << normal_ccdf(0.3, 0.5) << std::endl;
std::cout << normal_ccdf(0.4, 0.5) << std::endl;
std::cout << normal_ccdf(0.5, 0.5) << std::endl;
std::cout << normal_ccdf(0.7, 0.5) << std::endl;
}
void Model::run() {HERE;
// genotype2score();
Eigen::VectorXd vxd = Eigen::VectorXd::LinSpaced(3, 0.0, 1.0);
auto vd = wtl::eigen::as_vector(vxd);
auto bf = brute_force(vd, 3);
for (const auto& x: bf.generate()) {
std::cout << x << std::endl;
}
Simplex v(vd, 3);
auto it = v.begin();
++it;
}
void Model::write() const {HERE;
auto mat = Eigen::Matrix3d::Random();
std::ofstream("test.tsv") << mat.format(wtl::eigen::tsv());
std::cout << wtl::eigen::read_matrix<double>("test.tsv").format(wtl::eigen::tsv()) << std::endl;
if (WRITE_TO_FILES) {
derr("mkdir && cd to " << OUT_DIR << std::endl);
fs::create_directory(OUT_DIR);
wtl::cd(OUT_DIR);
wtl::Fout{"program_options.conf"} << CONFIG_STRING;
std::cerr << wtl::iso8601datetime() << std::endl;
}
}
} // namespace tumopp
|
Implement BruteForce
|
Implement BruteForce
|
C++
|
mit
|
heavywatal/likeligrid,heavywatal/likeligrid
|
02e04a5820ce033913cfb7c3ebf14fbbfe211d43
|
src/bindings/python/vistk/image/vil.cxx
|
src/bindings/python/vistk/image/vil.cxx
|
/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/python/any_conversion/prototypes.h>
#include <vistk/python/any_conversion/registration.h>
#include <vistk/python/numpy/import.h>
#include <vistk/python/numpy/registration.h>
#include <boost/cstdint.hpp>
#include <Python.h>
/**
* \file vil.cxx
*
* \brief Python bindings for \link vil_image_view\endlink.
*/
using namespace boost::python;
static pyimport_return_t import_numpy();
BOOST_PYTHON_MODULE(vil)
{
vistk::python::import_numpy();
vistk::python::register_memory_chunk();
vistk::python::register_image_base();
vistk::python::register_image_type();
vistk::python::register_type<vil_image_view<bool> >(10);
vistk::python::register_type<vil_image_view<uint8_t> >(10);
vistk::python::register_type<vil_image_view<float> >(10);
vistk::python::register_type<vil_image_view<double> >(10);
}
|
/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/python/any_conversion/prototypes.h>
#include <vistk/python/any_conversion/registration.h>
#include <vistk/python/numpy/import.h>
#include <vistk/python/numpy/numpy_to_vil.h>
#include <vistk/python/numpy/registration.h>
#include <vistk/python/numpy/vil_to_numpy.h>
#include <vil/vil_image_view.h>
#include <boost/python/args.hpp>
#include <boost/python/def.hpp>
#include <boost/python/module.hpp>
#include <boost/cstdint.hpp>
#include <Python.h>
/**
* \file vil.cxx
*
* \brief Python bindings for \link vil_image_view\endlink.
*/
using namespace boost::python;
BOOST_PYTHON_MODULE(vil)
{
vistk::python::import_numpy();
#define VIL_TYPES(call) \
call(bool); \
call(uint8_t); \
call(float); \
call(double)
vistk::python::register_memory_chunk();
vistk::python::register_image_base();
#define REGISTER_IMAGE_TYPE(type) \
vistk::python::register_image_type<type>(); \
vistk::python::register_type<vil_image_view<type> >(10)
VIL_TYPES(REGISTER_IMAGE_TYPE);
#undef REGISTER_IMAGE_TYPE
def("numpy_to_vil", &vistk::python::numpy_to_vil_base
, (arg("numpy array"))
, "Convert a NumPy array into a base vil image.");
def("vil_to_numpy", &vistk::python::vil_base_to_numpy
, (arg("numpy array"))
, "Convert a NumPy array into a base vil image.");
#define DEFINE_CONVERSION_FUNCTIONS(type) \
do \
{ \
def("numpy_to_vil_" #type, &vistk::python::numpy_to_vil<type> \
, (arg("numpy")) \
, "Convert a NumPy array into a " #type " vil image."); \
def("vil_to_numpy", &vistk::python::vil_to_numpy<type> \
, (arg("vil")) \
, "Convert a vil image into a NumPy array."); \
} while (false)
VIL_TYPES(DEFINE_CONVERSION_FUNCTIONS);
#undef DEFINE_FUNCTIONS
#undef VIL_TYPES
}
|
Add conversion functions to the vil module
|
Add conversion functions to the vil module
|
C++
|
bsd-3-clause
|
Kitware/sprokit,Kitware/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,mathstuf/sprokit
|
2d987b2a1c32540f51c31348a854310131fa0c17
|
src/client/elements/torrent_display.cpp
|
src/client/elements/torrent_display.cpp
|
#include "torrent_display.h"
#include "client/shared_data.h"
#include "client/data_formatting.h"
#include <iostream>
namespace client
{
void Torrent_display_element::update ( char key, std::shared_ptr < ncurses::Window > window )
{
auto torrent_data = client::Shared_data::get_torrent_data ();
if ( torrent_data.get () != nullptr )
{
int y = 0;
draw_totals ( torrent_data, window, y );
y += 2;
for ( auto torrent : *torrent_data )
{
if ( torrent->is_active () )
{
window->move ( 0, y );
window->draw_string ( torrent->get_string ( "name" ) );
y ++;
if ( torrent->get_double ( "progress" ) < 1 )
{
draw_progress ( torrent, window, y );
y ++;
}
if ( torrent->get_int ( "download_payload_rate" ) > 0 )
{
draw_download ( torrent, window, y );
y++;
}
if ( torrent->get_int ( "upload_payload_rate" ) > 0 )
{
draw_upload ( torrent, window, y );
y++;
}
y++;
}
}
window->move ( window->get_width () - 1, window->get_height () - 1 );
window->refresh ();
}
}
int Torrent_display_element::get_prefered_width () const { return 0; }
int Torrent_display_element::get_prefered_height () const { return 0; }
std::string Torrent_display_element::right_bound ( std::string text, size_t amount )
{
while ( text.size () < amount )
text = " " + text;
return text;
}
void Torrent_display_element::draw_progress (
std::shared_ptr < Torrent_data >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
std::string progress_number = to_percentage ( torrent_data->get_double ( "progress" ) );
std::string file_size = to_file_size ( torrent_data->get_double ( "total_wanted" ) );
window->move ( 0, y );
window->draw_string ( right_bound ( progress_number, 10 ) + " of " + file_size );
}
void Torrent_display_element::draw_download (
std::shared_ptr < Torrent_data >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
std::string download_speed = to_transfer_speed ( torrent_data->get_int ( "download_payload_rate" ) );
std::string eta = torrent_data->get_eta ();
window->move ( 0, y );
window->set_fg_color ( ncurses::Window::RED );
window->draw_string ( right_bound ( download_speed, 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
window->draw_string ( right_bound ( eta, 16 ) );
}
void Torrent_display_element::draw_upload (
std::shared_ptr < Torrent_data >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
std::string upload_speed = to_transfer_speed ( torrent_data->get_int ( "upload_payload_rate" ) );
std::string ratio = torrent_data->get_ratio ();
window->move ( 0, y );
window->set_fg_color ( ncurses::Window::GREEN );
window->draw_string ( right_bound ( upload_speed, 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
window->draw_string ( right_bound ( ratio, 16 ) );
}
void Torrent_display_element::draw_totals (
std::shared_ptr < std::vector < std::shared_ptr < Torrent_data > > >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
int total_download = 0;
int total_upload = 0;
for ( auto torrent : *torrent_data )
{
total_download += torrent->get_int ( "download_payload_rate" );
total_upload += torrent->get_int ( "upload_payload_rate" );
}
window->move ( 0, y );
window->draw_string ( "Download: " );
window->set_fg_color ( ncurses::Window::RED );
window->draw_string ( right_bound ( to_transfer_speed ( total_download ), 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
window->draw_string ( " Upload: " );
window->set_fg_color ( ncurses::Window::GREEN );
window->draw_string ( right_bound ( to_transfer_speed ( total_upload ), 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
}
}
|
#include "torrent_display.h"
#include "client/shared_data.h"
#include "client/data_formatting.h"
#include <iostream>
namespace client
{
void Torrent_display_element::update ( char key, std::shared_ptr < ncurses::Window > window )
{
auto torrent_data = client::Shared_data::get_torrent_data ();
if ( torrent_data.get () != nullptr )
{
int y = 0;
draw_totals ( torrent_data, window, y );
y += 2;
for ( auto torrent : *torrent_data )
{
if ( torrent->is_active () )
{
window->move ( 0, y );
window->draw_string ( torrent->get_string ( "name" ) );
y ++;
if ( torrent->get_double ( "progress" ) < 1 )
{
draw_progress ( torrent, window, y );
y ++;
}
if ( torrent->get_int ( "download_payload_rate" ) > 0 )
{
draw_download ( torrent, window, y );
y++;
}
if ( torrent->get_int ( "upload_payload_rate" ) > 0 )
{
draw_upload ( torrent, window, y );
y++;
}
y++;
}
}
window->move ( window->get_width () - 1, window->get_height () - 1 );
window->refresh ();
}
}
int Torrent_display_element::get_prefered_width () const { return 0; }
int Torrent_display_element::get_prefered_height () const { return 0; }
std::string Torrent_display_element::right_bound ( std::string text, size_t amount )
{
while ( text.size () < amount )
text = " " + text;
return text;
}
void Torrent_display_element::draw_progress (
std::shared_ptr < Torrent_data >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
std::string progress_number = to_percentage ( torrent_data->get_double ( "progress" ) );
std::string file_size = to_file_size ( torrent_data->get_double ( "total_wanted" ) );
std::string progress_text = right_bound ( progress_number, 10 ) + " of " + file_size + " [";
window->move ( 0, y );
window->draw_string ( progress_text );
int bar_width = window->get_width () - 2 - progress_text.size ();
window->set_fg_color ( ncurses::Window::CYAN );
for ( int i = 0; i < bar_width * torrent_data->get_double ( "progress" ); i++ )
{
window->draw_string ( "|" );
}
window->set_fg_color ( ncurses::Window::DEFAULT );
window->move ( window->get_width () - 1, y );
window->draw_string ( "]" );
}
void Torrent_display_element::draw_download (
std::shared_ptr < Torrent_data >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
std::string download_speed = to_transfer_speed ( torrent_data->get_int ( "download_payload_rate" ) );
std::string eta = torrent_data->get_eta ();
window->move ( 0, y );
window->set_fg_color ( ncurses::Window::RED );
window->draw_string ( right_bound ( download_speed, 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
window->draw_string ( right_bound ( eta, 16 ) );
}
void Torrent_display_element::draw_upload (
std::shared_ptr < Torrent_data >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
std::string upload_speed = to_transfer_speed ( torrent_data->get_int ( "upload_payload_rate" ) );
std::string ratio = torrent_data->get_ratio ();
window->move ( 0, y );
window->set_fg_color ( ncurses::Window::GREEN );
window->draw_string ( right_bound ( upload_speed, 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
window->draw_string ( right_bound ( ratio, 16 ) );
}
void Torrent_display_element::draw_totals (
std::shared_ptr < std::vector < std::shared_ptr < Torrent_data > > >& torrent_data,
std::shared_ptr < ncurses::Window > window,
int y
)
{
int total_download = 0;
int total_upload = 0;
for ( auto torrent : *torrent_data )
{
total_download += torrent->get_int ( "download_payload_rate" );
total_upload += torrent->get_int ( "upload_payload_rate" );
}
window->move ( 0, y );
window->draw_string ( "Download: " );
window->set_fg_color ( ncurses::Window::RED );
window->draw_string ( right_bound ( to_transfer_speed ( total_download ), 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
window->draw_string ( " Upload: " );
window->set_fg_color ( ncurses::Window::GREEN );
window->draw_string ( right_bound ( to_transfer_speed ( total_upload ), 14 ) );
window->set_fg_color ( ncurses::Window::DEFAULT );
}
}
|
Add progressbar to client::Torrent_display::draw_progress ()
|
Add progressbar to client::Torrent_display::draw_progress ()
|
C++
|
mit
|
froozen/s-torrent,froozen/s-torrent,froozen/s-torrent
|
d405899a654902d600aa9307b10c9f4d68316115
|
src/prefix.cc
|
src/prefix.cc
|
#include <map>
#include <ncurses.h>
#include <string>
#include "file_contents.hh"
#include "mode.hh"
#include "show_message.hh"
#include "prefix.hh"
prefix::prefix(std::string message)
: message(message) { }
void prefix::push_back(char ch, std::function<void(contents&, boost::optional<int>)> fun) {
this->map[ch] = fun;
}
void prefix::operator()(contents& cont, boost::optional<int> op) {
show_message(message + "-");
char ch = getch();
auto it = map.find(ch);
if(it == map.end()) {
show_message(std::string("Didn't recognize key sequence: '")
+ message + '-' + ch + '\'');
} else {
it->second(cont, op);
showing_message = false;
}
}
prefix::operator std::function < void ( contents&,
boost::optional<int> ) > () {
return std::function < void ( contents&,
boost::optional<int> ) >
([&,this] (contents& cont, boost::optional<int> op)
{
(*this)(cont,op);
});
}
|
#include <map>
#include <ncurses.h>
#include <string>
#include "file_contents.hh"
#include "mode.hh"
#include "show_message.hh"
#include "prefix.hh"
prefix::prefix(std::string message)
: message(message) { }
void prefix::push_back(char ch, std::function<void(contents&, boost::optional<int>)> fun) {
this->map[ch] = fun;
}
void prefix::operator()(contents& cont, boost::optional<int> op) {
show_message(message + "-");
char ch = getch();
auto it = map.find(ch);
if(it == map.end()) {
show_message(std::string("Didn't recognize key sequence: '")
+ message + '-' + ch + '\'');
} else {
it->second(cont, op);
showing_message = false;
}
}
prefix::operator std::function < void ( contents&,
boost::optional<int> ) > () {
return std::function < void ( contents&,
boost::optional<int> ) >
([this] (contents& cont, boost::optional<int> op)
{
(*this)(cont,op);
});
}
|
Make lambda capture *pointer* to ``this`` by value
|
Make lambda capture *pointer* to ``this`` by value
|
C++
|
mpl-2.0
|
czipperz/vick,czipperz/vick
|
f84d69854f9886662155dc711305114122575989
|
src/scene.cpp
|
src/scene.cpp
|
#include "./scene.h"
#include <QDebug>
#include <QOpenGLFramebufferObject>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./gl.h"
#include "./input/invoke_manager.h"
#include "./mesh.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./forces_visualizer_node.h"
#include "./render_data.h"
#include "./importer.h"
#include "./camera_controller.h"
#include "./camera_rotation_controller.h"
#include "./camera_zoom_controller.h"
#include "./camera_move_controller.h"
#include "./nodes.h"
#include "./quad.h"
#include "./utils/persister.h"
#include "./forces/labeller_frame_data.h"
BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes,
std::shared_ptr<Forces::Labeller> labeller)
: nodes(nodes), labeller(labeller)
{
cameraController = std::make_shared<CameraController>(camera);
cameraRotationController = std::make_shared<CameraRotationController>(camera);
cameraZoomController = std::make_shared<CameraZoomController>(camera);
cameraMoveController = std::make_shared<CameraMoveController>(camera);
invokeManager->addHandler("cam", cameraController.get());
invokeManager->addHandler("cameraRotation", cameraRotationController.get());
invokeManager->addHandler("cameraZoom", cameraZoomController.get());
invokeManager->addHandler("cameraMove", cameraMoveController.get());
}
Scene::~Scene()
{
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
const std::string filename = "assets/assets.dae";
Importer importer;
std::vector<std::shared_ptr<Node>> meshNodes;
for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
{
auto mesh = importer.import(filename, meshIndex);
auto node =
new MeshNode(filename, meshIndex, mesh, Eigen::Matrix4f::Identity());
meshNodes.push_back(std::unique_ptr<MeshNode>(node));
}
auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.553f, 0.02f));
meshNodes.push_back(std::make_shared<LabelNode>(label));
auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.334f, 0.317f, -0.013f));
meshNodes.push_back(std::make_shared<LabelNode>(label2));
auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2f(0.14f, 0.14f));
meshNodes.push_back(std::make_shared<LabelNode>(label3));
auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
meshNodes.push_back(std::make_shared<LabelNode>(label4));
Persister::save(meshNodes, "config/scene.xml");
nodes->addSceneNodesFrom("config/scene.xml");
for (auto &labelNode : nodes->getLabelNodes())
{
auto label = labelNode->getLabel();
labeller->addLabel(label.id, label.text, label.anchorPosition, label.size);
}
nodes->addNode(std::make_shared<ForcesVisualizerNode>(labeller));
quad = std::make_shared<Quad>();
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
this->frameTime = frameTime;
cameraController->setFrameTime(frameTime);
cameraRotationController->setFrameTime(frameTime);
cameraZoomController->setFrameTime(frameTime);
cameraMoveController->setFrameTime(frameTime);
auto newPositions = labeller->update(Forces::LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->getLabel().id];
}
}
void Scene::render()
{
glAssert(glViewport(0, 0, width, height));
glAssert(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
glAssert(fbo->bind());
glAssert(glViewport(0, 0, width, height));
glAssert(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData;
renderData.projectionMatrix = camera.getProjectionMatrix();
renderData.viewMatrix = camera.getViewMatrix();
renderData.cameraPosition = camera.getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
nodes->render(gl, renderData);
glAssert(fbo->release());
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix =
Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix();
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
glAssert(gl->glActiveTexture(GL_TEXTURE0));
glAssert(gl->glBindTexture(GL_TEXTURE_2D, fbo->texture()));
quad->render(gl, renderData);
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
glAssert(glViewport(0, 0, width, height));
camera.resize(width, height);
if (fbo.get())
fbo->release();
fbo = std::unique_ptr<QOpenGLFramebufferObject>(new QOpenGLFramebufferObject(
width, height, QOpenGLFramebufferObject::CombinedDepthStencil));
qWarning() << "create fbo";
/*
glAssert(fbo->bind());
glAssert(glViewport(0, 0, width, height));
glAssert(fbo->bindDefault());
*/
}
|
#include "./scene.h"
#include <QDebug>
#include <QOpenGLFramebufferObject>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./gl.h"
#include "./input/invoke_manager.h"
#include "./mesh.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./forces_visualizer_node.h"
#include "./render_data.h"
#include "./importer.h"
#include "./camera_controller.h"
#include "./camera_rotation_controller.h"
#include "./camera_zoom_controller.h"
#include "./camera_move_controller.h"
#include "./nodes.h"
#include "./quad.h"
#include "./utils/persister.h"
#include "./forces/labeller_frame_data.h"
BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes,
std::shared_ptr<Forces::Labeller> labeller)
: nodes(nodes), labeller(labeller)
{
cameraController = std::make_shared<CameraController>(camera);
cameraRotationController = std::make_shared<CameraRotationController>(camera);
cameraZoomController = std::make_shared<CameraZoomController>(camera);
cameraMoveController = std::make_shared<CameraMoveController>(camera);
invokeManager->addHandler("cam", cameraController.get());
invokeManager->addHandler("cameraRotation", cameraRotationController.get());
invokeManager->addHandler("cameraZoom", cameraZoomController.get());
invokeManager->addHandler("cameraMove", cameraMoveController.get());
}
Scene::~Scene()
{
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
const std::string filename = "assets/assets.dae";
Importer importer;
std::vector<std::shared_ptr<Node>> meshNodes;
for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
{
auto mesh = importer.import(filename, meshIndex);
auto node =
new MeshNode(filename, meshIndex, mesh, Eigen::Matrix4f::Identity());
meshNodes.push_back(std::unique_ptr<MeshNode>(node));
}
auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.553f, 0.02f));
meshNodes.push_back(std::make_shared<LabelNode>(label));
auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.334f, 0.317f, -0.013f));
meshNodes.push_back(std::make_shared<LabelNode>(label2));
auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2f(0.14f, 0.14f));
meshNodes.push_back(std::make_shared<LabelNode>(label3));
auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
meshNodes.push_back(std::make_shared<LabelNode>(label4));
Persister::save(meshNodes, "config/scene.xml");
nodes->addSceneNodesFrom("config/scene.xml");
for (auto &labelNode : nodes->getLabelNodes())
{
auto label = labelNode->getLabel();
labeller->addLabel(label.id, label.text, label.anchorPosition, label.size);
}
nodes->addNode(std::make_shared<ForcesVisualizerNode>(labeller));
quad = std::make_shared<Quad>();
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
this->frameTime = frameTime;
cameraController->setFrameTime(frameTime);
cameraRotationController->setFrameTime(frameTime);
cameraZoomController->setFrameTime(frameTime);
cameraMoveController->setFrameTime(frameTime);
auto newPositions = labeller->update(Forces::LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->getLabel().id];
}
}
void Scene::render()
{
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
glAssert(fbo->bind());
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData;
renderData.projectionMatrix = camera.getProjectionMatrix();
renderData.viewMatrix = camera.getViewMatrix();
renderData.cameraPosition = camera.getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
nodes->render(gl, renderData);
glAssert(fbo->release());
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix =
Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix();
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
glAssert(gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
glAssert(gl->glActiveTexture(GL_TEXTURE0));
glAssert(gl->glBindTexture(GL_TEXTURE_2D, fbo->texture()));
quad->render(gl, renderData);
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
glAssert(glViewport(0, 0, width, height));
camera.resize(width, height);
if (fbo.get())
fbo->release();
fbo = std::unique_ptr<QOpenGLFramebufferObject>(new QOpenGLFramebufferObject(
width, height, QOpenGLFramebufferObject::CombinedDepthStencil));
qWarning() << "create fbo";
/*
glAssert(fbo->bind());
glAssert(glViewport(0, 0, width, height));
glAssert(fbo->bindDefault());
*/
}
|
Use qt opengl functions if possible.
|
Use qt opengl functions if possible.
|
C++
|
mit
|
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
|
9b9c319eeb4b2ea64f53aae9fec9e3eccc09e8b7
|
src/utils.cpp
|
src/utils.cpp
|
#include "utils.h"
//
#include <fstream> // fstream
#include <boost/tokenizer.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <numeric>
#include <algorithm>
using namespace std;
using namespace boost;
using boost::numeric::ublas::project;
using boost::numeric::ublas::range;
using boost::numeric::ublas::matrix;
// FROM runModel_v2.cpp
/////////////////////////////////////////////////////////////////////
// expect a csv file of data
void LoadData(string file, matrix<double>& M) {
ifstream in(file.c_str());
if (!in.is_open()) return;
typedef tokenizer< char_separator<char> > Tokenizer;
char_separator<char> sep(",");
string line;
int nrows = 0;
int ncols = 0;
vector<string> vec;
// get the size first
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
ncols = vec.end() - vec.begin();
nrows++;
}
cout << "num rows = "<< nrows << " num cols = " << ncols << endl;
// create a matrix to hold data
matrix<double> Data(nrows, ncols);
// make second pass
in.clear();
in.seekg(0);
int r = 0;
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
unsigned int i = 0;
for(i=0; i < vec.size() ; i++) {
Data(r, i) = ::strtod(vec[i].c_str(), 0);
}
r++;
}
M = Data;
}
bool is_almost(double val1, double val2, double precision) {
return abs(val1-val2) < precision;
}
// http://stackoverflow.com/a/11747023/1769715
vector<double> linspace(double a, double b, int n) {
vector<double> values;
double step = (b-a) / (n-1);
while(a <= b) {
values.push_back(a);
a += step;
}
return values;
}
vector<double> log_linspace(double a, double b, int n) {
vector<double> values = linspace(log(a), log(b), n);
std::transform(values.begin(), values.end(), values.begin(),
(double (*)(double))exp);
return values;
}
vector<double> std_vector_sum(vector<double> vec1, vector<double> vec2) {
assert(vec1.size()==vec2.size());
vector<double> sum_vec;
for(unsigned int i=0; i<vec1.size(); i++) {
sum_vec.push_back(vec1[i] + vec2[i]);
}
return sum_vec;
}
vector<double> std_vector_sum(vector<vector<double> > vec_vec) {
vector<double> sum_vec = vec_vec[0];
vector<vector<double> >::iterator it = vec_vec.begin();
it++;
for(; it!=vec_vec.end(); it++) {
sum_vec = std_vector_sum(sum_vec, *it);
}
return sum_vec;
}
double calc_sum_sq_deviation(vector<double> values) {
double sum = std::accumulate(values.begin(), values.end(), 0.0);
double mean = sum / values.size();
double sum_sq_deviation = 0;
for(vector<double>::iterator it = values.begin(); it!=values.end(); it++) {
sum_sq_deviation += pow((*it) - mean, 2) ;
}
return sum_sq_deviation;
}
vector<double> extract_row(const matrix<double> data, int row_idx) {
vector<double> row;
for(unsigned int j=0;j < data.size2(); j++) {
row.push_back(data(row_idx, j));
}
return row;
}
vector<double> extract_col(const matrix<double> data, int col_idx) {
vector<double> col;
for(unsigned int j=0;j < data.size1(); j++) {
col.push_back(data(j, col_idx));
}
return col;
}
vector<double> append(vector<double> vec1, vector<double> vec2) {
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
return vec1;
}
vector<int> extract_global_ordering(map<int, int> global_to_local) {
vector<int> global_indices(global_to_local.size(), -1);
map<int,int>::iterator it;
for(it=global_to_local.begin(); it!=global_to_local.end(); it++) {
int global_idx = it->first;
int local_idx = it->second;
global_indices[local_idx] = global_idx;
}
return global_indices;
}
map<int, int> construct_lookup_map(vector<int> keys) {
return construct_lookup_map(keys, create_sequence(keys.size()));
}
map<int, vector<double> > construct_data_map(const MatrixD data) {
unsigned int num_rows = data.size1();
map<int, vector<double> > data_map;
for(unsigned int row_idx=0; row_idx<num_rows; row_idx++) {
data_map[row_idx] = extract_row(data, row_idx);
}
return data_map;
}
map<int, int> remove_and_reorder(map<int, int> old_global_to_local,
int global_to_remove) {
// extract current ordering
vector<int> global_indices = extract_global_ordering(old_global_to_local);
// remove
int local_to_remove = old_global_to_local[global_to_remove];
global_indices.erase(global_indices.begin() + local_to_remove);
// constrcut and return
return construct_lookup_map(global_indices);
}
vector<int> get_indices_to_reorder(vector<int> data_global_column_indices,
map<int, int> global_to_local) {
int num_local_cols = global_to_local.size();
int num_data_cols = data_global_column_indices.size();
vector<int> reorder_indices(num_local_cols, -1);
for(int data_column_idx=0; data_column_idx<num_data_cols; data_column_idx++) {
int global_column_idx = data_global_column_indices[data_column_idx];
if(global_to_local.find(global_column_idx) != global_to_local.end()) {
int local_idx = global_to_local[data_column_idx];
reorder_indices[local_idx] = data_column_idx;
}
}
return reorder_indices;
}
vector<double> reorder_per_indices(vector<double> raw_values,
vector<int> reorder_indices) {
vector<double> arranged_values;
vector<int>::iterator it;
for(it=reorder_indices.begin(); it!=reorder_indices.end(); it++) {
int raw_value_idx = *it;
double raw_value = raw_values[raw_value_idx];
arranged_values.push_back(raw_value);
}
return arranged_values;
}
vector<double> reorder_per_map(vector<double> raw_values,
vector<int> global_column_indices,
map<int, int> global_to_local) {
vector<int> reorder_indices = \
get_indices_to_reorder(global_column_indices, global_to_local);
return reorder_per_indices(raw_values, reorder_indices);
}
vector<vector<double> > reorder_per_map(vector<vector<double> > raw_values,
vector<int> global_column_indices,
map<int, int> global_to_local) {
vector<int> reorder_indices = get_indices_to_reorder(global_column_indices, global_to_local);
vector<vector<double> > arranged_values_v;
vector<vector<double> >::iterator it;
for(it=raw_values.begin(); it!=raw_values.end(); it++) {
vector<double> arranged_values = reorder_per_indices(*it, reorder_indices);
arranged_values_v.push_back(arranged_values);
}
return arranged_values_v;
}
vector<int> create_sequence(int len, int start) {
vector<int> sequence(len, 1);
if(len==0) return sequence;
sequence[0] = start;
std::partial_sum(sequence.begin(), sequence.end(), sequence.begin());
return sequence;
}
void insert_into_counts(unsigned int draw, vector<int> &counts) {
assert(draw<=counts.size());
if(draw==counts.size()) {
counts.push_back(1);
} else {
counts[draw]++;
}
}
vector<int> draw_crp_init_counts(int num_datum, double alpha,
RandomNumberGenerator &rng) {
vector<int> counts;
double rand_u;
int draw;
int sum_counts = 0;
for(int draw_idx=0; draw_idx<num_datum; draw_idx++) {
rand_u = rng.next();
draw = numerics::crp_draw_sample(counts, sum_counts, alpha, rand_u);
sum_counts++;
insert_into_counts(draw, counts);
}
return counts;
}
vector<vector<int> > draw_crp_init(vector<int> global_row_indices,
double alpha,
RandomNumberGenerator &rng) {
int num_datum = global_row_indices.size();
vector<int> counts = draw_crp_init_counts(num_datum, alpha, rng);
std::random_shuffle(global_row_indices.begin(), global_row_indices.end());
vector<int>::iterator it = global_row_indices.begin();
vector<vector<int> > cluster_indices_v;
for(unsigned int cluster_idx=0; cluster_idx<counts.size(); cluster_idx++) {
int count = counts[cluster_idx];
vector<int> cluster_indices(count, -1);
std::copy(it, it+count, cluster_indices.begin());
cluster_indices_v.push_back(cluster_indices);
it += count;
}
return cluster_indices_v;
}
void copy_column(const MatrixD fromM, int from_col, MatrixD &toM, int to_col) {
assert(fromM.size1()==toM.size1());
int num_rows = fromM.size1();
project(toM, range(0, num_rows), range(to_col, to_col+1)) = \
project(fromM, range(0, num_rows), range(from_col, from_col+1));
}
MatrixD extract_columns(const MatrixD fromM, vector<int> from_cols) {
int num_rows = fromM.size1();
int num_cols = from_cols.size();
MatrixD toM(num_rows, num_cols);
for(int to_col=0; to_col<num_cols; to_col++) {
int from_col = from_cols[to_col];
copy_column(fromM, from_col, toM, to_col);
}
return toM;
}
int intify(std::string str) {
std::istringstream strin(str);
int str_int;
strin >> str_int;
return str_int;
}
vector<double> create_crp_alpha_grid(int n_values, int N_GRID) {
// vector<double> paramRange = linspace(0.03, .97, N_GRID/2);
// int APPEND_N = (N_GRID + 1) / 2;
// vector<double> crp_alpha_grid_append = log_linspace(1., n_values,
// APPEND_N);
// vector<double> crp_alpha_grid = append(paramRange, crp_alpha_grid_append);
vector<double> crp_alpha_grid = log_linspace(1., n_values, N_GRID);
return crp_alpha_grid;
}
void construct_continuous_base_hyper_grids(int n_grid,
int data_num_vectors,
vector<double> &r_grid,
vector<double> &nu_grid) {
// int APPEND_N = (n_grid + 1) / 2;
// //
// vector<double> paramRange = linspace(0.03, .97, n_grid/2);
// vector<double> r_grid_append = log_linspace(1., data_num_vectors,
// APPEND_N);
// vector<double> nu_grid_append = log_linspace(1., data_num_vectors/2.,
// APPEND_N);
// //
// r_grid = append(paramRange, r_grid_append);
// nu_grid = append(paramRange, nu_grid_append);
r_grid = log_linspace(1, data_num_vectors, n_grid);
nu_grid = log_linspace(1, data_num_vectors, n_grid);
}
void construct_continuous_specific_hyper_grid(int n_grid,
vector<double> col_data,
vector<double> &s_grid,
vector<double> &mu_grid) {
// int APPEND_N = (n_grid + 1) / 2;
// vector<double> paramRange = linspace(0.03, .97, n_grid/2);
// construct s grid
double sum_sq_deviation = calc_sum_sq_deviation(col_data);
// vector<double> s_grid_append = log_linspace(1., sum_sq_deviation, APPEND_N);
// s_grid = append(paramRange, s_grid_append);
s_grid = log_linspace(sum_sq_deviation / 100., sum_sq_deviation, n_grid);
// construct mu grids
double min = *std::min_element(col_data.begin(), col_data.end());
double max = *std::max_element(col_data.begin(), col_data.end());
// vector<double> mu_grid_append = linspace(min, max, APPEND_N);
// mu_grid = append(paramRange, mu_grid_append);
mu_grid = linspace(min, max, n_grid);
}
void construct_multinomial_base_hyper_grids(int n_grid,
int data_num_vectors,
vector<double> &multinomial_alpha_grid) {
// int APPEND_N = (n_grid + 1) / 2;
//
// vector<double> paramRange = linspace(0.03, .97, n_grid/2);
// vector<double> multinomial_alpha_grid_append = log_linspace(1., data_num_vectors, APPEND_N);
// multinomial_alpha_grid = append(paramRange, multinomial_alpha_grid_append);
multinomial_alpha_grid = log_linspace(1., data_num_vectors, n_grid);
}
bool is_bad_value(double value) {
return isnan(value) || !isfinite(value);
}
|
#include "utils.h"
//
#include <fstream> // fstream
#include <boost/tokenizer.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <numeric>
#include <algorithm>
using namespace std;
using namespace boost;
using boost::numeric::ublas::project;
using boost::numeric::ublas::range;
using boost::numeric::ublas::matrix;
// FROM runModel_v2.cpp
/////////////////////////////////////////////////////////////////////
// expect a csv file of data
void LoadData(string file, matrix<double>& M) {
ifstream in(file.c_str());
if (!in.is_open()) return;
typedef tokenizer< char_separator<char> > Tokenizer;
char_separator<char> sep(",");
string line;
int nrows = 0;
int ncols = 0;
vector<string> vec;
// get the size first
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
ncols = vec.end() - vec.begin();
nrows++;
}
cout << "num rows = "<< nrows << " num cols = " << ncols << endl;
// create a matrix to hold data
matrix<double> Data(nrows, ncols);
// make second pass
in.clear();
in.seekg(0);
int r = 0;
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
unsigned int i = 0;
for(i=0; i < vec.size() ; i++) {
Data(r, i) = ::strtod(vec[i].c_str(), 0);
}
r++;
}
M = Data;
}
bool is_almost(double val1, double val2, double precision) {
return abs(val1-val2) < precision;
}
// http://stackoverflow.com/a/11747023/1769715
vector<double> linspace(double a, double b, int n) {
vector<double> values;
double step = (b-a) / (n-1);
double epsilon = step * 1E-6;
while(a <= (b + epsilon)) {
values.push_back(a);
a += step;
}
return values;
}
vector<double> log_linspace(double a, double b, int n) {
vector<double> values = linspace(log(a), log(b), n);
std::transform(values.begin(), values.end(), values.begin(),
(double (*)(double))exp);
return values;
}
vector<double> std_vector_sum(vector<double> vec1, vector<double> vec2) {
assert(vec1.size()==vec2.size());
vector<double> sum_vec;
for(unsigned int i=0; i<vec1.size(); i++) {
sum_vec.push_back(vec1[i] + vec2[i]);
}
return sum_vec;
}
vector<double> std_vector_sum(vector<vector<double> > vec_vec) {
vector<double> sum_vec = vec_vec[0];
vector<vector<double> >::iterator it = vec_vec.begin();
it++;
for(; it!=vec_vec.end(); it++) {
sum_vec = std_vector_sum(sum_vec, *it);
}
return sum_vec;
}
double calc_sum_sq_deviation(vector<double> values) {
double sum = std::accumulate(values.begin(), values.end(), 0.0);
double mean = sum / values.size();
double sum_sq_deviation = 0;
for(vector<double>::iterator it = values.begin(); it!=values.end(); it++) {
sum_sq_deviation += pow((*it) - mean, 2) ;
}
return sum_sq_deviation;
}
vector<double> extract_row(const matrix<double> data, int row_idx) {
vector<double> row;
for(unsigned int j=0;j < data.size2(); j++) {
row.push_back(data(row_idx, j));
}
return row;
}
vector<double> extract_col(const matrix<double> data, int col_idx) {
vector<double> col;
for(unsigned int j=0;j < data.size1(); j++) {
col.push_back(data(j, col_idx));
}
return col;
}
vector<double> append(vector<double> vec1, vector<double> vec2) {
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
return vec1;
}
vector<int> extract_global_ordering(map<int, int> global_to_local) {
vector<int> global_indices(global_to_local.size(), -1);
map<int,int>::iterator it;
for(it=global_to_local.begin(); it!=global_to_local.end(); it++) {
int global_idx = it->first;
int local_idx = it->second;
global_indices[local_idx] = global_idx;
}
return global_indices;
}
map<int, int> construct_lookup_map(vector<int> keys) {
return construct_lookup_map(keys, create_sequence(keys.size()));
}
map<int, vector<double> > construct_data_map(const MatrixD data) {
unsigned int num_rows = data.size1();
map<int, vector<double> > data_map;
for(unsigned int row_idx=0; row_idx<num_rows; row_idx++) {
data_map[row_idx] = extract_row(data, row_idx);
}
return data_map;
}
map<int, int> remove_and_reorder(map<int, int> old_global_to_local,
int global_to_remove) {
// extract current ordering
vector<int> global_indices = extract_global_ordering(old_global_to_local);
// remove
int local_to_remove = old_global_to_local[global_to_remove];
global_indices.erase(global_indices.begin() + local_to_remove);
// constrcut and return
return construct_lookup_map(global_indices);
}
vector<int> get_indices_to_reorder(vector<int> data_global_column_indices,
map<int, int> global_to_local) {
int num_local_cols = global_to_local.size();
int num_data_cols = data_global_column_indices.size();
vector<int> reorder_indices(num_local_cols, -1);
for(int data_column_idx=0; data_column_idx<num_data_cols; data_column_idx++) {
int global_column_idx = data_global_column_indices[data_column_idx];
if(global_to_local.find(global_column_idx) != global_to_local.end()) {
int local_idx = global_to_local[data_column_idx];
reorder_indices[local_idx] = data_column_idx;
}
}
return reorder_indices;
}
vector<double> reorder_per_indices(vector<double> raw_values,
vector<int> reorder_indices) {
vector<double> arranged_values;
vector<int>::iterator it;
for(it=reorder_indices.begin(); it!=reorder_indices.end(); it++) {
int raw_value_idx = *it;
double raw_value = raw_values[raw_value_idx];
arranged_values.push_back(raw_value);
}
return arranged_values;
}
vector<double> reorder_per_map(vector<double> raw_values,
vector<int> global_column_indices,
map<int, int> global_to_local) {
vector<int> reorder_indices = \
get_indices_to_reorder(global_column_indices, global_to_local);
return reorder_per_indices(raw_values, reorder_indices);
}
vector<vector<double> > reorder_per_map(vector<vector<double> > raw_values,
vector<int> global_column_indices,
map<int, int> global_to_local) {
vector<int> reorder_indices = get_indices_to_reorder(global_column_indices, global_to_local);
vector<vector<double> > arranged_values_v;
vector<vector<double> >::iterator it;
for(it=raw_values.begin(); it!=raw_values.end(); it++) {
vector<double> arranged_values = reorder_per_indices(*it, reorder_indices);
arranged_values_v.push_back(arranged_values);
}
return arranged_values_v;
}
vector<int> create_sequence(int len, int start) {
vector<int> sequence(len, 1);
if(len==0) return sequence;
sequence[0] = start;
std::partial_sum(sequence.begin(), sequence.end(), sequence.begin());
return sequence;
}
void insert_into_counts(unsigned int draw, vector<int> &counts) {
assert(draw<=counts.size());
if(draw==counts.size()) {
counts.push_back(1);
} else {
counts[draw]++;
}
}
vector<int> draw_crp_init_counts(int num_datum, double alpha,
RandomNumberGenerator &rng) {
vector<int> counts;
double rand_u;
int draw;
int sum_counts = 0;
for(int draw_idx=0; draw_idx<num_datum; draw_idx++) {
rand_u = rng.next();
draw = numerics::crp_draw_sample(counts, sum_counts, alpha, rand_u);
sum_counts++;
insert_into_counts(draw, counts);
}
return counts;
}
vector<vector<int> > draw_crp_init(vector<int> global_row_indices,
double alpha,
RandomNumberGenerator &rng) {
int num_datum = global_row_indices.size();
vector<int> counts = draw_crp_init_counts(num_datum, alpha, rng);
std::random_shuffle(global_row_indices.begin(), global_row_indices.end());
vector<int>::iterator it = global_row_indices.begin();
vector<vector<int> > cluster_indices_v;
for(unsigned int cluster_idx=0; cluster_idx<counts.size(); cluster_idx++) {
int count = counts[cluster_idx];
vector<int> cluster_indices(count, -1);
std::copy(it, it+count, cluster_indices.begin());
cluster_indices_v.push_back(cluster_indices);
it += count;
}
return cluster_indices_v;
}
void copy_column(const MatrixD fromM, int from_col, MatrixD &toM, int to_col) {
assert(fromM.size1()==toM.size1());
int num_rows = fromM.size1();
project(toM, range(0, num_rows), range(to_col, to_col+1)) = \
project(fromM, range(0, num_rows), range(from_col, from_col+1));
}
MatrixD extract_columns(const MatrixD fromM, vector<int> from_cols) {
int num_rows = fromM.size1();
int num_cols = from_cols.size();
MatrixD toM(num_rows, num_cols);
for(int to_col=0; to_col<num_cols; to_col++) {
int from_col = from_cols[to_col];
copy_column(fromM, from_col, toM, to_col);
}
return toM;
}
int intify(std::string str) {
std::istringstream strin(str);
int str_int;
strin >> str_int;
return str_int;
}
vector<double> create_crp_alpha_grid(int n_values, int N_GRID) {
vector<double> crp_alpha_grid = log_linspace(1., n_values, N_GRID);
return crp_alpha_grid;
}
void construct_continuous_base_hyper_grids(int n_grid,
int data_num_vectors,
vector<double> &r_grid,
vector<double> &nu_grid) {
r_grid = log_linspace(1, data_num_vectors, n_grid);
nu_grid = log_linspace(1, data_num_vectors, n_grid);
}
void construct_continuous_specific_hyper_grid(int n_grid,
vector<double> col_data,
vector<double> &s_grid,
vector<double> &mu_grid) {
// construct s grid
double sum_sq_deviation = calc_sum_sq_deviation(col_data);
s_grid = log_linspace(sum_sq_deviation / 100., sum_sq_deviation, n_grid);
// construct mu grids
double min = *std::min_element(col_data.begin(), col_data.end());
double max = *std::max_element(col_data.begin(), col_data.end());
mu_grid = linspace(min, max, n_grid);
}
void construct_multinomial_base_hyper_grids(int n_grid,
int data_num_vectors,
vector<double> &multinomial_alpha_grid) {
multinomial_alpha_grid = log_linspace(1., data_num_vectors, n_grid);
}
bool is_bad_value(double value) {
return isnan(value) || !isfinite(value);
}
|
fix bug in linspace not generating correct number of values remove old commented code
|
fix bug in linspace not generating correct number of values
remove old commented code
|
C++
|
apache-2.0
|
JDReutt/BayesDB,probcomp/crosscat,probcomp/crosscat,mit-probabilistic-computing-project/crosscat,JDReutt/BayesDB,fivejjs/crosscat,poppingtonic/BayesDB,probcomp/crosscat,JDReutt/BayesDB,mit-probabilistic-computing-project/crosscat,probcomp/crosscat,mit-probabilistic-computing-project/crosscat,probcomp/crosscat,probcomp/crosscat,poppingtonic/BayesDB,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,probcomp/crosscat,poppingtonic/BayesDB,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,fivejjs/crosscat,probcomp/crosscat,poppingtonic/BayesDB,poppingtonic/BayesDB,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,JDReutt/BayesDB,fivejjs/crosscat,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,JDReutt/BayesDB
|
7048e8b0b564e7c00a621b8019b74595bd5c49d2
|
src/utils.cpp
|
src/utils.cpp
|
/*
The MIT License(MIT)
//Copyright (c) 2016-2017 Oleg Linkin <[email protected]>
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 "utils.h"
#include <tuple>
#include <QList>
#include <QRegularExpression>
#include <QtDebug>
namespace Mnemosy
{
namespace Utils
{
void SetImagesWidth(QString& text, bool& hasArg)
{
QRegularExpression imgRxp("\\<img.*?src\\s*=\\s*('|\")(.+?)('|\").*?\\/\\>",
QRegularExpression::CaseInsensitiveOption);
QList<QPair<QString, QString>> matched;
QRegularExpressionMatchIterator matchIt = imgRxp.globalMatch(text);
while (matchIt.hasNext())
{
QRegularExpressionMatch match = matchIt.next();
const auto& imgTag = match.captured(0);
if (!imgTag.contains("l-stat.livejournal.net"))
{
matched << QPair<QString, QString>(imgTag, match.captured(2));
}
}
for (const auto& t : matched)
{
text.replace (t.first,
"<img src=\"" + t.second + QString("\" width=\"%1\" >"));
if (!hasArg)
{
hasArg = true;
}
}
}
void MoveFirstImageToTheTop(QString& text)
{
QRegularExpression imgRxp("(\\<img[\\w\\W]+?\\/?\\>)",
QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = imgRxp.match(text);
if (match.hasMatch())
{
QString matched = match.captured(0);
text.remove(match.capturedStart(0), match.capturedLength(0));
text.push_front(matched);
}
}
void RemoveStyleTag(QString& text)
{
QRegularExpression styleRxp ("style=\"(.+?)\"",
QRegularExpression::CaseInsensitiveOption);
text.remove(styleRxp);
}
void FixUntaggedUrls(QString& text)
{
auto pattern = "(?<!='|\")((http|ftp|https):\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)";
QRegularExpression untaggedUrlRxp(pattern, QRegularExpression::CaseInsensitiveOption);
text.replace(untaggedUrlRxp, "<a href=\"\\1\">\\1</a>");
}
void TryToFillEventFields(LJEvent& event)
{
if (!event.GetPosterID() && !event.GetPosterPicUrl().isEmpty())
{
QString url = event.GetPosterPicUrl().toString();
event.SetPosterID(url.mid(url.lastIndexOf("/") + 1)
.toLongLong());
}
if (event.GetPosterName().isEmpty())
{
QString url = event.GetUrl().toString();
QString name = url.mid(7, url.indexOf(".") - 7);
name.replace('-', "_");
event.SetPosterName(name);
}
}
QString AccessToString(Access acc)
{
switch (acc)
{
case APrivate:
return "private";
case APublic:
return "public";
case ACustom:
default:
return "usemask";
}
}
QString AdultContentToString(AdultContent ac)
{
switch (ac)
{
case ACAdultsFrom14:
return "concepts";
case ACAdultsFrom18:
return "explicit";
case ACWithoutAdultContent:
default:
return "none";
}
}
QString ScreeningToString(CommentsManagement cm)
{
switch (cm)
{
case CMShowFriendsComments:
return "F";
case CMScreenComments:
return "A";
case CMScreenAnonymouseComments:
return "R";
case CMScreenNotFromFriendsWithLinks:
return "L";
case CMShowComments:
default:
return "N";
}
}
}
} // namespace Mnemosy
|
/*
The MIT License(MIT)
//Copyright (c) 2016-2017 Oleg Linkin <[email protected]>
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 "utils.h"
#include <tuple>
#include <QList>
#include <QRegularExpression>
#include <QtDebug>
namespace Mnemosy
{
namespace Utils
{
void SetImagesWidth(QString& text, bool& hasArg)
{
QRegularExpression imgRxp("\\<img.*?src\\s*=\\s*('|\")(.+?)('|\").*?\\>",
QRegularExpression::CaseInsensitiveOption);
QList<QPair<QString, QString>> matched;
QRegularExpressionMatchIterator matchIt = imgRxp.globalMatch(text);
while (matchIt.hasNext())
{
QRegularExpressionMatch match = matchIt.next();
const auto& imgTag = match.captured(0);
if (!imgTag.contains("l-stat.livejournal.net"))
{
matched << QPair<QString, QString>(imgTag, match.captured(2));
}
}
for (const auto& t : matched)
{
text.replace (t.first,
"<img src=\"" + t.second + QString("\" width=\"%1\" >"));
if (!hasArg)
{
hasArg = true;
}
}
}
void MoveFirstImageToTheTop(QString& text)
{
QRegularExpression imgRxp("(\\<img[\\w\\W]+?\\/?\\>)",
QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = imgRxp.match(text);
if (match.hasMatch())
{
QString matched = match.captured(0);
text.remove(match.capturedStart(0), match.capturedLength(0));
text.push_front(matched);
}
}
void RemoveStyleTag(QString& text)
{
QRegularExpression styleRxp ("style=\"(.+?)\"",
QRegularExpression::CaseInsensitiveOption);
text.remove(styleRxp);
}
void FixUntaggedUrls(QString& text)
{
auto pattern = "(?<!='|\")((http|ftp|https):\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?)";
QRegularExpression untaggedUrlRxp(pattern, QRegularExpression::CaseInsensitiveOption);
text.replace(untaggedUrlRxp, "<a href=\"\\1\">\\1</a>");
}
void TryToFillEventFields(LJEvent& event)
{
if (!event.GetPosterID() && !event.GetPosterPicUrl().isEmpty())
{
QString url = event.GetPosterPicUrl().toString();
event.SetPosterID(url.mid(url.lastIndexOf("/") + 1)
.toLongLong());
}
if (event.GetPosterName().isEmpty())
{
QString url = event.GetUrl().toString();
QString name = url.mid(7, url.indexOf(".") - 7);
name.replace('-', "_");
event.SetPosterName(name);
}
}
QString AccessToString(Access acc)
{
switch (acc)
{
case APrivate:
return "private";
case APublic:
return "public";
case ACustom:
default:
return "usemask";
}
}
QString AdultContentToString(AdultContent ac)
{
switch (ac)
{
case ACAdultsFrom14:
return "concepts";
case ACAdultsFrom18:
return "explicit";
case ACWithoutAdultContent:
default:
return "none";
}
}
QString ScreeningToString(CommentsManagement cm)
{
switch (cm)
{
case CMShowFriendsComments:
return "F";
case CMScreenComments:
return "A";
case CMScreenAnonymouseComments:
return "R";
case CMScreenNotFromFriendsWithLinks:
return "L";
case CMShowComments:
default:
return "N";
}
}
}
} // namespace Mnemosy
|
Fix img width setter
|
Fix img width setter
|
C++
|
mit
|
Maledictus/harbour-mnemosy,Maledictus/harbour-mnemosy
|
6dc7c2389aeea1ab1ded7e3e1fef16fa764775d8
|
src/write.cpp
|
src/write.cpp
|
#include <fstream>
#include <string>
#include <type_traits>
#include <variant>
#include <boost/hana/functional/overload.hpp>
#include <tmxpp.hpp>
#include <tmxpp/exceptions.hpp>
#include <tmxpp/impl/Xml.hpp>
#include <tmxpp/impl/tmx_info.hpp>
#include <tmxpp/impl/write_utility.hpp>
namespace tmxpp {
namespace impl {
namespace {
using namespace tmx_info;
template <class Number>
void write(Size<Number> sz, Xml::Element elem)
{
add(elem, size_width, sz.w);
add(elem, size_height, sz.h);
}
void write_tile(pxSize sz, Xml::Element elem)
{
add(elem, tile_size_width, sz.w);
add(elem, tile_size_height, sz.h);
}
// Properties ------------------------------------------------------------------
void write(const Property::Value& value, Xml::Element prop)
{
auto add = [=](Xml::Attribute::Value alternative, auto value) {
prop.add(property_alternative, alternative);
impl::add(prop, property_value, value);
};
std::visit(
boost::hana::overload(
[=](int i) { add(property_alternative_int, i); },
[=](double d) { add(property_alternative_double, d); },
[=](bool b) {
add(property_alternative_bool,
get(b ? property_value_true : property_value_false));
},
[=](Color c) { add(property_alternative_color, c); },
[=](File f) { add(property_alternative_file, f.string()); },
[=](const std::string& s) {
prop.add(property_alternative, property_alternative_string);
if (bool is_multiline{s.find('\n') != std::string::npos})
prop.value(Xml::Element::Value{s});
else
impl::add(prop, property_value, s);
}),
value);
}
void write(const Property& p, Xml::Element elem)
{
add(elem, property_name, p.name);
write(p.value, elem);
}
void write(const Properties& ps, Xml::Element parent)
{
if (ps.empty())
return;
auto elem{parent.add(properties)};
for (const auto& p : ps)
write(p, elem.add(property));
}
// Image -----------------------------------------------------------------------
void write(const Image& img, Xml::Element elem)
{
add(elem, image_source, img.source.string());
if (auto trans{img.transparent})
add(elem, image_transparent, *trans);
if (auto sz{img.size})
write(*sz, elem);
}
// Animation -------------------------------------------------------------------
void write(Frame f, Xml::Element elem)
{
add(elem, frame_local_id, f.local_id);
add(elem, frame_duration, f.duration.count());
}
void write(const Animation& anim, Xml::Element parent)
{
if (anim.empty())
return;
auto elem{parent.add(animation)};
for (const auto& f : anim)
write(f, elem.add(frame));
}
// Map::Tile_set ---------------------------------------------------------------
void write_tile(Offset o, Xml::Element parent)
{
if (o == Offset{})
return;
auto elem{parent.add(tile_offset)};
add(elem, tile_offset_x, o.x);
add(elem, tile_offset_y, o.y);
}
template <class Tile>
std::enable_if_t<
std::is_same_v<Tile, Tile_set::Tile> ||
std::is_same_v<Tile, Image_collection::Tile>>
write(const Tile& tile, Xml::Element elem)
{
add(elem, tile_set_tile_local_id, tile.local_id);
write(tile.properties, elem);
if
constexpr(std::is_same_v<Tile, Image_collection::Tile>)
write(tile.image, elem.add(image));
// if (auto cs{tile.collision_shape})
// write(*cs, elem.add(object_layer));
write(tile.animation, elem);
}
template <class Tiles>
std::enable_if_t<
std::is_same_v<Tiles, Tile_set::Tiles> ||
std::is_same_v<Tiles, Image_collection::Tiles>>
write(const Tiles& ts, Xml::Element parent)
{
if (ts.empty())
return;
for (const auto& t : ts)
write(t, parent.add(tile_set_tile));
}
template <class Tset>
void map_tile_set_visitor(const Tset& ts, Xml::Element elem)
{
add(elem, tile_set_first_global_id, ts.first_global_id);
if (!ts.tsx.empty())
add(elem, tile_set_tsx, ts.tsx.string());
add(elem, tile_set_name, ts.name);
if
constexpr(std::is_same_v<Tset, Tile_set>)
{
write_tile(ts.tile_size, elem);
if (ts.spacing != Pixel{0})
add(elem, tile_set_spacing, ts.spacing);
if (ts.margin != Pixel{0})
add(elem, tile_set_margin, ts.margin);
add(elem, tile_set_tile_count, ts.size.w * ts.size.h);
add(elem, tile_set_columns, ts.size.w);
}
else {
write_tile(ts.max_tile_size, elem);
add(elem, tile_set_tile_count, ts.tile_count);
add(elem, tile_set_columns, ts.columns);
};
write_tile(ts.tile_offset, elem);
write(ts.properties, elem);
if
constexpr(std::is_same_v<Tset, Tile_set>)
write(ts.image, elem.add(image));
write(ts.tiles, elem);
}
void write(const Map::Tile_set& ts, Xml::Element elem)
{
std::visit([elem](const auto& ts) { map_tile_set_visitor(ts, elem); }, ts);
}
// Map::Layer ------------------------------------------------------------------
void write(Object_layer::Draw_order do_, Xml::Element layer)
{
layer.add(object_layer_draw_order, [do_] {
switch (do_) {
case Object_layer::Draw_order::top_down:
return object_layer_draw_order_top_down;
case Object_layer::Draw_order::index:
return object_layer_draw_order_index;
default: throw Exception{""};
}
}());
}
void write(Offset o, Xml::Element layer)
{
if (o == Offset{})
return;
add(layer, offset_x, o.x);
add(layer, offset_y, o.y);
}
template <class Layer>
void layer_visitor(const Layer& l, Xml::Element elem)
{
// clang-format off
if constexpr(std::is_same_v<Layer, Object_layer>) {
if (auto c{l.color})
add(elem, object_layer_color, *c);
write(l.draw_order, elem);
}
add(elem, layer_name, l.name);
if (l.opacity != Unit_interval{1})
add(elem, layer_opacity, l.opacity);
if (!l.visible)
add(elem, layer_visible, "0");
write(l.offset, elem);
if constexpr(std::is_same_v<Layer, Image_layer>)
if (auto img{l.image})
write(*img, elem.add(image));
write(l.properties, elem);
// clang-format on
}
void write(const Map::Layer& l, Xml::Element map)
{
std::visit(
[map](const auto& l) {
auto elem{map.add([] {
using Layer = std::decay_t<decltype(l)>;
// clang-format off
if constexpr(std::is_same_v<Layer, Tile_layer>)
return tile_layer;
if constexpr(std::is_same_v<Layer, Object_layer>)
return object_layer;
if constexpr(std::is_same_v<Layer, Image_layer>)
return image_layer;
// clang-format on
}())};
layer_visitor(l, elem);
},
l);
}
// Map -------------------------------------------------------------------------
void write(Map::Render_order ro, Xml::Element map)
{
map.add(map_render_order, [ro] {
switch (ro) {
case Map::Render_order::right_down: return map_render_order_right_down;
case Map::Render_order::right_up: return map_render_order_right_up;
case Map::Render_order::left_down: return map_render_order_left_down;
case Map::Render_order::left_up: return map_render_order_left_up;
default: throw Exception{""};
}
}());
}
void write(Map::Staggered::Axis a, Xml::Element map)
{
map.add(map_staggered_axis, [a] {
switch (a) {
case Map::Staggered::Axis::x: return map_staggered_axis_x;
case Map::Staggered::Axis::y: return map_staggered_axis_y;
default: throw Exception{""};
}
}());
}
void write(Map::Staggered::Index i, Xml::Element map)
{
map.add(map_staggered_index, [i] {
switch (i) {
case Map::Staggered::Index::even: return map_staggered_index_even;
case Map::Staggered::Index::odd: return map_staggered_index_odd;
default: throw Exception{""};
}
}());
}
void write(Map::Staggered s, Xml::Element map)
{
write(s.axis, map);
write(s.index, map);
}
void write(Map::Hexagonal h, Xml::Element map)
{
add(map, map_hexagonal_side_legth, h.side_length);
write(static_cast<Map::Staggered>(h), map);
}
void write(
Map::Orientation orient, Map::Render_order render_order, Xml::Element map)
{
auto add = [=](Xml::Attribute::Value orient) {
map.add(map_orientation, orient);
write(render_order, map);
};
std::visit(
boost::hana::overload(
[=](Map::Orthogonal) { add(map_orthogonal); },
[=](Map::Isometric) { add(map_isometric); },
[=](Map::Staggered s) {
add(map_staggered);
write(s, map);
},
[=](Map::Hexagonal h) {
add(map_hexagonal);
write(h, map);
}),
orient);
}
void write(const Map::Tile_sets& tses, Xml::Element map)
{
for (const auto& ts : tses)
write(ts, map.add(tile_set));
}
void write(const Map::Layers& ls, Xml::Element map)
{
for (const auto& l : ls)
write(l, map);
}
void write(const Map& map, Xml::Element elem)
{
add(elem, map_version, map.version);
write(map.orientation, map.render_order, elem);
write(map.size, elem);
write_tile(map.general_tile_size, elem);
if (auto bg{map.background})
add(elem, map_background, *bg);
add(elem, map_next_unique_id, map.next_unique_id);
write(map.properties, elem);
write(map.tile_sets, elem);
write(map.layers, elem);
}
} // namespace
} // namespace impl
void write(const Map& map, gsl::not_null<gsl::czstring<>> path)
{
impl::Xml tmx{impl::tmx_info::map};
impl::write(map, tmx.root());
std::ofstream{path} << tmx;
}
void write(const Map::Tile_set&);
void write(const Tile_set&);
void write(const Image_collection&);
} // namespace tmxpp
|
#include <fstream>
#include <string>
#include <type_traits>
#include <variant>
#include <boost/hana/functional/overload.hpp>
#include <tmxpp.hpp>
#include <tmxpp/exceptions.hpp>
#include <tmxpp/impl/Xml.hpp>
#include <tmxpp/impl/tmx_info.hpp>
#include <tmxpp/impl/write_utility.hpp>
namespace tmxpp {
namespace impl {
namespace {
using namespace tmx_info;
template <class Number>
void write(Size<Number> sz, Xml::Element elem)
{
add(elem, size_width, sz.w);
add(elem, size_height, sz.h);
}
void write_tile(pxSize sz, Xml::Element elem)
{
add(elem, tile_size_width, sz.w);
add(elem, tile_size_height, sz.h);
}
// Properties ------------------------------------------------------------------
void write(const Property::Value& value, Xml::Element prop)
{
auto add = [=](Xml::Attribute::Value alternative, auto value) {
prop.add(property_alternative, alternative);
impl::add(prop, property_value, value);
};
std::visit(
boost::hana::overload(
[=](int i) { add(property_alternative_int, i); },
[=](double d) { add(property_alternative_double, d); },
[=](bool b) {
add(property_alternative_bool,
get(b ? property_value_true : property_value_false));
},
[=](Color c) { add(property_alternative_color, c); },
[=](File f) { add(property_alternative_file, f.string()); },
[=](const std::string& s) {
prop.add(property_alternative, property_alternative_string);
if (bool is_multiline{s.find('\n') != std::string::npos})
prop.value(Xml::Element::Value{s});
else
impl::add(prop, property_value, s);
}),
value);
}
void write(const Property& p, Xml::Element elem)
{
add(elem, property_name, p.name);
write(p.value, elem);
}
void write(const Properties& ps, Xml::Element parent)
{
if (ps.empty())
return;
auto elem{parent.add(properties)};
for (const auto& p : ps)
write(p, elem.add(property));
}
// Image -----------------------------------------------------------------------
void write(const Image& img, Xml::Element elem)
{
add(elem, image_source, img.source.string());
if (auto trans{img.transparent})
add(elem, image_transparent, *trans);
if (auto sz{img.size})
write(*sz, elem);
}
// Animation -------------------------------------------------------------------
void write(Frame f, Xml::Element elem)
{
add(elem, frame_local_id, f.local_id);
add(elem, frame_duration, f.duration.count());
}
void write(const Animation& anim, Xml::Element parent)
{
if (anim.empty())
return;
auto elem{parent.add(animation)};
for (const auto& f : anim)
write(f, elem.add(frame));
}
// Map::Tile_set ---------------------------------------------------------------
void write_tile(Offset o, Xml::Element parent)
{
if (o == Offset{})
return;
auto elem{parent.add(tile_offset)};
add(elem, tile_offset_x, o.x);
add(elem, tile_offset_y, o.y);
}
template <class Tile>
std::enable_if_t<
std::is_same_v<Tile, Tile_set::Tile> ||
std::is_same_v<Tile, Image_collection::Tile>>
write(const Tile& tile, Xml::Element elem)
{
add(elem, tile_set_tile_local_id, tile.local_id);
write(tile.properties, elem);
// clang-format off
if constexpr (std::is_same_v<Tile, Image_collection::Tile>)
write(tile.image, elem.add(image));
// clang-format on
// if (auto cs{tile.collision_shape})
// write(*cs, elem.add(object_layer));
write(tile.animation, elem);
}
template <class Tiles>
std::enable_if_t<
std::is_same_v<Tiles, Tile_set::Tiles> ||
std::is_same_v<Tiles, Image_collection::Tiles>>
write(const Tiles& ts, Xml::Element parent)
{
if (ts.empty())
return;
for (const auto& t : ts)
write(t, parent.add(tile_set_tile));
}
template <class Tset>
void map_tile_set_visitor(const Tset& ts, Xml::Element elem)
{
add(elem, tile_set_first_global_id, ts.first_global_id);
if (!ts.tsx.empty())
add(elem, tile_set_tsx, ts.tsx.string());
add(elem, tile_set_name, ts.name);
// clang-format off
if constexpr (std::is_same_v<Tset, Tile_set>) {
write_tile(ts.tile_size, elem);
if (ts.spacing != Pixel{0})
add(elem, tile_set_spacing, ts.spacing);
if (ts.margin != Pixel{0})
add(elem, tile_set_margin, ts.margin);
add(elem, tile_set_tile_count, ts.size.w * ts.size.h);
add(elem, tile_set_columns, ts.size.w);
}
else {
write_tile(ts.max_tile_size, elem);
add(elem, tile_set_tile_count, ts.tile_count);
add(elem, tile_set_columns, ts.columns);
};
write_tile(ts.tile_offset, elem);
write(ts.properties, elem);
if constexpr (std::is_same_v<Tset, Tile_set>)
write(ts.image, elem.add(image));
// clang-format on
write(ts.tiles, elem);
}
void write(const Map::Tile_set& ts, Xml::Element elem)
{
std::visit([elem](const auto& ts) { map_tile_set_visitor(ts, elem); }, ts);
}
// Map::Layer ------------------------------------------------------------------
void write(Object_layer::Draw_order do_, Xml::Element layer)
{
layer.add(object_layer_draw_order, [do_] {
switch (do_) {
case Object_layer::Draw_order::top_down:
return object_layer_draw_order_top_down;
case Object_layer::Draw_order::index:
return object_layer_draw_order_index;
default: throw Exception{""};
}
}());
}
void write(Offset o, Xml::Element layer)
{
if (o == Offset{})
return;
add(layer, offset_x, o.x);
add(layer, offset_y, o.y);
}
template <class Layer>
void layer_visitor(const Layer& l, Xml::Element elem)
{
// clang-format off
if constexpr (std::is_same_v<Layer, Object_layer>) {
if (auto c{l.color})
add(elem, object_layer_color, *c);
write(l.draw_order, elem);
}
add(elem, layer_name, l.name);
if (l.opacity != Unit_interval{1})
add(elem, layer_opacity, l.opacity);
if (!l.visible)
add(elem, layer_visible, "0");
write(l.offset, elem);
if constexpr (std::is_same_v<Layer, Image_layer>)
if (auto img{l.image})
write(*img, elem.add(image));
write(l.properties, elem);
// clang-format on
}
void write(const Map::Layer& l, Xml::Element map)
{
std::visit(
[map](const auto& l) {
auto elem{map.add([] {
using Layer = std::decay_t<decltype(l)>;
// clang-format off
if constexpr (std::is_same_v<Layer, Tile_layer>)
return tile_layer;
if constexpr (std::is_same_v<Layer, Object_layer>)
return object_layer;
if constexpr (std::is_same_v<Layer, Image_layer>)
return image_layer;
// clang-format on
}())};
layer_visitor(l, elem);
},
l);
}
// Map -------------------------------------------------------------------------
void write(Map::Render_order ro, Xml::Element map)
{
map.add(map_render_order, [ro] {
switch (ro) {
case Map::Render_order::right_down: return map_render_order_right_down;
case Map::Render_order::right_up: return map_render_order_right_up;
case Map::Render_order::left_down: return map_render_order_left_down;
case Map::Render_order::left_up: return map_render_order_left_up;
default: throw Exception{""};
}
}());
}
void write(Map::Staggered::Axis a, Xml::Element map)
{
map.add(map_staggered_axis, [a] {
switch (a) {
case Map::Staggered::Axis::x: return map_staggered_axis_x;
case Map::Staggered::Axis::y: return map_staggered_axis_y;
default: throw Exception{""};
}
}());
}
void write(Map::Staggered::Index i, Xml::Element map)
{
map.add(map_staggered_index, [i] {
switch (i) {
case Map::Staggered::Index::even: return map_staggered_index_even;
case Map::Staggered::Index::odd: return map_staggered_index_odd;
default: throw Exception{""};
}
}());
}
void write(Map::Staggered s, Xml::Element map)
{
write(s.axis, map);
write(s.index, map);
}
void write(Map::Hexagonal h, Xml::Element map)
{
add(map, map_hexagonal_side_legth, h.side_length);
write(static_cast<Map::Staggered>(h), map);
}
void write(
Map::Orientation orient, Map::Render_order render_order, Xml::Element map)
{
auto add = [=](Xml::Attribute::Value orient) {
map.add(map_orientation, orient);
write(render_order, map);
};
std::visit(
boost::hana::overload(
[=](Map::Orthogonal) { add(map_orthogonal); },
[=](Map::Isometric) { add(map_isometric); },
[=](Map::Staggered s) {
add(map_staggered);
write(s, map);
},
[=](Map::Hexagonal h) {
add(map_hexagonal);
write(h, map);
}),
orient);
}
void write(const Map::Tile_sets& tses, Xml::Element map)
{
for (const auto& ts : tses)
write(ts, map.add(tile_set));
}
void write(const Map::Layers& ls, Xml::Element map)
{
for (const auto& l : ls)
write(l, map);
}
void write(const Map& map, Xml::Element elem)
{
add(elem, map_version, map.version);
write(map.orientation, map.render_order, elem);
write(map.size, elem);
write_tile(map.general_tile_size, elem);
if (auto bg{map.background})
add(elem, map_background, *bg);
add(elem, map_next_unique_id, map.next_unique_id);
write(map.properties, elem);
write(map.tile_sets, elem);
write(map.layers, elem);
}
} // namespace
} // namespace impl
void write(const Map& map, gsl::not_null<gsl::czstring<>> path)
{
impl::Xml tmx{impl::tmx_info::map};
impl::write(map, tmx.root());
std::ofstream{path} << tmx;
}
void write(const Map::Tile_set&);
void write(const Tile_set&);
void write(const Image_collection&);
} // namespace tmxpp
|
Reformat if constexpr
|
Reformat if constexpr
|
C++
|
unlicense
|
johelegp/tmxpp
|
b8fdbc94a7defaa5b4b0ec43f59bccf2e71cadd3
|
folly/net/detail/SocketFileDescriptorMap.cpp
|
folly/net/detail/SocketFileDescriptorMap.cpp
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/net/detail/SocketFileDescriptorMap.h>
#ifdef _WIN32
#include <shared_mutex>
#include <unordered_map>
#include <fcntl.h>
// We need this, but it's only defined for kernel drivers :(
#define STATUS_HANDLE_NOT_CLOSABLE 0xC0000235L
namespace folly {
namespace netops {
namespace detail {
static std::unordered_map<SOCKET, int> socketMap;
static std::shared_mutex socketMapMutex;
static int closeOnlyFileDescriptor(int fd) {
HANDLE h = (HANDLE)_get_osfhandle(fd);
// If we were to just call _close on the descriptor, it would
// close the HANDLE, but it wouldn't free any of the resources
// associated to the SOCKET, and we can't call _close after
// calling closesocket, because closesocket has already closed
// the HANDLE, and _close would attempt to close the HANDLE
// again, resulting in a double free.
// We can however protect the HANDLE from actually being closed
// long enough to close the file descriptor, then close the
// socket itself.
constexpr DWORD protectFlag = HANDLE_FLAG_PROTECT_FROM_CLOSE;
DWORD handleFlags = 0;
if (!GetHandleInformation(h, &handleFlags)) {
return -1;
}
if (!SetHandleInformation(h, protectFlag, protectFlag)) {
return -1;
}
int c = 0;
__try {
// We expect this to fail. It still closes the file descriptor though.
c = ::_close(fd);
// We just have to catch the SEH exception that gets thrown when we do
// this with a debugger attached -_-....
} __except (
GetExceptionCode() == STATUS_HANDLE_NOT_CLOSABLE
? EXCEPTION_CONTINUE_EXECUTION
: EXCEPTION_CONTINUE_SEARCH) {
// We told it to continue execution, so nothing here would
// be run anyways.
}
// We're at the core, we don't get the luxery of SCOPE_EXIT because
// of circular dependencies.
if (!SetHandleInformation(h, protectFlag, handleFlags)) {
return -1;
}
if (c != -1) {
return -1;
}
return 0;
}
int SocketFileDescriptorMap::close(int fd) noexcept {
auto hand = SocketFileDescriptorMap::fdToSocket(fd);
{
std::unique_lock<std::shared_mutex> lock{socketMapMutex};
if (socketMap.find(hand) != socketMap.end()) {
socketMap.erase(hand);
}
}
auto r = closeOnlyFileDescriptor(fd);
if (r != 0) {
return r;
}
return closesocket((SOCKET)hand);
}
int SocketFileDescriptorMap::close(SOCKET sock) noexcept {
bool found = false;
int fd = 0;
{
std::unique_lock<std::shared_mutex> lock{socketMapMutex};
auto lookup = socketMap.find(sock);
found = lookup != socketMap.end();
if (found) {
fd = lookup->second;
}
}
if (found) {
return SocketFileDescriptorMap::close(fd);
}
return closesocket(sock);
}
SOCKET SocketFileDescriptorMap::fdToSocket(int fd) noexcept {
if (fd == -1) {
return INVALID_SOCKET;
}
return (SOCKET)_get_osfhandle(fd);
}
int SocketFileDescriptorMap::socketToFd(SOCKET sock) noexcept {
if (sock == INVALID_SOCKET) {
return -1;
}
{
std::shared_lock<std::shared_mutex> lock{socketMapMutex};
auto const found = socketMap.find(sock);
if (found != socketMap.end()) {
return found->second;
}
}
std::unique_lock<std::shared_mutex> lock{socketMapMutex};
auto const found = socketMap.find(sock);
if (found != socketMap.end()) {
return found->second;
}
int fd = _open_osfhandle((intptr_t)sock, O_RDWR | O_BINARY);
socketMap.emplace(sock, fd);
return fd;
}
} // namespace detail
} // namespace netops
} // namespace folly
#elif defined(__XROS__) || defined(__EMSCRIPTEN__)
// Stub this out for now.
#include <stdexcept>
namespace folly {
namespace netops {
namespace detail {
int SocketFileDescriptorMap::close(int fd) noexcept {
throw std::logic_error("Not implemented!");
}
int SocketFileDescriptorMap::close(void* sock) noexcept {
throw std::logic_error("Not implemented!");
}
void* SocketFileDescriptorMap::fdToSocket(int fd) noexcept {
throw std::logic_error("Not implemented!");
}
int SocketFileDescriptorMap::socketToFd(void* sock) noexcept {
throw std::logic_error("Not implemented!");
}
} // namespace detail
} // namespace netops
} // namespace folly
#endif
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/net/detail/SocketFileDescriptorMap.h>
#ifdef _WIN32
#include <shared_mutex>
#include <unordered_map>
#include <fcntl.h>
// We need this, but it's only defined for kernel drivers :(
#define STATUS_HANDLE_NOT_CLOSABLE 0xC0000235L
namespace folly {
namespace netops {
namespace detail {
static std::unordered_map<SOCKET, int> socketMap;
static std::shared_mutex socketMapMutex;
static int closeOnlyFileDescriptor(int fd) {
HANDLE h = (HANDLE)_get_osfhandle(fd);
// If we were to just call _close on the descriptor, it would
// close the HANDLE, but it wouldn't free any of the resources
// associated to the SOCKET, and we can't call _close after
// calling closesocket, because closesocket has already closed
// the HANDLE, and _close would attempt to close the HANDLE
// again, resulting in a double free.
// We can however protect the HANDLE from actually being closed
// long enough to close the file descriptor, then close the
// socket itself.
constexpr DWORD protectFlag = HANDLE_FLAG_PROTECT_FROM_CLOSE;
DWORD handleFlags = 0;
if (!GetHandleInformation(h, &handleFlags)) {
return -1;
}
if (!SetHandleInformation(h, protectFlag, protectFlag)) {
return -1;
}
int c = 0;
__try {
// We expect this to fail. It still closes the file descriptor though.
c = ::_close(fd);
// We just have to catch the SEH exception that gets thrown when we do
// this with a debugger attached -_-....
} __except (
GetExceptionCode() == STATUS_HANDLE_NOT_CLOSABLE
? EXCEPTION_CONTINUE_EXECUTION
: EXCEPTION_CONTINUE_SEARCH) {
// We told it to continue execution, so nothing here would
// be run anyways.
}
// We're at the core, we don't get the luxery of SCOPE_EXIT because
// of circular dependencies.
if (!SetHandleInformation(h, protectFlag, handleFlags)) {
return -1;
}
if (c != -1) {
return -1;
}
return 0;
}
int SocketFileDescriptorMap::close(int fd) noexcept {
auto hand = SocketFileDescriptorMap::fdToSocket(fd);
{
std::unique_lock<std::shared_mutex> lock{socketMapMutex};
if (socketMap.find(hand) != socketMap.end()) {
socketMap.erase(hand);
}
}
auto r = closeOnlyFileDescriptor(fd);
if (r != 0) {
return r;
}
return closesocket((SOCKET)hand);
}
int SocketFileDescriptorMap::close(SOCKET sock) noexcept {
bool found = false;
int fd = 0;
{
std::unique_lock<std::shared_mutex> lock{socketMapMutex};
auto lookup = socketMap.find(sock);
found = lookup != socketMap.end();
if (found) {
fd = lookup->second;
}
}
if (found) {
return SocketFileDescriptorMap::close(fd);
}
return closesocket(sock);
}
SOCKET SocketFileDescriptorMap::fdToSocket(int fd) noexcept {
if (fd == -1) {
return INVALID_SOCKET;
}
return (SOCKET)_get_osfhandle(fd);
}
int SocketFileDescriptorMap::socketToFd(SOCKET sock) noexcept {
if (sock == INVALID_SOCKET) {
return -1;
}
{
std::shared_lock<std::shared_mutex> lock{socketMapMutex};
auto const found = socketMap.find(sock);
if (found != socketMap.end()) {
return found->second;
}
}
std::unique_lock<std::shared_mutex> lock{socketMapMutex};
auto const found = socketMap.find(sock);
if (found != socketMap.end()) {
return found->second;
}
int fd = _open_osfhandle((intptr_t)sock, O_RDWR | O_BINARY);
socketMap.emplace(sock, fd);
return fd;
}
} // namespace detail
} // namespace netops
} // namespace folly
#elif defined(__XROS__) || defined(__EMSCRIPTEN__)
// Stub this out for now.
#include <stdexcept>
namespace folly {
namespace netops {
namespace detail {
int SocketFileDescriptorMap::close(int fd) noexcept {
std::terminate();
}
int SocketFileDescriptorMap::close(void* sock) noexcept {
std::terminate();
}
void* SocketFileDescriptorMap::fdToSocket(int fd) noexcept {
std::terminate();
}
int SocketFileDescriptorMap::socketToFd(void* sock) noexcept {
std::terminate();
}
} // namespace detail
} // namespace netops
} // namespace folly
#endif
|
Fix stub of sockets for EMSCRIPTEN and XROS
|
Fix stub of sockets for EMSCRIPTEN and XROS
Summary:
The current implementation of function stubs in `SocketFileDescriptorMap.cpp` generates the following build errors:
```
stderr: xplat/folly/net/detail/SocketFileDescriptorMap.cpp:171:3: error: 'socketToFd' has a non-throwing exception specification but can still throw [-Werror,-Wexceptions]
throw std::logic_error("Not implemented!");
^
xplat/folly/net/detail/SocketFileDescriptorMap.cpp:170:30: note: function declared non-throwing here
int SocketFileDescriptorMap::socketToFd(void* sock) noexcept {
```
because the methods are stubbed out to throw and exception even though they are marked as `noexcept`.
To fix the warning the subbing implementation is changed to call `std::terminate()` instead of throwing an exception. According to the language specification (https://en.cppreference.com/w/cpp/language/noexcept_spec) this should not result in any change in run-time behavior, since throwing and exception in a method marked as `noexcept` is effectively a call to `std::terminate()`.
Differential Revision: D29687674
fbshipit-source-id: 77405d8a31e45c8836e8746c9b25e12ef06335c4
|
C++
|
apache-2.0
|
facebook/folly,facebook/folly,facebook/folly,facebook/folly,facebook/folly
|
d9cf74fd33708c2c4fd8bf5214b45889688b03cc
|
ConcurrentQueues/test/concurrent_queue_test.cpp
|
ConcurrentQueues/test/concurrent_queue_test.cpp
|
#include "concurrent_queue_test.h"
#include <iostream>
#include <chrono>
#include <type_traits>
#include <queue>
using ::testing::Values;
using ::testing::Combine;
using ::testing::Types;
using std::cout;
using std::endl;
std::ostream& operator<<(std::ostream& os, const std::chrono::duration<double>& t) {
double val;
if ((val = std::chrono::duration<double>(t).count()) > 1.0){
os << val << " seconds";
}
else if ((val = std::chrono::duration<double, std::milli>(t).count()) > 1.0){
os << val << " milliseconds";
}
else if ((val = std::chrono::duration<double, std::micro>(t).count()) > 1.0){
os << val << " microseconds";
}
else{
val = std::chrono::duration<double, std::nano>(t).count();
os << val << " nanoseconds";
}
return os;
}
void QueueTest::SetUp(){
auto tupleParams = GetParam();
_params = TestParameters{::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams), ::testing::get<4>(tupleParams), ::testing::get<5>(tupleParams)};
readers.resize(_params.nReaders, basic_timer());
writers.resize(_params.nWriters, basic_timer());
cout << "Readers: " << _params.nReaders << endl;
cout << "Writers: " << _params.nWriters << endl;
cout << "Elements: " << _params.nElements << endl;
cout << "Queue Size: " << _params.queueSize << endl;
cout << "Subqueue Size: " << _params.subqueueSize << endl;
cout << "Test Type: ";
switch (_params.testType) {
case BUSY_TEST: cout << "Busy Test"; break;
case YIELD_TEST: cout << "Yield Test"; break;
case SLEEP_TEST: cout << "Sleep Test"; break;
case BACKOFF_TEST: cout << "Backoff Test"; break;
default: break;
}
cout << endl;
}
void QueueTest::TearDown(){
cout << "Enqueue:" << endl;
auto writeDur = writers[0].getElapsedDuration();
auto writeMax = writers[0].getElapsedDuration();
int toMeasure = 1;
for (size_t i=1; i<writers.size(); ++i){
auto dur = writers[i].getElapsedDuration();
if (dur > std::chrono::nanoseconds(1)){
writeDur += dur;
if (dur > writeMax) writeMax = dur;
++toMeasure;
}
}
writeDur/=toMeasure;
cout << "Max write thread duration: " << writeMax << endl;
cout << "Average write thread duration: " << writeDur << endl;
cout << "Time per enqueue (average): " << writeDur / _params.nElements << endl;
cout << "Time per enqueue (worst case): " << writeMax / _params.nElements << endl;
cout << "Enqueue ops/second (average): " << static_cast<double>(_params.nElements) / writeDur.count() << std::endl;
cout << "Enqueue ops/second (worst case): " << static_cast<double>(_params.nElements) / writeMax.count() << std::endl;
cout << "Enqueue ops/second/thread (worst case): " << static_cast<double>(_params.nElements) / writeMax.count() / _params.nWriters << std::endl;
cout << "Dequeue:" << endl;
auto readDur = readers[0].getElapsedDuration();
auto readMax = readers[0].getElapsedDuration();
toMeasure = 1;
for (size_t i=1; i<readers.size(); ++i){
auto dur = readers[i].getElapsedDuration();
if (dur > std::chrono::nanoseconds(1)){
readDur += dur;
if (dur > readMax) readMax = dur;
++toMeasure;
}
}
readDur/=toMeasure;
cout << "Max read thread duration: " << readMax << endl;
cout << "Average read thread duration: " << readDur << endl;
cout << "Time per dequeue (average case)" << readDur / _params.nElements << std::endl;
cout << "Time per dequeue (worst case): " << readMax/_params.nElements << endl;
cout << "Dequeue ops/second (average case): " << static_cast<double>(_params.nElements) / readDur.count() << std::endl;
cout << "Dequeue ops/second (worst case): " << static_cast<double>(_params.nElements) / readMax.count() << std::endl;
cout << "Dequeue ops/second/thread (worst case): " << static_cast<double>(_params.nElements) / readMax.count() / _params.nReaders << std::endl;
}
namespace ListQueue{
using qtype = bk_conq::list_queue<QueueTest::queue_test_type_t>;
using mqtype = bk_conq::multi_unbounded_queue<qtype>;
using bqtype = bk_conq::blocking_unbounded_queue<qtype>;
using bmqtype = bk_conq::blocking_unbounded_queue<mqtype>;
TEST_P(QueueTest, list_queue) {
QueueTest::TemplatedTest<qtype, queue_test_type_t>();
}
TEST_P(QueueTest, list_queue_blocking) {
QueueTest::BlockingTest<bqtype, queue_test_type_t>();
}
TEST_P(QueueTest, multi_list_queue) {
QueueTest::TemplatedTest<mqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, multi_list_queue_blocking) {
QueueTest::BlockingTest<bmqtype, queue_test_type_t>(_params.subqueueSize);
}
}
namespace BoundedListQueue {
using qtype = bk_conq::bounded_list_queue<QueueTest::queue_test_type_t>;
using mqtype = bk_conq::multi_bounded_queue<qtype>;
using bqtype = bk_conq::blocking_bounded_queue<qtype>;
using bmqtype = bk_conq::blocking_bounded_queue<mqtype>;
TEST_P(QueueTest, bounded_list_queue) {
QueueTest::TemplatedTest<qtype, queue_test_type_t>();
}
TEST_P(QueueTest, bounded_list_queue_blocking) {
QueueTest::BlockingTest<bqtype, queue_test_type_t>();
}
TEST_P(QueueTest, multi_bounded_list_queue) {
QueueTest::TemplatedTest<mqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, multi_bounded_list_queue_blocking) {
QueueTest::BlockingTest<bmqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, untemplated) {
mqtype q(_params.queueSize, _params.subqueueSize);
std::vector<std::thread> l;
for (size_t i = 0; i < _params.nReaders; ++i) {
l.emplace_back([&, i]() {
readers[i].start();
queue_test_type_t res;
for (size_t j = 0; j < _params.nElements / _params.nReaders; ++j) {
while (!q.mc_dequeue(res));
}
if (i == 0) {
size_t remainder = _params.nElements - ((_params.nElements / _params.nReaders) * _params.nReaders);
for (size_t j = 0; j < remainder; ++j) {
while (!q.mc_dequeue(res));
}
}
readers[i].stop();
});
}
for (size_t i = 0; i < _params.nWriters; ++i) {
l.emplace_back([&, i]() {
writers[i].start();
for (size_t j = 0; j < _params.nElements / _params.nWriters; ++j) {
while (!q.mp_enqueue(j));
}
if (i == 0) {
size_t remainder = _params.nElements - ((_params.nElements / _params.nWriters) * _params.nWriters);
for (size_t j = 0; j < remainder; ++j) {
while (!q.mp_enqueue(j));
}
}
writers[i].stop();
});
}
for (size_t i = 0; i < _params.nReaders + _params.nWriters; ++i) {
l[i].join();
}
}
}
namespace VectorQueue {
using qtype = bk_conq::vector_queue<QueueTest::queue_test_type_t>;
using mqtype = bk_conq::multi_bounded_queue<qtype>;
using bqtype = bk_conq::blocking_bounded_queue<qtype>;
using bmqtype = bk_conq::blocking_bounded_queue<mqtype>;
TEST_P(QueueTest, vector_queue) {
QueueTest::TemplatedTest<qtype, queue_test_type_t>();
}
TEST_P(QueueTest, vector_queue_blocking) {
QueueTest::BlockingTest<bqtype, queue_test_type_t>();
}
TEST_P(QueueTest, multi_vector_queue) {
QueueTest::TemplatedTest<mqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, multi_vector_queue_blocking) {
QueueTest::BlockingTest<bmqtype, queue_test_type_t>(_params.subqueueSize);
}
}
INSTANTIATE_TEST_CASE_P(
queue_benchmark,
QueueTest,
testing::Combine(
Values(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), //readers
Values(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), //writers
Values(1e6, 1e7, 1e8, 1e9), //elements
Values(8192, 32768, 131072, 524288, 2097152), //queue size (bounded only)
Values(2, 4, 8, 16, 32, 64), //subqueue size (multiqueue only)
Values(QueueTestType::BUSY_TEST, QueueTestType::YIELD_TEST, QueueTestType::SLEEP_TEST, QueueTestType::BACKOFF_TEST)) //test type
);
|
#include "concurrent_queue_test.h"
#include <iostream>
#include <chrono>
#include <type_traits>
using ::testing::Values;
using ::testing::Combine;
using ::testing::Types;
using std::cout;
using std::endl;
std::ostream& operator<<(std::ostream& os, const std::chrono::duration<double>& t) {
double val;
if ((val = std::chrono::duration<double>(t).count()) > 1.0){
os << val << " seconds";
}
else if ((val = std::chrono::duration<double, std::milli>(t).count()) > 1.0){
os << val << " milliseconds";
}
else if ((val = std::chrono::duration<double, std::micro>(t).count()) > 1.0){
os << val << " microseconds";
}
else{
val = std::chrono::duration<double, std::nano>(t).count();
os << val << " nanoseconds";
}
return os;
}
void QueueTest::SetUp(){
auto tupleParams = GetParam();
_params = TestParameters{::testing::get<0>(tupleParams), ::testing::get<1>(tupleParams), ::testing::get<2>(tupleParams), ::testing::get<3>(tupleParams), ::testing::get<4>(tupleParams), ::testing::get<5>(tupleParams)};
readers.resize(_params.nReaders, basic_timer());
writers.resize(_params.nWriters, basic_timer());
cout << "Readers: " << _params.nReaders << endl;
cout << "Writers: " << _params.nWriters << endl;
cout << "Elements: " << _params.nElements << endl;
cout << "Queue Size: " << _params.queueSize << endl;
cout << "Subqueue Size: " << _params.subqueueSize << endl;
cout << "Test Type: ";
switch (_params.testType) {
case BUSY_TEST: cout << "Busy Test"; break;
case YIELD_TEST: cout << "Yield Test"; break;
case SLEEP_TEST: cout << "Sleep Test"; break;
case BACKOFF_TEST: cout << "Backoff Test"; break;
default: break;
}
cout << endl;
}
void QueueTest::TearDown(){
cout << "Enqueue:" << endl;
auto writeDur = writers[0].getElapsedDuration();
auto writeMax = writers[0].getElapsedDuration();
int toMeasure = 1;
for (size_t i=1; i<writers.size(); ++i){
auto dur = writers[i].getElapsedDuration();
if (dur > std::chrono::nanoseconds(1)){
writeDur += dur;
if (dur > writeMax) writeMax = dur;
++toMeasure;
}
}
writeDur/=toMeasure;
cout << "Max write thread duration: " << writeMax << endl;
cout << "Average write thread duration: " << writeDur << endl;
cout << "Time per enqueue (average): " << writeDur / _params.nElements << endl;
cout << "Time per enqueue (worst case): " << writeMax / _params.nElements << endl;
cout << "Enqueue ops/second (average): " << static_cast<double>(_params.nElements) / writeDur.count() << std::endl;
cout << "Enqueue ops/second (worst case): " << static_cast<double>(_params.nElements) / writeMax.count() << std::endl;
cout << "Enqueue ops/second/thread (worst case): " << static_cast<double>(_params.nElements) / writeMax.count() / _params.nWriters << std::endl;
cout << "Dequeue:" << endl;
auto readDur = readers[0].getElapsedDuration();
auto readMax = readers[0].getElapsedDuration();
toMeasure = 1;
for (size_t i=1; i<readers.size(); ++i){
auto dur = readers[i].getElapsedDuration();
if (dur > std::chrono::nanoseconds(1)){
readDur += dur;
if (dur > readMax) readMax = dur;
++toMeasure;
}
}
readDur/=toMeasure;
cout << "Max read thread duration: " << readMax << endl;
cout << "Average read thread duration: " << readDur << endl;
cout << "Time per dequeue (average case)" << readDur / _params.nElements << std::endl;
cout << "Time per dequeue (worst case): " << readMax/_params.nElements << endl;
cout << "Dequeue ops/second (average case): " << static_cast<double>(_params.nElements) / readDur.count() << std::endl;
cout << "Dequeue ops/second (worst case): " << static_cast<double>(_params.nElements) / readMax.count() << std::endl;
cout << "Dequeue ops/second/thread (worst case): " << static_cast<double>(_params.nElements) / readMax.count() / _params.nReaders << std::endl;
}
namespace ListQueue{
using qtype = bk_conq::list_queue<QueueTest::queue_test_type_t>;
using mqtype = bk_conq::multi_unbounded_queue<qtype>;
using bqtype = bk_conq::blocking_unbounded_queue<qtype>;
using bmqtype = bk_conq::blocking_unbounded_queue<mqtype>;
TEST_P(QueueTest, list_queue) {
QueueTest::TemplatedTest<qtype, queue_test_type_t>();
}
TEST_P(QueueTest, list_queue_blocking) {
QueueTest::BlockingTest<bqtype, queue_test_type_t>();
}
TEST_P(QueueTest, multi_list_queue) {
QueueTest::TemplatedTest<mqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, multi_list_queue_blocking) {
QueueTest::BlockingTest<bmqtype, queue_test_type_t>(_params.subqueueSize);
}
}
namespace BoundedListQueue {
using qtype = bk_conq::bounded_list_queue<QueueTest::queue_test_type_t>;
using mqtype = bk_conq::multi_bounded_queue<qtype>;
using bqtype = bk_conq::blocking_bounded_queue<qtype>;
using bmqtype = bk_conq::blocking_bounded_queue<mqtype>;
TEST_P(QueueTest, bounded_list_queue) {
QueueTest::TemplatedTest<qtype, queue_test_type_t>();
}
TEST_P(QueueTest, bounded_list_queue_blocking) {
QueueTest::BlockingTest<bqtype, queue_test_type_t>();
}
TEST_P(QueueTest, multi_bounded_list_queue) {
QueueTest::TemplatedTest<mqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, multi_bounded_list_queue_blocking) {
QueueTest::BlockingTest<bmqtype, queue_test_type_t>(_params.subqueueSize);
}
}
namespace VectorQueue {
using qtype = bk_conq::vector_queue<QueueTest::queue_test_type_t>;
using mqtype = bk_conq::multi_bounded_queue<qtype>;
using bqtype = bk_conq::blocking_bounded_queue<qtype>;
using bmqtype = bk_conq::blocking_bounded_queue<mqtype>;
TEST_P(QueueTest, vector_queue) {
QueueTest::TemplatedTest<qtype, queue_test_type_t>();
}
TEST_P(QueueTest, vector_queue_blocking) {
QueueTest::BlockingTest<bqtype, queue_test_type_t>();
}
TEST_P(QueueTest, multi_vector_queue) {
QueueTest::TemplatedTest<mqtype, queue_test_type_t>(_params.subqueueSize);
}
TEST_P(QueueTest, multi_vector_queue_blocking) {
QueueTest::BlockingTest<bmqtype, queue_test_type_t>(_params.subqueueSize);
}
}
INSTANTIATE_TEST_CASE_P(
queue_benchmark,
QueueTest,
testing::Combine(
Values(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), //readers
Values(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), //writers
Values(1e6, 1e7, 1e8, 1e9), //elements
Values(8192, 32768, 131072, 524288, 2097152), //queue size (bounded only)
Values(2, 4, 8, 16, 32, 64), //subqueue size (multiqueue only)
Values(QueueTestType::BUSY_TEST, QueueTestType::YIELD_TEST, QueueTestType::SLEEP_TEST, QueueTestType::BACKOFF_TEST)) //test type
);
|
remove untemplated test
|
remove untemplated test
|
C++
|
unknown
|
Barath-Kannan/ConcurrentQueues,Barath-Kannan/MPMCQueue
|
05bde52ab9559cc8cbdfcdaa358e1d9b2e30731a
|
perlin.cc
|
perlin.cc
|
#include <iostream>
#include <random>
#include <SFML/Graphics.hpp>
#include <noise/noise.h>
#include "force.h"
#include "particle.h"
#include "util.h"
using namespace noise;
namespace util {
double map(double val, double from_min, double from_max, double to_min, double to_max)
{
double from_range, to_range;
from_range = from_max - from_min;
to_range = to_max - to_min;
double new_val = (((val - from_min) * to_range) / from_range) + to_min;
if (new_val > to_max)
return to_max;
if (new_val < to_min)
return to_min;
return new_val;
}
}
int main()
{
// These values are used to compute perlin noise
double xn = 0, yn = 0, zn = 0;
const double xoffset = 0.05;
const double yoffset = 0.05;
const double zoffset = 0.001;
// Window size
constexpr int width = 1600;
constexpr int height = 800;
constexpr int num_particles = 5000;
constexpr int cell_size = 10;
constexpr float flow_strength = 3.f;
const int cols = width / cell_size;
const int rows = height / cell_size;
// Random number generator setup
std::random_device rd;
std::default_random_engine gen(rd());
// distributions for random x and y coordinates
std::uniform_int_distribution<int> rand_x(0, width-1);
std::uniform_int_distribution<int> rand_y(0, height-1);
// distribution for random hue values
std::uniform_real_distribution<float> rand_h(0.f, 360.f);
// Setup noise generator
module::Perlin noise;
noise.SetSeed(rand_y(gen));
// Create and initialize the force vectors on a grid layout
Force forces[rows][cols];
for (unsigned int y = 0; y < rows; y++)
{
for (unsigned int x = 0; x < cols; x++)
{
forces[y][x].setPosition(x * cell_size, y * cell_size);
forces[y][x].setMagnitude(cell_size);
forces[y][x].setAngle(0.f);
}
}
// Create and initialize the particles
Particle particles[num_particles];
for (int i = 0; i < num_particles; i++)
{
particles[i].current.position = sf::Vector2f(rand_x(gen), rand_y(gen));
float r,g,b,h,s = 1,v = 1;
h = rand_h(gen);
HSVtoRGB(r, g, b, h, s, v);
// Random color for each line (with alpha)
//particles[i].current.color = sf::Color(r*255, g*255, b*255, 10);
// All black with alpha
particles[i].current.color = sf::Color::Black;
particles[i].current.color.a = 10;
}
sf::RenderWindow window(sf::VideoMode(width, height), "Perlin", sf::Style::Close);
window.setFramerateLimit(60);
window.clear(sf::Color::White);
sf::Clock clock;
sf::Time time;
int frames = 0;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//window.clear();
yn = 0;
for (unsigned int y = 0; y < rows; y++)
{
xn = 0;
for (unsigned int x = 0; x < cols; x++)
{
double n = noise.GetValue(xn, yn, zn);
float dir = util::map(n, -1, 1, 0, 360);
forces[y][x].setAngle(dir);
//forces[y][x].draw(window);
xn += xoffset;
}
yn += yoffset;
}
for (int i = 0; i < num_particles; i++)
{
Particle *p = &particles[i];
int gx, gy;
gx = p->current.position.x / cell_size;
gy = p->current.position.y / cell_size;
p->acceleration = forces[gy][gx].getVector() / (float)cell_size * flow_strength;
p->update(window);
p->draw(window);
}
window.display();
zn += zoffset;
// Calculate FPS
frames += 1;
time += clock.restart();
if (time.asSeconds() > 1)
{
std::cout << 1.f / time.asSeconds() * frames << std::endl;
time = sf::Time();
frames = 0;
}
}
}
|
#include <vector>
#include <iostream>
#include <random>
#include <SFML/Graphics.hpp>
#include <noise/noise.h>
#include "force.h"
#include "particle.h"
#include "util.h"
using namespace noise;
namespace util {
double map(double val, double from_min, double from_max, double to_min, double to_max)
{
double from_range, to_range;
from_range = from_max - from_min;
to_range = to_max - to_min;
double new_val = (((val - from_min) * to_range) / from_range) + to_min;
if (new_val > to_max)
return to_max;
if (new_val < to_min)
return to_min;
return new_val;
}
}
int main()
{
// These values are used to compute perlin noise
double xn = 0, yn = 0, zn = 0;
const double xoffset = 0.05;
const double yoffset = 0.05;
const double zoffset = 0.001;
// Window size
constexpr int width = 1600;
constexpr int height = 800;
constexpr int num_particles = 5000;
constexpr int cell_size = 10;
constexpr float flow_strength = 3.f;
const int cols = width / cell_size;
const int rows = height / cell_size;
// Random number generator setup
std::random_device rd;
std::default_random_engine gen(rd());
// distributions for random x and y coordinates
std::uniform_int_distribution<int> rand_x(0, width-1);
std::uniform_int_distribution<int> rand_y(0, height-1);
// distribution for random hue values
std::uniform_real_distribution<float> rand_h(0.f, 360.f);
// Setup noise generator
module::Perlin noise;
noise.SetSeed(rand_y(gen));
// Create and initialize the force vectors on a grid layout
std::vector< std::vector<Force> > forces(rows, std::vector<Force> (cols, Force()));
for (unsigned int y = 0; y < rows; y++)
{
for (unsigned int x = 0; x < cols; x++)
{
forces[y][x].setPosition(x * cell_size, y * cell_size);
forces[y][x].setMagnitude(cell_size);
forces[y][x].setAngle(0.f);
}
}
// Create and initialize the particles
Particle particles[num_particles];
for (int i = 0; i < num_particles; i++)
{
particles[i].current.position = sf::Vector2f(rand_x(gen), rand_y(gen));
float r,g,b,h,s = 1,v = 1;
h = rand_h(gen);
HSVtoRGB(r, g, b, h, s, v);
// Random color for each line (with alpha)
//particles[i].current.color = sf::Color(r*255, g*255, b*255, 10);
// All black with alpha
particles[i].current.color = sf::Color::Black;
particles[i].current.color.a = 10;
}
sf::RenderWindow window(sf::VideoMode(width, height), "Perlin", sf::Style::Close);
window.setFramerateLimit(60);
window.clear(sf::Color::White);
sf::Clock clock;
sf::Time time;
int frames = 0;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//window.clear();
yn = 0;
for (unsigned int y = 0; y < rows; y++)
{
xn = 0;
for (unsigned int x = 0; x < cols; x++)
{
double n = noise.GetValue(xn, yn, zn);
float dir = util::map(n, -1, 1, 0, 360);
forces[y][x].setAngle(dir);
//forces[y][x].draw(window);
xn += xoffset;
}
yn += yoffset;
}
for (int i = 0; i < num_particles; i++)
{
Particle *p = &particles[i];
int gx, gy;
gx = p->current.position.x / cell_size;
gy = p->current.position.y / cell_size;
p->acceleration = forces[gy][gx].getVector() / (float)cell_size * flow_strength;
p->update(window);
p->draw(window);
}
window.display();
zn += zoffset;
// Calculate FPS
frames += 1;
time += clock.restart();
if (time.asSeconds() > 1)
{
std::cout << 1.f / time.asSeconds() * frames << std::endl;
time = sf::Time();
frames = 0;
}
}
}
|
Fix stack overflow causing segfault by switching C style array (stack allocated) to std::vector (heap allocated)
|
Fix stack overflow causing segfault by switching C style array (stack allocated) to std::vector (heap allocated)
|
C++
|
mit
|
bikefrivolously/perlin-noise-art
|
c15b5072cb22330dd981a1e7490a7d2ba833ddde
|
libraries/plugins/account_history/include/graphene/account_history/account_history_plugin.hpp
|
libraries/plugins/account_history/include/graphene/account_history/account_history_plugin.hpp
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_history_object.hpp>
#include <fc/thread/future.hpp>
namespace graphene { namespace account_history {
using namespace chain;
//using namespace graphene::db;
//using boost::multi_index_container;
//using namespace boost::multi_index;
//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ACCOUNT_HISTORY_SPACE_ID
#define ACCOUNT_HISTORY_SPACE_ID 4
#endif
enum account_history_object_type
{
key_account_object_type = 0
};
namespace detail
{
class account_history_plugin_impl;
}
class account_history_plugin : public graphene::app::plugin
{
public:
account_history_plugin();
virtual ~account_history_plugin();
std::string plugin_name()const override;
virtual void plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg) override;
virtual void plugin_initialize(const boost::program_options::variables_map& options) override;
virtual void plugin_startup() override;
flat_set<account_id_type> tracked_accounts()const;
friend class detail::account_history_plugin_impl;
std::unique_ptr<detail::account_history_plugin_impl> my;
};
} } //graphene::account_history
/*
struct by_seq;
struct by_op;
typedef boost::multi_index_container<
graphene::chain::account_transaction_history_object,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
boost::multi_index::ordered_unique< tag<by_seq>,
composite_key< account_transaction_history_object,
member< account_transaction_history_object, account_id_type, &account_transaction_history_object::account>,
member< account_transaction_history_object, uint32_t, &account_transaction_history_object::sequence>
>
>,
boost::multi_index::ordered_unique< tag<by_op>,
composite_key< account_transaction_history_object,
member< account_transaction_history_object, account_id_type, &account_transaction_history_object::account>,
member< account_transaction_history_object, operation_history_id_type, &account_transaction_history_object::operation_id>
>
>
>
> account_transaction_history_multi_index_type;
typedef graphene::account_history::generic_index<graphene::chain::account_transaction_history_object, account_transaction_history_multi_index_type> account_transaction_history_index;
*/
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/app/plugin.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/operation_history_object.hpp>
#include <fc/thread/future.hpp>
namespace graphene { namespace account_history {
using namespace chain;
//using namespace graphene::db;
//using boost::multi_index_container;
//using namespace boost::multi_index;
//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//
#ifndef ACCOUNT_HISTORY_SPACE_ID
#define ACCOUNT_HISTORY_SPACE_ID 4
#endif
enum account_history_object_type
{
key_account_object_type = 0
};
namespace detail
{
class account_history_plugin_impl;
}
class account_history_plugin : public graphene::app::plugin
{
public:
account_history_plugin();
virtual ~account_history_plugin();
std::string plugin_name()const override;
virtual void plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg) override;
virtual void plugin_initialize(const boost::program_options::variables_map& options) override;
virtual void plugin_startup() override;
flat_set<account_id_type> tracked_accounts()const;
friend class detail::account_history_plugin_impl;
std::unique_ptr<detail::account_history_plugin_impl> my;
};
} } //graphene::account_history
|
Remove commented-out index code
|
Remove commented-out index code
|
C++
|
mit
|
bitshares/bitshares-2,bitshares/bitshares-2,bitshares/bitshares-2,bitshares/bitshares-2
|
b1c0df458455f3693654e31d955da2d20e9cc286
|
src/cblas.cpp
|
src/cblas.cpp
|
/**
* @file amici_cblas.cpp
* @brief BLAS routines required by AMICI
*
**/
#include "amici/defines.h"
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#elif defined(AMICI_BLAS_MKL)
#include <mkl.h>
#else
extern "C"
{
#include <cblas.h>
}
#endif
namespace amici {
/*!
* amici_dgemm provides an interface to the blas matrix matrix multiplication
* routine dgemm. This routines computes
* C = alpha*A*B + beta*C with A: [MxK] B:[KxN] C:[MxN]
*
* @param[in] layout can be AMICI_BLAS_ColMajor or AMICI_BLAS_RowMajor.
* @param[in] TransA flag indicating whether A should be transposed before
* multiplication
* @param[in] TransB flag indicating whether B should be transposed before
* multiplication
* @param[in] M number of rows in A/C
* @param[in] N number of columns in B/C
* @param[in] K number of rows in B, number of columns in A
* @param[in] alpha coefficient alpha
* @param[in] A matrix A
* @param[in] lda leading dimension of A (m or k)
* @param[in] B matrix B
* @param[in] ldb leading dimension of B (k or n)
* @param[in] beta coefficient beta
* @param[in,out] C matrix C
* @param[in] ldc leading dimension of C (m or n)
*/
void amici_dgemm(AMICI_BLAS_LAYOUT layout, AMICI_BLAS_TRANSPOSE TransA,
AMICI_BLAS_TRANSPOSE TransB, const int M, const int N,
const int K, const double alpha, const double *A,
const int lda, const double *B, const int ldb,
const double beta, double *C, const int ldc) {
cblas_dgemm((CBLAS_ORDER)layout, (CBLAS_TRANSPOSE)TransA,
(CBLAS_TRANSPOSE)TransB, M, N, K, alpha, A, lda, B, ldb, beta,
C, ldc);
}
/*!
* amici_dgemm provides an interface to the blas matrix vector multiplication
* routine dgemv. This routines computes
* y = alpha*A*x + beta*y with A: [MxK] B:[KxN] C:[MxN]
*
* @param[in] layout can be AMICI_BLAS_ColMajor or AMICI_BLAS_RowMajor.
* @param[in] TransA flag indicating whether A should be transposed before
* multiplication
* @param[in] M number of rows in A
* @param[in] N number of columns in A
* @param[in] alpha coefficient alpha
* @param[in] A matrix A
* @param[in] lda leading dimension of A (m or n)
* @param[in] X vector X
* @param[in] incX increment for entries of X
* @param[in] beta coefficient beta
* @param[in,out] Y vector Y
* @param[in] incY increment for entries of Y
*/
void amici_dgemv(AMICI_BLAS_LAYOUT layout, AMICI_BLAS_TRANSPOSE TransA,
const int M, const int N, const double alpha, const double *A,
const int lda, const double *X, const int incX,
const double beta, double *Y, const int incY) {
cblas_dgemv((CBLAS_ORDER)layout, (CBLAS_TRANSPOSE)TransA, M, N, alpha, A,
lda, X, incX, beta, Y, incY);
}
} // namespace amici
|
/**
* @file cblas.cpp
* @brief BLAS routines required by AMICI
*
**/
#include "amici/defines.h"
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#elif defined(AMICI_BLAS_MKL)
#include <mkl.h>
#else
extern "C"
{
#include <cblas.h>
}
#endif
namespace amici {
/*!
* amici_dgemm provides an interface to the blas matrix matrix multiplication
* routine dgemm. This routines computes
* C = alpha*A*B + beta*C with A: [MxK] B:[KxN] C:[MxN]
*
* @param[in] layout can be AMICI_BLAS_ColMajor or AMICI_BLAS_RowMajor.
* @param[in] TransA flag indicating whether A should be transposed before
* multiplication
* @param[in] TransB flag indicating whether B should be transposed before
* multiplication
* @param[in] M number of rows in A/C
* @param[in] N number of columns in B/C
* @param[in] K number of rows in B, number of columns in A
* @param[in] alpha coefficient alpha
* @param[in] A matrix A
* @param[in] lda leading dimension of A (m or k)
* @param[in] B matrix B
* @param[in] ldb leading dimension of B (k or n)
* @param[in] beta coefficient beta
* @param[in,out] C matrix C
* @param[in] ldc leading dimension of C (m or n)
*/
void amici_dgemm(AMICI_BLAS_LAYOUT layout, AMICI_BLAS_TRANSPOSE TransA,
AMICI_BLAS_TRANSPOSE TransB, const int M, const int N,
const int K, const double alpha, const double *A,
const int lda, const double *B, const int ldb,
const double beta, double *C, const int ldc) {
cblas_dgemm((CBLAS_ORDER)layout, (CBLAS_TRANSPOSE)TransA,
(CBLAS_TRANSPOSE)TransB, M, N, K, alpha, A, lda, B, ldb, beta,
C, ldc);
}
/*!
* amici_dgemm provides an interface to the blas matrix vector multiplication
* routine dgemv. This routines computes
* y = alpha*A*x + beta*y with A: [MxK] B:[KxN] C:[MxN]
*
* @param[in] layout can be AMICI_BLAS_ColMajor or AMICI_BLAS_RowMajor.
* @param[in] TransA flag indicating whether A should be transposed before
* multiplication
* @param[in] M number of rows in A
* @param[in] N number of columns in A
* @param[in] alpha coefficient alpha
* @param[in] A matrix A
* @param[in] lda leading dimension of A (m or n)
* @param[in] X vector X
* @param[in] incX increment for entries of X
* @param[in] beta coefficient beta
* @param[in,out] Y vector Y
* @param[in] incY increment for entries of Y
*/
void amici_dgemv(AMICI_BLAS_LAYOUT layout, AMICI_BLAS_TRANSPOSE TransA,
const int M, const int N, const double alpha, const double *A,
const int lda, const double *X, const int incX,
const double beta, double *Y, const int incY) {
cblas_dgemv((CBLAS_ORDER)layout, (CBLAS_TRANSPOSE)TransA, M, N, alpha, A,
lda, X, incX, beta, Y, incY);
}
} // namespace amici
|
Fix doxygen ...again
|
Fix doxygen ...again
|
C++
|
bsd-2-clause
|
AMICI-developer/AMICI,AMICI-developer/AMICI,FFroehlich/AMICI,AMICI-developer/AMICI,FFroehlich/AMICI,FFroehlich/AMICI,FFroehlich/AMICI,AMICI-developer/AMICI
|
fe30e1b5bdf509445b1919890673f6d44cf76b00
|
src/chain.cpp
|
src/chain.cpp
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 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 "chain.h"
using namespace std;
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 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 "chain.h"
using namespace std;
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != NULL &&
(heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
|
Make GetAncestor more robust
|
Make GetAncestor more robust
This check for pskip != NULL was introduced in #5927 for 0.12.
It is in general safer and allows GetAncestor to be used in more places, specifically in the mining tests for the backport of BIP 68 to 0.11.
|
C++
|
mit
|
bitcoinxt/bitcoinxt,bitcoinxt/bitcoinxt,bitcoinxt/bitcoinxt,dagurval/bitcoinxt,bitcoinxt/bitcoinxt,bitcoinxt/bitcoinxt,dagurval/bitcoinxt,dagurval/bitcoinxt,dagurval/bitcoinxt,dagurval/bitcoinxt,bitcoinxt/bitcoinxt,dagurval/bitcoinxt
|
792043e99288d02e54759df97cada4bbf5e8b86b
|
chrome/browser/instant/instant_browsertest.cc
|
chrome/browser/instant/instant_browsertest.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/location_bar.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
class InstantTest : public InProcessBrowserTest {
public:
InstantTest()
: location_bar_(NULL),
preview_(NULL) {
EnableDOMAutomation();
}
void SetupInstantProvider(const std::string& page) {
TemplateURLModel* model = browser()->profile()->GetTemplateURLModel();
ASSERT_TRUE(model);
if (!model->loaded()) {
model->Load();
ui_test_utils::WaitForNotification(
NotificationType::TEMPLATE_URL_MODEL_LOADED);
}
ASSERT_TRUE(model->loaded());
// TemplateURLModel takes ownership of this.
TemplateURL* template_url = new TemplateURL();
std::string url = StringPrintf(
"http://%s:%d/files/instant/%s?q={searchTerms}",
test_server()->host_port_pair().host().c_str(),
test_server()->host_port_pair().port(),
page.c_str());
template_url->SetURL(url, 0, 0);
template_url->SetInstantURL(url, 0, 0);
template_url->set_keyword(UTF8ToWide("foo"));
template_url->set_short_name(UTF8ToWide("foo"));
model->Add(template_url);
model->SetDefaultSearchProvider(template_url);
}
// Type a character to get instant to trigger.
void SetupLocationBar() {
location_bar_ = browser()->window()->GetLocationBar();
ASSERT_TRUE(location_bar_);
location_bar_->location_entry()->SetUserText(L"a");
}
// Wait for instant to load and ensure it is in the state we expect.
void SetupPreview() {
preview_ = browser()->instant()->GetPreviewContents();
ASSERT_TRUE(preview_);
ui_test_utils::WaitForNavigation(&preview_->controller());
// Verify the initial setup of the search box.
ASSERT_TRUE(browser()->instant());
EXPECT_TRUE(browser()->instant()->IsShowingInstant());
EXPECT_FALSE(browser()->instant()->is_active());
// When the page loads, the initial searchBox values are set and no events
// have been called.
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.sv", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.onsubmitcalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.oncancelcalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.onchangecalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.onresizecalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"a", "window.chrome.searchBox.value", preview_));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
false, "window.chrome.searchBox.verbatim", preview_));
}
void SetLocationBarText(const std::wstring& text) {
ASSERT_TRUE(location_bar_);
location_bar_->location_entry()->SetUserText(text);
ui_test_utils::WaitForNotification(
NotificationType::INSTANT_CONTROLLER_SHOWN);
}
void SendKey(app::KeyboardCode key) {
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), key, false, false, false, false));
}
void CheckStringValueFromJavascript(
const std::string& expected,
const std::string& function,
TabContents* tab_contents) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s)", function.c_str());
std::string result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
tab_contents->render_view_host(),
std::wstring(), UTF8ToWide(script), &result));
EXPECT_EQ(expected, result);
}
void CheckBoolValueFromJavascript(
bool expected,
const std::string& function,
TabContents* tab_contents) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s)", function.c_str());
bool result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab_contents->render_view_host(),
std::wstring(), UTF8ToWide(script), &result));
EXPECT_EQ(expected, result);
}
void CheckIntValueFromJavascript(
int expected,
const std::string& function,
TabContents* tab_contents) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s)", function.c_str());
int result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractInt(
tab_contents->render_view_host(),
std::wstring(), UTF8ToWide(script), &result));
EXPECT_EQ(expected, result);
}
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kEnablePredictiveInstant);
}
LocationBar* location_bar_;
TabContents* preview_;
};
// TODO(tonyg): Add the following tests:
// 1. Test that setSuggestions() works.
// 2. Test that the search box API is not populated for pages other than the
// default search provider.
// 3. Test resize events.
#if defined(OS_WIN)
#define MAYBE_OnChangeEvent OnChangeEvent
#else
#define MAYBE_OnChangeEvent DISABLED_OnChangeEvent
#endif
// Verify that the onchange event is dispatched upon typing in the box.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnChangeEvent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
ASSERT_NO_FATAL_FAILURE(SetupPreview());
ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
// Check that the value is reflected and onchange is called.
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"abc", "window.chrome.searchBox.value", preview_));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
false, "window.chrome.searchBox.verbatim", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
1, "window.onchangecalls", preview_));
}
#if defined(OS_WIN)
#define MAYBE_OnSubmitEvent OnSubmitEvent
#else
#define MAYBE_OnSubmitEvent DISABLED_OnSubmitEvent
#endif
// Verify that the onsubmit event is dispatched upon pressing enter.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnSubmitEvent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
ASSERT_NO_FATAL_FAILURE(SetupPreview());
ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_RETURN));
// Check that the preview contents have been committed.
ASSERT_FALSE(browser()->instant()->GetPreviewContents());
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
// Check that the value is reflected and onsubmit is called.
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.sv", contents));
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"abc", "window.chrome.searchBox.value", contents));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.searchBox.verbatim", contents));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
1, "window.onsubmitcalls", contents));
}
#if defined(OS_WIN)
#define MAYBE_OnCancelEvent OnCancelEvent
#else
#define MAYBE_OnCancelEvent DISABLED_OnCancelEvent
#endif
// Verify that the oncancel event is dispatched upon losing focus.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnCancelEvent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
ASSERT_NO_FATAL_FAILURE(SetupPreview());
ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_TAB_CONTAINER));
// Check that the preview contents have been committed.
ASSERT_FALSE(browser()->instant()->GetPreviewContents());
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
// Check that the value is reflected and oncancel is called.
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.sv", contents));
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"abc", "window.chrome.searchBox.value", contents));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
false, "window.chrome.searchBox.verbatim", contents));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
1, "window.oncancelcalls", contents));
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/location_bar.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
class InstantTest : public InProcessBrowserTest {
public:
InstantTest()
: location_bar_(NULL),
preview_(NULL) {
EnableDOMAutomation();
}
void SetupInstantProvider(const std::string& page) {
TemplateURLModel* model = browser()->profile()->GetTemplateURLModel();
ASSERT_TRUE(model);
if (!model->loaded()) {
model->Load();
ui_test_utils::WaitForNotification(
NotificationType::TEMPLATE_URL_MODEL_LOADED);
}
ASSERT_TRUE(model->loaded());
// TemplateURLModel takes ownership of this.
TemplateURL* template_url = new TemplateURL();
std::string url = StringPrintf(
"http://%s:%d/files/instant/%s?q={searchTerms}",
test_server()->host_port_pair().host().c_str(),
test_server()->host_port_pair().port(),
page.c_str());
template_url->SetURL(url, 0, 0);
template_url->SetInstantURL(url, 0, 0);
template_url->set_keyword(UTF8ToWide("foo"));
template_url->set_short_name(UTF8ToWide("foo"));
model->Add(template_url);
model->SetDefaultSearchProvider(template_url);
}
// Type a character to get instant to trigger.
void SetupLocationBar() {
location_bar_ = browser()->window()->GetLocationBar();
ASSERT_TRUE(location_bar_);
location_bar_->location_entry()->SetUserText(L"a");
}
// Wait for instant to load and ensure it is in the state we expect.
void SetupPreview() {
preview_ = browser()->instant()->GetPreviewContents();
ASSERT_TRUE(preview_);
ui_test_utils::WaitForNavigation(&preview_->controller());
// Verify the initial setup of the search box.
ASSERT_TRUE(browser()->instant());
EXPECT_TRUE(browser()->instant()->IsShowingInstant());
EXPECT_FALSE(browser()->instant()->is_active());
// When the page loads, the initial searchBox values are set and no events
// have been called.
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.sv", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.onsubmitcalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.oncancelcalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.onchangecalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
0, "window.onresizecalls", preview_));
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"a", "window.chrome.searchBox.value", preview_));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
false, "window.chrome.searchBox.verbatim", preview_));
}
void SetLocationBarText(const std::wstring& text) {
ASSERT_TRUE(location_bar_);
location_bar_->location_entry()->SetUserText(text);
ui_test_utils::WaitForNotification(
NotificationType::INSTANT_CONTROLLER_SHOWN);
}
void SendKey(app::KeyboardCode key) {
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), key, false, false, false, false));
}
void CheckStringValueFromJavascript(
const std::string& expected,
const std::string& function,
TabContents* tab_contents) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s)", function.c_str());
std::string result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
tab_contents->render_view_host(),
std::wstring(), UTF8ToWide(script), &result));
EXPECT_EQ(expected, result);
}
void CheckBoolValueFromJavascript(
bool expected,
const std::string& function,
TabContents* tab_contents) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s)", function.c_str());
bool result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab_contents->render_view_host(),
std::wstring(), UTF8ToWide(script), &result));
EXPECT_EQ(expected, result);
}
void CheckIntValueFromJavascript(
int expected,
const std::string& function,
TabContents* tab_contents) {
std::string script = StringPrintf(
"window.domAutomationController.send(%s)", function.c_str());
int result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractInt(
tab_contents->render_view_host(),
std::wstring(), UTF8ToWide(script), &result));
EXPECT_EQ(expected, result);
}
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kEnablePredictiveInstant);
}
LocationBar* location_bar_;
TabContents* preview_;
};
// TODO(tonyg): Add the following tests:
// 1. Test that setSuggestions() works.
// 2. Test that the search box API is not populated for pages other than the
// default search provider.
// 3. Test resize events.
#if defined(OS_WIN)
// Disabled, http://crbug.com/62940.
#define MAYBE_OnChangeEvent DISABLED_OnChangeEvent
#else
#define MAYBE_OnChangeEvent DISABLED_OnChangeEvent
#endif
// Verify that the onchange event is dispatched upon typing in the box.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnChangeEvent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
ASSERT_NO_FATAL_FAILURE(SetupPreview());
ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
// Check that the value is reflected and onchange is called.
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"abc", "window.chrome.searchBox.value", preview_));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
false, "window.chrome.searchBox.verbatim", preview_));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
1, "window.onchangecalls", preview_));
}
#if defined(OS_WIN)
#define MAYBE_OnSubmitEvent OnSubmitEvent
#else
#define MAYBE_OnSubmitEvent DISABLED_OnSubmitEvent
#endif
// Verify that the onsubmit event is dispatched upon pressing enter.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnSubmitEvent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
ASSERT_NO_FATAL_FAILURE(SetupPreview());
ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
ASSERT_NO_FATAL_FAILURE(SendKey(app::VKEY_RETURN));
// Check that the preview contents have been committed.
ASSERT_FALSE(browser()->instant()->GetPreviewContents());
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
// Check that the value is reflected and onsubmit is called.
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.sv", contents));
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"abc", "window.chrome.searchBox.value", contents));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.searchBox.verbatim", contents));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
1, "window.onsubmitcalls", contents));
}
#if defined(OS_WIN)
#define MAYBE_OnCancelEvent OnCancelEvent
#else
#define MAYBE_OnCancelEvent DISABLED_OnCancelEvent
#endif
// Verify that the oncancel event is dispatched upon losing focus.
IN_PROC_BROWSER_TEST_F(InstantTest, MAYBE_OnCancelEvent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_NO_FATAL_FAILURE(SetupInstantProvider("search.html"));
ASSERT_NO_FATAL_FAILURE(SetupLocationBar());
ASSERT_NO_FATAL_FAILURE(SetupPreview());
ASSERT_NO_FATAL_FAILURE(SetLocationBarText(L"abc"));
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_TAB_CONTAINER));
// Check that the preview contents have been committed.
ASSERT_FALSE(browser()->instant()->GetPreviewContents());
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
// Check that the value is reflected and oncancel is called.
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
true, "window.chrome.sv", contents));
EXPECT_NO_FATAL_FAILURE(CheckStringValueFromJavascript(
"abc", "window.chrome.searchBox.value", contents));
EXPECT_NO_FATAL_FAILURE(CheckBoolValueFromJavascript(
false, "window.chrome.searchBox.verbatim", contents));
EXPECT_NO_FATAL_FAILURE(CheckIntValueFromJavascript(
1, "window.oncancelcalls", contents));
}
|
Disable InstantTest.OnSubmitEvent
|
Disable InstantTest.OnSubmitEvent
TBR=tonyg
BUG=62940
TEST=interactive_ui_tests
Review URL: http://codereview.chromium.org/4889001
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@65929 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium
|
cfed6f1112c231128cbd4b7c5d76e4e65529f495
|
common/core/desktop/src/kmx/kmx_processor.cpp
|
common/core/desktop/src/kmx/kmx_processor.cpp
|
#include <keyman/keyboardprocessor.h>
#include "state.hpp"
#include "kmx/kmx_processor.hpp"
#include <map>
using namespace km::kbp;
using namespace kmx;
km_kbp_status kmx_processor::validate() const {
return _valid ? KM_KBP_STATUS_OK : KM_KBP_STATUS_INVALID_KEYBOARD;
}
kmx_processor::kmx_processor(kbp::path p) {
p.replace_extension(".kmx");
_valid = bool(_kmx.Load(p.c_str()));
if (!_valid)
return;
keyboard_attributes::options_store defaults;
_kmx.GetOptions()->Init(defaults);
for (auto const & opt: defaults)
{
if (!opt.empty() && opt.scope == KM_KBP_OPT_KEYBOARD )
persisted_store()[opt.key] = opt.value;
}
// Fill out attributes
auto v = _kmx.GetKeyboard()->Keyboard->version;
auto vs = std::to_string(v >> 16) + "." + std::to_string(v & 0xffff);
_attributes = keyboard_attributes(static_cast<std::u16string>(p.stem()),
std::u16string(vs.begin(), vs.end()), p.parent(), defaults);
}
char16_t const *
kmx_processor::lookup_option(
km_kbp_option_scope scope,
std::u16string const &key
) const {
char16_t const *pValue = nullptr;
switch (scope) {
case KM_KBP_OPT_KEYBOARD:
pValue = _kmx.GetOptions()->LookUp(key);
break;
case KM_KBP_OPT_ENVIRONMENT:
pValue = _kmx.GetEnvironment()->LookUp(key);
break;
default:
break;
}
return pValue ? pValue : nullptr;
}
option
kmx_processor::update_option(
km_kbp_option_scope scope,
std::u16string const &key,
std::u16string const &value
) {
switch (scope) {
case KM_KBP_OPT_KEYBOARD:
_kmx.GetOptions()->Set(key, value);
persisted_store()[key] = value;
break;
case KM_KBP_OPT_ENVIRONMENT:
_kmx.GetEnvironment()->Set(key, value);
break;
default:
return option();
break;
}
return option(scope, key, value);
}
km_kbp_status
kmx_processor::process_event(
km_kbp_state *state,
km_kbp_virtual_key vk,
uint16_t modifier_state,
uint8_t is_key_down
) {
// Construct a context buffer from the items
std::u16string ctxt;
auto cp = state->context();
for (auto c = cp.begin(); c != cp.end(); c++) {
switch (c->type) {
case KM_KBP_CT_CHAR:
if (Uni_IsSMP(c->character)) {
ctxt += Uni_UTF32ToSurrogate1(c->character);
ctxt += Uni_UTF32ToSurrogate2(c->character);
} else {
ctxt += (km_kbp_cp)c->character;
}
break;
case KM_KBP_CT_MARKER:
assert(c->marker > 0);
ctxt += UC_SENTINEL;
ctxt += CODE_DEADKEY;
ctxt += c->marker;
break;
}
}
_kmx.GetContext()->Set(ctxt.c_str());
_kmx.GetActions()->ResetQueue();
state->actions().clear();
if (!_kmx.ProcessEvent(state, vk, modifier_state, is_key_down)) {
// We need to output the default keystroke
state->actions().push_emit_keystroke();
}
for (auto i = 0; i < _kmx.GetActions()->Length(); i++) {
auto a = _kmx.GetActions()->Get(i);
switch (a.ItemType) {
case QIT_CAPSLOCK:
state->actions().push_capslock(a.dwData);
break;
case QIT_VKEYDOWN:
case QIT_VKEYUP:
case QIT_VSHIFTDOWN:
case QIT_VSHIFTUP:
// TODO: eliminate??
break;
case QIT_CHAR:
state->context().push_character(a.dwData);
state->actions().push_character(a.dwData);
break;
case QIT_DEADKEY:
state->context().push_marker(a.dwData);
state->actions().push_marker(a.dwData);
break;
case QIT_BELL:
state->actions().push_alert();
break;
case QIT_BACK:
switch (a.dwData) {
case BK_DEFAULT:
// This only happens if we know we have context to delete. Last item must be a character
assert(!state->context().empty());
assert(state->context().back().type != KM_KBP_IT_MARKER);
if(!state->context().empty()) {
auto item = state->context().back();
state->context().pop_back();
state->actions().push_backspace(KM_KBP_BT_CHAR, item.character);
} else {
// Note: only runs on non-debug build, fail safe
state->actions().push_backspace(KM_KBP_BT_UNKNOWN);
}
break;
case BK_DEADKEY:
// This only happens if we know we have context to delete. Last item must be a deadkey
assert(!state->context().empty());
assert(state->context().back().type == KM_KBP_IT_MARKER);
if(!state->context().empty()) {
auto item = state->context().back();
state->context().pop_back();
state->actions().push_backspace(KM_KBP_BT_MARKER, item.marker);
} else {
// Note: only runs on non-debug build, fail safe
state->actions().push_backspace(KM_KBP_BT_UNKNOWN);
}
break;
default:
assert(false);
}
break;
case QIT_INVALIDATECONTEXT:
state->actions().push_invalidate_context();
break;
default:
// std::cout << "Unexpected item type " << a.ItemType << ", " << a.dwData << std::endl;
assert(false);
}
}
state->actions().commit();
return KM_KBP_STATUS_OK;
}
constexpr km_kbp_attr const engine_attrs = {
256,
KM_KBP_LIB_CURRENT,
KM_KBP_LIB_AGE,
KM_KBP_LIB_REVISION,
KM_KBP_TECH_KMX,
"SIL International"
};
km_kbp_attr const & kmx_processor::attributes() const {
return engine_attrs;
}
km_kbp_keyboard_key * kmx_processor::get_key_list() const {
// Iterate through the groups and get the rules with virtual keys
// and store the key along with the modifer.
const uint32_t group_cnt = _kmx.GetKeyboard()->Keyboard->cxGroupArray;
const LPGROUP group_array = _kmx.GetKeyboard()->Keyboard->dpGroupArray;
GROUP *p_group;
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t> map_rules;
km_kbp_virtual_key v_key;
uint32_t modifier_flag;
// Use hash map to get the unique list
for(auto i = decltype(group_cnt){0}; i < group_cnt; i++)
{
p_group = &group_array[i];
if(p_group->fUsingKeys)
{
for(auto j = decltype(p_group->cxKeyArray){0}; j < p_group->cxKeyArray; j++)
{
v_key = p_group->dpKeyArray[j].Key;
modifier_flag = p_group->dpKeyArray[j].ShiftFlags;
if(modifier_flag == 0) {
if(!MapUSCharToVK(v_key, &v_key, &modifier_flag)) continue;
}
map_rules[std::make_pair(v_key,modifier_flag)] = (modifier_flag & K_MODIFIERFLAG); // Clear kmx special flags
}
}
}
// Now convert to the keyboard key array
km_kbp_keyboard_key *rules = new km_kbp_keyboard_key[map_rules.size() + 1];
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t>::iterator it = map_rules.begin();
int n = 0;
while (it != map_rules.end()){
auto pair = it->first;
rules[n].key = pair.first;
rules[n].modifier_flag = it->second;
it++;
n++;
}
// Insert list termination
rules[n] = KM_KBP_KEYBOARD_KEY_LIST_END;
return rules;
}
|
#include <keyman/keyboardprocessor.h>
#include "state.hpp"
#include "kmx/kmx_processor.hpp"
#include <map>
using namespace km::kbp;
using namespace kmx;
km_kbp_status kmx_processor::validate() const {
return _valid ? KM_KBP_STATUS_OK : KM_KBP_STATUS_INVALID_KEYBOARD;
}
kmx_processor::kmx_processor(kbp::path p) {
p.replace_extension(".kmx");
_valid = bool(_kmx.Load(p.c_str()));
if (!_valid)
return;
keyboard_attributes::options_store defaults;
_kmx.GetOptions()->Init(defaults);
for (auto const & opt: defaults)
{
if (!opt.empty() && opt.scope == KM_KBP_OPT_KEYBOARD )
persisted_store()[opt.key] = opt.value;
}
// Fill out attributes
auto v = _kmx.GetKeyboard()->Keyboard->version;
auto vs = std::to_string(v >> 16) + "." + std::to_string(v & 0xffff);
_attributes = keyboard_attributes(static_cast<std::u16string>(p.stem()),
std::u16string(vs.begin(), vs.end()), p.parent(), defaults);
}
char16_t const *
kmx_processor::lookup_option(
km_kbp_option_scope scope,
std::u16string const &key
) const {
char16_t const *pValue = nullptr;
switch (scope) {
case KM_KBP_OPT_KEYBOARD:
pValue = _kmx.GetOptions()->LookUp(key);
break;
case KM_KBP_OPT_ENVIRONMENT:
pValue = _kmx.GetEnvironment()->LookUp(key);
break;
default:
break;
}
return pValue ? pValue : nullptr;
}
option
kmx_processor::update_option(
km_kbp_option_scope scope,
std::u16string const &key,
std::u16string const &value
) {
switch (scope) {
case KM_KBP_OPT_KEYBOARD:
_kmx.GetOptions()->Set(key, value);
persisted_store()[key] = value;
break;
case KM_KBP_OPT_ENVIRONMENT:
_kmx.GetEnvironment()->Set(key, value);
break;
default:
return option();
break;
}
return option(scope, key, value);
}
km_kbp_status
kmx_processor::process_event(
km_kbp_state *state,
km_kbp_virtual_key vk,
uint16_t modifier_state,
uint8_t is_key_down
) {
// Construct a context buffer from the items
std::u16string ctxt;
auto cp = state->context();
for (auto c = cp.begin(); c != cp.end(); c++) {
switch (c->type) {
case KM_KBP_CT_CHAR:
if (Uni_IsSMP(c->character)) {
ctxt += Uni_UTF32ToSurrogate1(c->character);
ctxt += Uni_UTF32ToSurrogate2(c->character);
} else {
ctxt += (km_kbp_cp)c->character;
}
break;
case KM_KBP_CT_MARKER:
assert(c->marker > 0);
ctxt += UC_SENTINEL;
ctxt += CODE_DEADKEY;
ctxt += c->marker;
break;
}
}
_kmx.GetContext()->Set(ctxt.c_str());
_kmx.GetActions()->ResetQueue();
state->actions().clear();
if (!_kmx.ProcessEvent(state, vk, modifier_state, is_key_down)) {
// We need to output the default keystroke
state->actions().push_emit_keystroke();
}
for (auto i = 0; i < _kmx.GetActions()->Length(); i++) {
auto a = _kmx.GetActions()->Get(i);
switch (a.ItemType) {
case QIT_CAPSLOCK:
state->actions().push_capslock(a.dwData);
break;
case QIT_VKEYDOWN:
case QIT_VKEYUP:
case QIT_VSHIFTDOWN:
case QIT_VSHIFTUP:
// TODO: eliminate??
break;
case QIT_CHAR:
state->context().push_character(a.dwData);
state->actions().push_character(a.dwData);
break;
case QIT_DEADKEY:
state->context().push_marker(a.dwData);
state->actions().push_marker(a.dwData);
break;
case QIT_BELL:
state->actions().push_alert();
break;
case QIT_BACK:
switch (a.dwData) {
case BK_DEFAULT:
// This only happens if we know we have context to delete. Last item must be a character
assert(!state->context().empty());
assert(state->context().back().type != KM_KBP_IT_MARKER);
if(!state->context().empty()) {
auto item = state->context().back();
state->context().pop_back();
state->actions().push_backspace(KM_KBP_BT_CHAR, item.character);
} else {
// Note: only runs on non-debug build, fail safe
state->actions().push_backspace(KM_KBP_BT_UNKNOWN);
}
break;
case BK_DEADKEY:
// This only happens if we know we have context to delete. Last item must be a deadkey
assert(!state->context().empty());
assert(state->context().back().type == KM_KBP_IT_MARKER);
if(!state->context().empty()) {
auto item = state->context().back();
state->context().pop_back();
state->actions().push_backspace(KM_KBP_BT_MARKER, item.marker);
} else {
// Note: only runs on non-debug build, fail safe
state->actions().push_backspace(KM_KBP_BT_UNKNOWN);
}
break;
default:
assert(false);
}
break;
case QIT_INVALIDATECONTEXT:
state->actions().push_invalidate_context();
break;
default:
// std::cout << "Unexpected item type " << a.ItemType << ", " << a.dwData << std::endl;
assert(false);
}
}
state->actions().commit();
return KM_KBP_STATUS_OK;
}
constexpr km_kbp_attr const engine_attrs = {
256,
KM_KBP_LIB_CURRENT,
KM_KBP_LIB_AGE,
KM_KBP_LIB_REVISION,
KM_KBP_TECH_KMX,
"SIL International"
};
km_kbp_attr const & kmx_processor::attributes() const {
return engine_attrs;
}
km_kbp_keyboard_key * kmx_processor::get_key_list() const {
// Iterate through the groups and get the rules with virtual keys
// and store the key along with the modifer.
const uint32_t group_cnt = _kmx.GetKeyboard()->Keyboard->cxGroupArray;
const LPGROUP group_array = _kmx.GetKeyboard()->Keyboard->dpGroupArray;
GROUP *p_group;
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t> map_rules;
km_kbp_virtual_key v_key;
uint32_t modifier_flag;
// Use hash map to get the unique list
for(auto i = decltype(group_cnt){0}; i < group_cnt; i++)
{
p_group = &group_array[i];
if(p_group->fUsingKeys)
{
for(auto j = decltype(p_group->cxKeyArray){0}; j < p_group->cxKeyArray; j++)
{
v_key = p_group->dpKeyArray[j].Key;
modifier_flag = p_group->dpKeyArray[j].ShiftFlags;
if(modifier_flag == 0) {
// This must be a ASCII character corresponding US Keyboard key cap
if(!MapUSCharToVK(v_key, &v_key, &modifier_flag)) continue;
}
map_rules[std::make_pair(v_key,modifier_flag)] = (modifier_flag & K_MODIFIERFLAG); // Clear kmx special flags
}
}
}
// Now convert to the keyboard key array
km_kbp_keyboard_key *rules = new km_kbp_keyboard_key[map_rules.size() + 1];
std::map<std::pair<km_kbp_virtual_key,uint32_t>, uint32_t>::iterator it = map_rules.begin();
int n = 0;
while (it != map_rules.end()){
auto pair = it->first;
rules[n].key = pair.first;
rules[n].modifier_flag = it->second;
it++;
n++;
}
// Insert list termination
rules[n] = KM_KBP_KEYBOARD_KEY_LIST_END;
return rules;
}
|
add comment for clarity
|
feat(windows): add comment for clarity
|
C++
|
apache-2.0
|
tavultesoft/keymanweb,tavultesoft/keymanweb
|
5164bc1eaed7c4432532126b92d4035ea38d74fd
|
compiler/passes/returnStarTuplesByRefArgs.cpp
|
compiler/passes/returnStarTuplesByRefArgs.cpp
|
/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "astutil.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
//
// returnStarTuplesByRefArgs changes all functions that return star
// tuples into function that take, as arguments, references to these
// star tuples and assign the values into these references
//
void returnStarTuplesByRefArgs() {
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
if ((fn->retType->symbol->hasFlag(FLAG_STAR_TUPLE))) {
SET_LINENO(fn);
//
// change function interface to take a reference
//
Symbol* ret = fn->getReturnSymbol();
//
// Is it redundant to make this both have ref intent and ref type?
//
ArgSymbol* arg = new ArgSymbol(INTENT_REF, "_ret", ret->type->refType);
fn->insertFormalAtTail(arg);
fn->retType = dtVoid;
fn->insertBeforeReturn(new CallExpr(PRIM_MOVE, arg, ret));
CallExpr* call = toCallExpr(fn->body->body.tail);
INT_ASSERT(call && call->isPrimitive(PRIM_RETURN));
call->get(1)->replace(new SymExpr(gVoid));
//
// update call sites to new interface
//
forv_Vec(CallExpr, call, *fn->calledBy) {
SET_LINENO(call);
CallExpr* move = toCallExpr(call->parentExpr);
if (!move) {
//
// insert dummy to capture return
//
Symbol* tmp = newTemp(ret->type);
call->insertBefore(new DefExpr(tmp));
move = new CallExpr(PRIM_MOVE, tmp, call->remove());
tmp->defPoint->insertAfter(move);
}
SymExpr* actual = toSymExpr(move->get(1));
actual->remove();
if (actual->typeInfo() != arg->type) {
Symbol* tmp = newTemp(arg->type);
move->insertBefore(new DefExpr(tmp));
move->insertBefore(new CallExpr(PRIM_MOVE, tmp,
new CallExpr(PRIM_ADDR_OF, actual)));
actual = new SymExpr(tmp);
}
move->replace(call->remove());
call->insertAtTail(actual);
}
}
}
//
// replace SET/GET_MEMBER primitives on star tuples with
// SET/GET_SVEC_MEMBER primitives
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_SET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER_VALUE)) {
Type* type = call->get(1)->getValType();
if (type->symbol->hasFlag(FLAG_STAR_TUPLE)) {
SET_LINENO(call);
AggregateType* ct = toAggregateType(type);
SymExpr* se = toSymExpr(call->get(2));
int i = atoi(se->var->name+1);
INT_ASSERT(i >= 1 && i <= ct->fields.length);
if (call->isPrimitive(PRIM_SET_MEMBER))
call->primitive = primitives[PRIM_SET_SVEC_MEMBER];
else if (call->isPrimitive(PRIM_GET_MEMBER))
call->primitive = primitives[PRIM_GET_SVEC_MEMBER];
else if (call->isPrimitive(PRIM_GET_MEMBER_VALUE))
call->primitive = primitives[PRIM_GET_SVEC_MEMBER_VALUE];
call->get(2)->replace(new SymExpr(new_IntSymbol(i)));
}
}
}
}
|
/*
* Copyright 2004-2014 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is 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 "astutil.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
//
// returnStarTuplesByRefArgs changes all functions that return star
// tuples into function that take, as arguments, references to these
// star tuples and assign the values into these references
//
void returnStarTuplesByRefArgs() {
compute_call_sites();
forv_Vec(FnSymbol, fn, gFnSymbols) {
if ((fn->retType->symbol->hasFlag(FLAG_STAR_TUPLE))) {
SET_LINENO(fn);
//
// change function interface to take a reference
//
Symbol* ret = fn->getReturnSymbol();
//
// Is it redundant to make this both have ref intent and ref type?
//
ArgSymbol* arg = new ArgSymbol(INTENT_REF, "_ret", ret->type->refType);
fn->insertFormalAtTail(arg);
fn->retType = dtVoid;
fn->insertBeforeReturnAfterLabel(new CallExpr(PRIM_MOVE, arg, ret));
CallExpr* call = toCallExpr(fn->body->body.tail);
INT_ASSERT(call && call->isPrimitive(PRIM_RETURN));
call->get(1)->replace(new SymExpr(gVoid));
//
// update call sites to new interface
//
forv_Vec(CallExpr, call, *fn->calledBy) {
SET_LINENO(call);
CallExpr* move = toCallExpr(call->parentExpr);
if (!move) {
//
// insert dummy to capture return
//
Symbol* tmp = newTemp(ret->type);
call->insertBefore(new DefExpr(tmp));
move = new CallExpr(PRIM_MOVE, tmp, call->remove());
tmp->defPoint->insertAfter(move);
}
SymExpr* actual = toSymExpr(move->get(1));
actual->remove();
if (actual->typeInfo() != arg->type) {
Symbol* tmp = newTemp(arg->type);
move->insertBefore(new DefExpr(tmp));
move->insertBefore(new CallExpr(PRIM_MOVE, tmp,
new CallExpr(PRIM_ADDR_OF, actual)));
actual = new SymExpr(tmp);
}
move->replace(call->remove());
call->insertAtTail(actual);
}
}
}
//
// replace SET/GET_MEMBER primitives on star tuples with
// SET/GET_SVEC_MEMBER primitives
//
forv_Vec(CallExpr, call, gCallExprs) {
if (call->isPrimitive(PRIM_SET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER) ||
call->isPrimitive(PRIM_GET_MEMBER_VALUE)) {
Type* type = call->get(1)->getValType();
if (type->symbol->hasFlag(FLAG_STAR_TUPLE)) {
SET_LINENO(call);
AggregateType* ct = toAggregateType(type);
SymExpr* se = toSymExpr(call->get(2));
int i = atoi(se->var->name+1);
INT_ASSERT(i >= 1 && i <= ct->fields.length);
if (call->isPrimitive(PRIM_SET_MEMBER))
call->primitive = primitives[PRIM_SET_SVEC_MEMBER];
else if (call->isPrimitive(PRIM_GET_MEMBER))
call->primitive = primitives[PRIM_GET_SVEC_MEMBER];
else if (call->isPrimitive(PRIM_GET_MEMBER_VALUE))
call->primitive = primitives[PRIM_GET_SVEC_MEMBER_VALUE];
call->get(2)->replace(new SymExpr(new_IntSymbol(i)));
}
}
}
}
|
Make returnStarTuplesByRefArgs() put the return variable write-back in the right place.
|
Make returnStarTuplesByRefArgs() put the return variable write-back in the right place.
I stumbled across this long-standing bug after disabling returnRecordsByRefArguments().
Apparently that routine covered at least some cases that must be handled by
returnStartTuplesByRefArgs() when it is disabled.
If there is an early return in the routine, it will jump to the exit label. As written,
returnStarTuplesByRefArgs() was putting the write-back to the return variable before the
exit label. This works fine for the straight-line path, but fails to write out the result
when the early return fires. This results in the caller using uninitialized memory, which
is generally bad.
The fix is a one-liner. The call to insertBeforeReturn() that inserts the write-back was
changed to insertBeforeReturnAfterLabel(). That puts the write-back in the right place.
|
C++
|
apache-2.0
|
hildeth/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel
|
f021a7a011573764e31bbe00f9283e5b09b74362
|
lib/sanitizer_common/sanitizer_stacktrace.cc
|
lib/sanitizer_common/sanitizer_stacktrace.cc
|
//===-- sanitizer_stacktrace.cc -------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_flags.h"
#include "sanitizer_stacktrace.h"
namespace __sanitizer {
uptr StackTrace::GetNextInstructionPc(uptr pc) {
#if defined(__mips__)
return pc + 8;
#elif defined(__powerpc__)
return pc + 4;
#else
return pc + 1;
#endif
}
uptr StackTrace::GetCurrentPc() {
return GET_CALLER_PC();
}
void BufferedStackTrace::Init(const uptr *pcs, uptr cnt, uptr extra_top_pc) {
size = cnt + !!extra_top_pc;
CHECK_LE(size, kStackTraceMax);
internal_memcpy(trace_buffer, pcs, cnt * sizeof(trace_buffer[0]));
if (extra_top_pc)
trace_buffer[cnt] = extra_top_pc;
top_frame_bp = 0;
}
// In GCC on ARM bp points to saved lr, not fp, so we should check the next
// cell in stack to be a saved frame pointer. GetCanonicFrame returns the
// pointer to saved frame pointer in any case.
static inline uhwptr *GetCanonicFrame(uptr bp,
uptr stack_top,
uptr stack_bottom) {
#ifdef __arm__
if (!IsValidFrame(bp, stack_top, stack_bottom)) return 0;
uhwptr *bp_prev = (uhwptr *)bp;
if (IsValidFrame((uptr)bp_prev[0], stack_top, stack_bottom)) return bp_prev;
// The next frame pointer does not look right. This could be a GCC frame, step
// back by 1 word and try again.
if (IsValidFrame((uptr)bp_prev[-1], stack_top, stack_bottom))
return bp_prev - 1;
// Nope, this does not look right either. This means the frame after next does
// not have a valid frame pointer, but we can still extract the caller PC.
// Unfortunately, there is no way to decide between GCC and LLVM frame
// layouts. Assume LLVM.
return bp_prev;
#else
return (uhwptr*)bp;
#endif
}
void BufferedStackTrace::FastUnwindStack(uptr pc, uptr bp, uptr stack_top,
uptr stack_bottom, u32 max_depth) {
CHECK_GE(max_depth, 2);
trace_buffer[0] = pc;
size = 1;
if (stack_top < 4096) return; // Sanity check for stack top.
uhwptr *frame = GetCanonicFrame(bp, stack_top, stack_bottom);
// Lowest possible address that makes sense as the next frame pointer.
// Goes up as we walk the stack.
uptr bottom = stack_bottom;
// Avoid infinite loop when frame == frame[0] by using frame > prev_frame.
while (IsValidFrame((uptr)frame, stack_top, bottom) &&
IsAligned((uptr)frame, sizeof(*frame)) &&
size < max_depth) {
#ifdef __powerpc__
// PowerPC ABIs specify that the return address is saved at offset
// 16 of the *caller's* stack frame. Thus we must dereference the
// back chain to find the caller frame before extracting it.
uhwptr *caller_frame = (uhwptr*)frame[0];
if (!IsValidFrame((uptr)caller_frame, stack_top, bottom) ||
!IsAligned((uptr)caller_frame, sizeof(uhwptr)))
break;
uhwptr pc1 = caller_frame[2];
#elif defined(__s390__)
uhwptr pc1 = frame[14];
#else
uhwptr pc1 = frame[1];
#endif
if (pc1 != pc) {
trace_buffer[size++] = (uptr) pc1;
}
bottom = (uptr)frame;
frame = GetCanonicFrame((uptr)frame[0], stack_top, bottom);
}
}
static bool MatchPc(uptr cur_pc, uptr trace_pc, uptr threshold) {
return cur_pc - trace_pc <= threshold || trace_pc - cur_pc <= threshold;
}
void BufferedStackTrace::PopStackFrames(uptr count) {
CHECK_LT(count, size);
size -= count;
for (uptr i = 0; i < size; ++i) {
trace_buffer[i] = trace_buffer[i + count];
}
}
uptr BufferedStackTrace::LocatePcInTrace(uptr pc) {
// Use threshold to find PC in stack trace, as PC we want to unwind from may
// slightly differ from return address in the actual unwinded stack trace.
const int kPcThreshold = 320;
for (uptr i = 0; i < size; ++i) {
if (MatchPc(pc, trace[i], kPcThreshold))
return i;
}
return 0;
}
} // namespace __sanitizer
|
//===-- sanitizer_stacktrace.cc -------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer
// run-time libraries.
//===----------------------------------------------------------------------===//
#include "sanitizer_common.h"
#include "sanitizer_flags.h"
#include "sanitizer_stacktrace.h"
namespace __sanitizer {
uptr StackTrace::GetNextInstructionPc(uptr pc) {
#if defined(__mips__)
return pc + 8;
#elif defined(__powerpc__)
return pc + 4;
#else
return pc + 1;
#endif
}
uptr StackTrace::GetCurrentPc() {
return GET_CALLER_PC();
}
void BufferedStackTrace::Init(const uptr *pcs, uptr cnt, uptr extra_top_pc) {
size = cnt + !!extra_top_pc;
CHECK_LE(size, kStackTraceMax);
internal_memcpy(trace_buffer, pcs, cnt * sizeof(trace_buffer[0]));
if (extra_top_pc)
trace_buffer[cnt] = extra_top_pc;
top_frame_bp = 0;
}
// In GCC on ARM bp points to saved lr, not fp, so we should check the next
// cell in stack to be a saved frame pointer. GetCanonicFrame returns the
// pointer to saved frame pointer in any case.
static inline uhwptr *GetCanonicFrame(uptr bp,
uptr stack_top,
uptr stack_bottom) {
#ifdef __arm__
if (!IsValidFrame(bp, stack_top, stack_bottom)) return 0;
uhwptr *bp_prev = (uhwptr *)bp;
if (IsValidFrame((uptr)bp_prev[0], stack_top, stack_bottom)) return bp_prev;
// The next frame pointer does not look right. This could be a GCC frame, step
// back by 1 word and try again.
if (IsValidFrame((uptr)bp_prev[-1], stack_top, stack_bottom))
return bp_prev - 1;
// Nope, this does not look right either. This means the frame after next does
// not have a valid frame pointer, but we can still extract the caller PC.
// Unfortunately, there is no way to decide between GCC and LLVM frame
// layouts. Assume LLVM.
return bp_prev;
#else
return (uhwptr*)bp;
#endif
}
void BufferedStackTrace::FastUnwindStack(uptr pc, uptr bp, uptr stack_top,
uptr stack_bottom, u32 max_depth) {
CHECK_GE(max_depth, 2);
trace_buffer[0] = pc;
size = 1;
if (stack_top < 4096) return; // Sanity check for stack top.
uhwptr *frame = GetCanonicFrame(bp, stack_top, stack_bottom);
// Lowest possible address that makes sense as the next frame pointer.
// Goes up as we walk the stack.
uptr bottom = stack_bottom;
// Avoid infinite loop when frame == frame[0] by using frame > prev_frame.
while (IsValidFrame((uptr)frame, stack_top, bottom) &&
IsAligned((uptr)frame, sizeof(*frame)) &&
size < max_depth) {
#ifdef __powerpc__
// PowerPC ABIs specify that the return address is saved at offset
// 16 of the *caller's* stack frame. Thus we must dereference the
// back chain to find the caller frame before extracting it.
uhwptr *caller_frame = (uhwptr*)frame[0];
if (!IsValidFrame((uptr)caller_frame, stack_top, bottom) ||
!IsAligned((uptr)caller_frame, sizeof(uhwptr)))
break;
uhwptr pc1 = caller_frame[2];
#elif defined(__s390__)
uhwptr pc1 = frame[14];
#else
uhwptr pc1 = frame[1];
#endif
if (pc1 != pc) {
trace_buffer[size++] = (uptr) pc1;
}
bottom = (uptr)frame;
frame = GetCanonicFrame((uptr)frame[0], stack_top, bottom);
}
}
static bool MatchPc(uptr cur_pc, uptr trace_pc, uptr threshold) {
return cur_pc - trace_pc <= threshold || trace_pc - cur_pc <= threshold;
}
void BufferedStackTrace::PopStackFrames(uptr count) {
CHECK_LT(count, size);
size -= count;
for (uptr i = 0; i < size; ++i) {
trace_buffer[i] = trace_buffer[i + count];
}
}
uptr BufferedStackTrace::LocatePcInTrace(uptr pc) {
// Use threshold to find PC in stack trace, as PC we want to unwind from may
// slightly differ from return address in the actual unwinded stack trace.
const int kPcThreshold = 350;
for (uptr i = 0; i < size; ++i) {
if (MatchPc(pc, trace[i], kPcThreshold))
return i;
}
return 0;
}
} // namespace __sanitizer
|
Increase LocatePcInTrace threshold.
|
[asan] Increase LocatePcInTrace threshold.
Not sure what changed, but on my machine this is literally one byte
short. Only happens when malloc_context_size <= 2 due to the special
case in GET_STACK_TRACE definition (see asan_stack.h):
StackTrace::GetCurrentPc() on the right (context size > 2) branch
returns the address that is 200-something bytes from the return
address it is later matched to, while the same call on the left
branch is 321 bytes away from it.
This fixes the double-free test on my machine.
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@266932 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
9419014690715aa3208d6f311b5b90c9ed0208c0
|
src/cubez.cpp
|
src/cubez.cpp
|
#include <cubez/cubez.h>
#include "defs.h"
#include "private_universe.h"
#include "byte_vector.h"
#include "component.h"
#include "system_impl.h"
#define AS_PRIVATE(expr) ((PrivateUniverse*)(universe_->self))->expr
const qbVar qbNone = { QB_TAG_VOID, 0 };
static qbUniverse* universe_ = nullptr;
Coro main;
qbResult qb_init(qbUniverse* u) {
universe_ = u;
universe_->self = new PrivateUniverse();
main = coro_init();
return AS_PRIVATE(init());
}
qbResult qb_start() {
return AS_PRIVATE(start());
}
qbResult qb_stop() {
qbResult ret = AS_PRIVATE(stop());
universe_ = nullptr;
return ret;
}
qbResult qb_loop() {
return AS_PRIVATE(loop());
}
qbId qb_create_program(const char* name) {
return AS_PRIVATE(create_program(name));
}
qbResult qb_run_program(qbId program) {
return AS_PRIVATE(run_program(program));
}
qbResult qb_detach_program(qbId program) {
return AS_PRIVATE(detach_program(program));
}
qbResult qb_join_program(qbId program) {
return AS_PRIVATE(join_program(program));
}
qbResult qb_system_enable(qbSystem system) {
return AS_PRIVATE(enable_system(system));
}
qbResult qb_system_disable(qbSystem system) {
return AS_PRIVATE(disable_system(system));
}
qbResult qb_componentattr_create(qbComponentAttr* attr) {
*attr = (qbComponentAttr)calloc(1, sizeof(qbComponentAttr_));
new (*attr) qbComponentAttr_;
(*attr)->is_shared = false;
(*attr)->type = qbComponentType::QB_COMPONENT_TYPE_RAW;
return qbResult::QB_OK;
}
qbResult qb_componentattr_destroy(qbComponentAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_componentattr_setdatasize(qbComponentAttr attr, size_t size) {
attr->data_size = size;
return qbResult::QB_OK;
}
qbResult qb_componentattr_settype(qbComponentAttr attr, qbComponentType type) {
attr->type = type;
return qbResult::QB_OK;
}
qbResult qb_componentattr_setshared(qbComponentAttr attr) {
attr->is_shared = true;
return qbResult::QB_OK;
}
qbResult qb_component_create(
qbComponent* component, qbComponentAttr attr) {
return AS_PRIVATE(component_create(component, attr));
}
qbResult qb_component_destroy(qbComponent*) {
return qbResult::QB_OK;
}
size_t qb_component_getcount(qbComponent component) {
return AS_PRIVATE(component_getcount(component));
}
qbResult qb_entityattr_create(qbEntityAttr* attr) {
*attr = (qbEntityAttr)calloc(1, sizeof(qbEntityAttr_));
new (*attr) qbEntityAttr_;
return qbResult::QB_OK;
}
qbResult qb_entityattr_destroy(qbEntityAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_entityattr_addcomponent(qbEntityAttr attr, qbComponent component,
void* instance_data) {
attr->component_list.push_back({component, instance_data});
return qbResult::QB_OK;
}
qbResult qb_entity_create(qbEntity* entity, qbEntityAttr attr) {
return AS_PRIVATE(entity_create(entity, *attr));
}
qbResult qb_entity_destroy(qbEntity entity) {
return AS_PRIVATE(entity_destroy(entity));
}
bool qb_entity_hascomponent(qbEntity entity, qbComponent component) {
return AS_PRIVATE(entity_hascomponent(entity, component));
}
qbResult qb_entity_addcomponent(qbEntity entity, qbComponent component,
void* instance_data) {
return AS_PRIVATE(entity_addcomponent(entity, component, instance_data));
}
qbResult qb_entity_removecomponent(qbEntity entity, qbComponent component) {
return AS_PRIVATE(entity_removecomponent(entity, component));
}
qbId qb_entity_getid(qbEntity entity) {
return entity;
}
qbResult qb_barrier_create(qbBarrier* barrier) {
*barrier = AS_PRIVATE(barrier_create());
return QB_OK;
}
qbResult qb_barrier_destroy(qbBarrier* barrier) {
AS_PRIVATE(barrier_destroy(*barrier));
return QB_OK;
}
qbResult qb_systemattr_create(qbSystemAttr* attr) {
*attr = (qbSystemAttr)calloc(1, sizeof(qbSystemAttr_));
new (*attr) qbSystemAttr_;
return qbResult::QB_OK;
}
qbResult qb_systemattr_destroy(qbSystemAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setprogram(qbSystemAttr attr, qbId program) {
attr->program = program;
return qbResult::QB_OK;
}
qbResult qb_systemattr_addconst(qbSystemAttr attr, qbComponent component) {
attr->constants.push_back(component);
attr->components.push_back(component);
return qbResult::QB_OK;
}
qbResult qb_systemattr_addmutable(qbSystemAttr attr, qbComponent component) {
attr->mutables.push_back(component);
attr->components.push_back(component);
return qbResult::QB_OK;
}
qbResult qb_systemattr_setfunction(qbSystemAttr attr, qbTransform transform) {
attr->transform = transform;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setcallback(qbSystemAttr attr, qbCallback callback) {
attr->callback = callback;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setcondition(qbSystemAttr attr, qbCondition condition) {
attr->condition = condition;
return qbResult::QB_OK;
}
qbResult qb_systemattr_settrigger(qbSystemAttr attr, qbTrigger trigger) {
attr->trigger = trigger;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setpriority(qbSystemAttr attr, int16_t priority) {
attr->priority = priority;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setjoin(qbSystemAttr attr, qbComponentJoin join) {
attr->join = join;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setuserstate(qbSystemAttr attr, void* state) {
attr->state = state;
return qbResult::QB_OK;
}
qbResult qb_systemattr_addbarrier(qbSystemAttr attr,
qbBarrier barrier) {
qbTicket_* t = new qbTicket_;
t->impl = ((Barrier*)barrier->impl)->MakeTicket().release();
t->lock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->lock(); };
t->unlock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->unlock(); };
attr->tickets.push_back(t);
return QB_OK;
}
qbResult qb_system_create(qbSystem* system, qbSystemAttr attr) {
if (!attr->program) {
attr->program = 0;
}
#ifdef __ENGINE_DEBUG__
DEBUG_ASSERT(attr->transform || attr->callback,
qbResult::QB_ERROR_SYSTEMATTR_HAS_FUNCTION_OR_CALLBACK);
#endif
AS_PRIVATE(system_create(system, *attr));
return qbResult::QB_OK;
}
qbResult qb_system_destroy(qbSystem*) {
return qbResult::QB_OK;
}
qbResult qb_eventattr_create(qbEventAttr* attr) {
*attr = (qbEventAttr)calloc(1, sizeof(qbEventAttr_));
new (*attr) qbEventAttr_;
return qbResult::QB_OK;
}
qbResult qb_eventattr_destroy(qbEventAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_eventattr_setprogram(qbEventAttr attr, qbId program) {
attr->program = program;
return qbResult::QB_OK;
}
qbResult qb_eventattr_setmessagesize(qbEventAttr attr, size_t size) {
attr->message_size = size;
return qbResult::QB_OK;
}
qbResult qb_event_create(qbEvent* event, qbEventAttr attr) {
if (!attr->program) {
attr->program = 0;
}
#ifdef __ENGINE_DEBUG__
DEBUG_ASSERT(attr->message_size > 0,
qbResult::QB_ERROR_EVENTATTR_MESSAGE_SIZE_IS_ZERO);
#endif
return AS_PRIVATE(event_create(event, attr));
}
qbResult qb_event_destroy(qbEvent* event) {
return AS_PRIVATE(event_destroy(event));
}
qbResult qb_event_flushall(qbProgram program) {
return AS_PRIVATE(event_flushall(program));
}
qbResult qb_event_subscribe(qbEvent event, qbSystem system) {
return AS_PRIVATE(event_subscribe(event, system));
}
qbResult qb_event_unsubscribe(qbEvent event, qbSystem system) {
return AS_PRIVATE(event_unsubscribe(event, system));
}
qbResult qb_event_send(qbEvent event, void* message) {
return AS_PRIVATE(event_send(event, message));
}
qbResult qb_event_sendsync(qbEvent event, void* message) {
return AS_PRIVATE(event_sendsync(event, message));
}
qbResult qb_instance_oncreate(qbComponent component,
qbInstanceOnCreate on_create) {
return AS_PRIVATE(instance_oncreate(component, on_create));
}
qbResult qb_instance_ondestroy(qbComponent component,
qbInstanceOnDestroy on_destroy) {
return AS_PRIVATE(instance_ondestroy(component, on_destroy));
}
qbEntity qb_instance_getentity(qbInstance instance) {
return instance->entity;
}
qbResult qb_instance_getconst(qbInstance instance, void* pbuffer) {
return AS_PRIVATE(instance_getconst(instance, pbuffer));
}
qbResult qb_instance_getmutable(qbInstance instance, void* pbuffer) {
return AS_PRIVATE(instance_getmutable(instance, pbuffer));
}
qbResult qb_instance_getcomponent(qbInstance instance, qbComponent component, void* pbuffer) {
return AS_PRIVATE(instance_getcomponent(instance, component, pbuffer));
}
bool qb_instance_hascomponent(qbInstance instance, qbComponent component) {
return AS_PRIVATE(instance_hascomponent(instance, component));
}
qbResult qb_instance_find(qbComponent component, qbEntity entity, void* pbuffer) {
return AS_PRIVATE(instance_find(component, entity, pbuffer));
}
qbCoro qb_coro_create(qbVar(*entry)(qbVar var)) {
qbCoro ret = new qbCoro_();
ret->main = coro_new(entry);
return ret;
}
qbResult qb_coro_destroy(qbCoro* coro) {
delete *coro;
return QB_OK;
}
qbVar qb_coro_run(qbCoro coro, qbVar var) {
return coro_call(coro->main, var);
}
qbVar qb_coro_yield(qbVar var) {
return coro_yield(var);
}
qbVar qbVoid(void* p) {
qbVar v;
v.tag = QB_TAG_VOID;
v.p = p;
return v;
}
qbVar qbUint(uint64_t u) {
qbVar v;
v.tag = QB_TAG_UINT;
v.u = u;
return v;
}
qbVar qbInt(int64_t i) {
qbVar v;
v.tag = QB_TAG_INT;
v.i = i;
return v;
}
qbVar qbDouble(double d) {
qbVar v;
v.tag = QB_TAG_DOUBLE;
v.d = d;
return v;
}
qbVar qbChar(char c) {
qbVar v;
v.tag = QB_TAG_CHAR;
v.c = c;
return v;
}
|
#include <cubez/cubez.h>
#include "defs.h"
#include "private_universe.h"
#include "byte_vector.h"
#include "component.h"
#include "system_impl.h"
#include "utils_internal.h"
#define AS_PRIVATE(expr) ((PrivateUniverse*)(universe_->self))->expr
const qbVar qbNone = { QB_TAG_VOID, 0 };
static qbUniverse* universe_ = nullptr;
Coro main;
qbResult qb_init(qbUniverse* u) {
utils_initialize();
universe_ = u;
universe_->self = new PrivateUniverse();
main = coro_init();
return AS_PRIVATE(init());
}
qbResult qb_start() {
return AS_PRIVATE(start());
}
qbResult qb_stop() {
qbResult ret = AS_PRIVATE(stop());
universe_ = nullptr;
return ret;
}
qbResult qb_loop() {
return AS_PRIVATE(loop());
}
qbId qb_create_program(const char* name) {
return AS_PRIVATE(create_program(name));
}
qbResult qb_run_program(qbId program) {
return AS_PRIVATE(run_program(program));
}
qbResult qb_detach_program(qbId program) {
return AS_PRIVATE(detach_program(program));
}
qbResult qb_join_program(qbId program) {
return AS_PRIVATE(join_program(program));
}
qbResult qb_system_enable(qbSystem system) {
return AS_PRIVATE(enable_system(system));
}
qbResult qb_system_disable(qbSystem system) {
return AS_PRIVATE(disable_system(system));
}
qbResult qb_componentattr_create(qbComponentAttr* attr) {
*attr = (qbComponentAttr)calloc(1, sizeof(qbComponentAttr_));
new (*attr) qbComponentAttr_;
(*attr)->is_shared = false;
(*attr)->type = qbComponentType::QB_COMPONENT_TYPE_RAW;
return qbResult::QB_OK;
}
qbResult qb_componentattr_destroy(qbComponentAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_componentattr_setdatasize(qbComponentAttr attr, size_t size) {
attr->data_size = size;
return qbResult::QB_OK;
}
qbResult qb_componentattr_settype(qbComponentAttr attr, qbComponentType type) {
attr->type = type;
return qbResult::QB_OK;
}
qbResult qb_componentattr_setshared(qbComponentAttr attr) {
attr->is_shared = true;
return qbResult::QB_OK;
}
qbResult qb_component_create(
qbComponent* component, qbComponentAttr attr) {
return AS_PRIVATE(component_create(component, attr));
}
qbResult qb_component_destroy(qbComponent*) {
return qbResult::QB_OK;
}
size_t qb_component_getcount(qbComponent component) {
return AS_PRIVATE(component_getcount(component));
}
qbResult qb_entityattr_create(qbEntityAttr* attr) {
*attr = (qbEntityAttr)calloc(1, sizeof(qbEntityAttr_));
new (*attr) qbEntityAttr_;
return qbResult::QB_OK;
}
qbResult qb_entityattr_destroy(qbEntityAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_entityattr_addcomponent(qbEntityAttr attr, qbComponent component,
void* instance_data) {
attr->component_list.push_back({component, instance_data});
return qbResult::QB_OK;
}
qbResult qb_entity_create(qbEntity* entity, qbEntityAttr attr) {
return AS_PRIVATE(entity_create(entity, *attr));
}
qbResult qb_entity_destroy(qbEntity entity) {
return AS_PRIVATE(entity_destroy(entity));
}
bool qb_entity_hascomponent(qbEntity entity, qbComponent component) {
return AS_PRIVATE(entity_hascomponent(entity, component));
}
qbResult qb_entity_addcomponent(qbEntity entity, qbComponent component,
void* instance_data) {
return AS_PRIVATE(entity_addcomponent(entity, component, instance_data));
}
qbResult qb_entity_removecomponent(qbEntity entity, qbComponent component) {
return AS_PRIVATE(entity_removecomponent(entity, component));
}
qbId qb_entity_getid(qbEntity entity) {
return entity;
}
qbResult qb_barrier_create(qbBarrier* barrier) {
*barrier = AS_PRIVATE(barrier_create());
return QB_OK;
}
qbResult qb_barrier_destroy(qbBarrier* barrier) {
AS_PRIVATE(barrier_destroy(*barrier));
return QB_OK;
}
qbResult qb_systemattr_create(qbSystemAttr* attr) {
*attr = (qbSystemAttr)calloc(1, sizeof(qbSystemAttr_));
new (*attr) qbSystemAttr_;
return qbResult::QB_OK;
}
qbResult qb_systemattr_destroy(qbSystemAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setprogram(qbSystemAttr attr, qbId program) {
attr->program = program;
return qbResult::QB_OK;
}
qbResult qb_systemattr_addconst(qbSystemAttr attr, qbComponent component) {
attr->constants.push_back(component);
attr->components.push_back(component);
return qbResult::QB_OK;
}
qbResult qb_systemattr_addmutable(qbSystemAttr attr, qbComponent component) {
attr->mutables.push_back(component);
attr->components.push_back(component);
return qbResult::QB_OK;
}
qbResult qb_systemattr_setfunction(qbSystemAttr attr, qbTransform transform) {
attr->transform = transform;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setcallback(qbSystemAttr attr, qbCallback callback) {
attr->callback = callback;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setcondition(qbSystemAttr attr, qbCondition condition) {
attr->condition = condition;
return qbResult::QB_OK;
}
qbResult qb_systemattr_settrigger(qbSystemAttr attr, qbTrigger trigger) {
attr->trigger = trigger;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setpriority(qbSystemAttr attr, int16_t priority) {
attr->priority = priority;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setjoin(qbSystemAttr attr, qbComponentJoin join) {
attr->join = join;
return qbResult::QB_OK;
}
qbResult qb_systemattr_setuserstate(qbSystemAttr attr, void* state) {
attr->state = state;
return qbResult::QB_OK;
}
qbResult qb_systemattr_addbarrier(qbSystemAttr attr,
qbBarrier barrier) {
qbTicket_* t = new qbTicket_;
t->impl = ((Barrier*)barrier->impl)->MakeTicket().release();
t->lock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->lock(); };
t->unlock = [ticket{ t->impl }]() { ((Barrier::Ticket*)ticket)->unlock(); };
attr->tickets.push_back(t);
return QB_OK;
}
qbResult qb_system_create(qbSystem* system, qbSystemAttr attr) {
if (!attr->program) {
attr->program = 0;
}
#ifdef __ENGINE_DEBUG__
DEBUG_ASSERT(attr->transform || attr->callback,
qbResult::QB_ERROR_SYSTEMATTR_HAS_FUNCTION_OR_CALLBACK);
#endif
AS_PRIVATE(system_create(system, *attr));
return qbResult::QB_OK;
}
qbResult qb_system_destroy(qbSystem*) {
return qbResult::QB_OK;
}
qbResult qb_eventattr_create(qbEventAttr* attr) {
*attr = (qbEventAttr)calloc(1, sizeof(qbEventAttr_));
new (*attr) qbEventAttr_;
return qbResult::QB_OK;
}
qbResult qb_eventattr_destroy(qbEventAttr* attr) {
delete *attr;
*attr = nullptr;
return qbResult::QB_OK;
}
qbResult qb_eventattr_setprogram(qbEventAttr attr, qbId program) {
attr->program = program;
return qbResult::QB_OK;
}
qbResult qb_eventattr_setmessagesize(qbEventAttr attr, size_t size) {
attr->message_size = size;
return qbResult::QB_OK;
}
qbResult qb_event_create(qbEvent* event, qbEventAttr attr) {
if (!attr->program) {
attr->program = 0;
}
#ifdef __ENGINE_DEBUG__
DEBUG_ASSERT(attr->message_size > 0,
qbResult::QB_ERROR_EVENTATTR_MESSAGE_SIZE_IS_ZERO);
#endif
return AS_PRIVATE(event_create(event, attr));
}
qbResult qb_event_destroy(qbEvent* event) {
return AS_PRIVATE(event_destroy(event));
}
qbResult qb_event_flushall(qbProgram program) {
return AS_PRIVATE(event_flushall(program));
}
qbResult qb_event_subscribe(qbEvent event, qbSystem system) {
return AS_PRIVATE(event_subscribe(event, system));
}
qbResult qb_event_unsubscribe(qbEvent event, qbSystem system) {
return AS_PRIVATE(event_unsubscribe(event, system));
}
qbResult qb_event_send(qbEvent event, void* message) {
return AS_PRIVATE(event_send(event, message));
}
qbResult qb_event_sendsync(qbEvent event, void* message) {
return AS_PRIVATE(event_sendsync(event, message));
}
qbResult qb_instance_oncreate(qbComponent component,
qbInstanceOnCreate on_create) {
return AS_PRIVATE(instance_oncreate(component, on_create));
}
qbResult qb_instance_ondestroy(qbComponent component,
qbInstanceOnDestroy on_destroy) {
return AS_PRIVATE(instance_ondestroy(component, on_destroy));
}
qbEntity qb_instance_getentity(qbInstance instance) {
return instance->entity;
}
qbResult qb_instance_getconst(qbInstance instance, void* pbuffer) {
return AS_PRIVATE(instance_getconst(instance, pbuffer));
}
qbResult qb_instance_getmutable(qbInstance instance, void* pbuffer) {
return AS_PRIVATE(instance_getmutable(instance, pbuffer));
}
qbResult qb_instance_getcomponent(qbInstance instance, qbComponent component, void* pbuffer) {
return AS_PRIVATE(instance_getcomponent(instance, component, pbuffer));
}
bool qb_instance_hascomponent(qbInstance instance, qbComponent component) {
return AS_PRIVATE(instance_hascomponent(instance, component));
}
qbResult qb_instance_find(qbComponent component, qbEntity entity, void* pbuffer) {
return AS_PRIVATE(instance_find(component, entity, pbuffer));
}
qbCoro qb_coro_create(qbVar(*entry)(qbVar var)) {
qbCoro ret = new qbCoro_();
ret->main = coro_new(entry);
return ret;
}
qbCoro qb_coro_create_unsafe(qbVar(*entry)(qbVar var), void* stack, size_t stack_size) {
qbCoro ret = new qbCoro_();
ret->main = coro_new_unsafe(entry, (uintptr_t)stack, stack_size);
return ret;
}
qbResult qb_coro_destroy(qbCoro* coro) {
delete *coro;
*coro = nullptr;
return QB_OK;
}
qbVar qb_coro_run(qbCoro coro, qbVar var) {
return coro_call(coro->main, var);
}
qbVar qb_coro_yield(qbVar var) {
return coro_yield(var);
}
qbVar qbVoid(void* p) {
qbVar v;
v.tag = QB_TAG_VOID;
v.p = p;
return v;
}
qbVar qbUint(uint64_t u) {
qbVar v;
v.tag = QB_TAG_UINT;
v.u = u;
return v;
}
qbVar qbInt(int64_t i) {
qbVar v;
v.tag = QB_TAG_INT;
v.i = i;
return v;
}
qbVar qbDouble(double d) {
qbVar v;
v.tag = QB_TAG_DOUBLE;
v.d = d;
return v;
}
qbVar qbChar(char c) {
qbVar v;
v.tag = QB_TAG_CHAR;
v.c = c;
return v;
}
|
Initialize timers
|
Initialize timers
|
C++
|
apache-2.0
|
rohdesamuel/cubez,rohdesamuel/cubez,rohdesamuel/cubez,rohdesamuel/cubez
|
20ccad6f60c5979e8445f7819341e06feae324f9
|
src/dlfcn.cpp
|
src/dlfcn.cpp
|
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/tss.hpp>
#include <iostream>
#include <cstring>
# ifdef _WIN32
# include <windows.h>
# else
# include <dlfcn.h>
# endif
#include <qi/qi.hpp>
#include <qi/path.hpp>
#include "filesystem.hpp"
namespace qi {
namespace os {
void *dlopen(const char *filename, int flag) {
std::string fullName = path::findLib(filename);
if (fullName.empty())
{
qiLogError("qi.dlopen") << "Could not locate library " << filename;
fullName = filename; // Do not return here, let sys call fails and set errno.
}
void *handle = NULL;
boost::filesystem::path fname(fullName, qi::unicodeFacet());
qiLogDebug("qi.dlopen") << "opening " << fname;
#ifdef _WIN32
handle = LoadLibraryW(fname.wstring(qi::unicodeFacet()).c_str());
#else
if (flag == -1)
flag = RTLD_NOW;
handle = ::dlopen(fname.string(qi::unicodeFacet()).c_str(), flag);
#endif
return handle;
}
int dlclose(void *handle) {
if (!handle)
return 0;
#ifdef _WIN32
// Mimic unix dlclose (0 on success)
return FreeLibrary((HINSTANCE) handle) != 0 ? 0 : -1;
#else
return ::dlclose(handle);
#endif
}
void *dlsym(void *handle, const char *symbol) {
void* function = NULL;
if(!handle)
return 0;
#ifdef _WIN32
function = (void *)GetProcAddress((HINSTANCE) handle, symbol);
#else
function = ::dlsym(handle, symbol);
#endif
return function;
}
#ifdef _WIN32
void cleanup(char* ptr)
{
delete[] ptr;
}
#endif // !_WIN32
const char *dlerror(void) {
#ifdef _WIN32
DWORD lastError = GetLastError();
// Unix dlerror() return null if error code is 0
if (lastError == 0)
return NULL;
static boost::thread_specific_ptr<char> err(cleanup);
if (!err.get())
err.reset(static_cast<char*>(new char[255]));
DWORD result = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, lastError, 0, err.get(), sizeof(char) * 255, 0);
// Unix dlerror() resets its value after a call, ensure same behavior
SetLastError(0);
return err.get();
#else
return ::dlerror();
#endif
}
}
}
|
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/tss.hpp>
#include <iostream>
#include <cstring>
# ifdef _WIN32
# include <windows.h>
# else
# include <dlfcn.h>
# endif
#include <qi/qi.hpp>
#include <qi/path.hpp>
#include "filesystem.hpp"
namespace qi {
namespace os {
void *dlopen(const char *filename, int flag) {
std::string fullName = path::findLib(filename);
if (fullName.empty())
{
qiLogError("qi.dlopen") << "Could not locate library " << filename;
fullName = filename; // Do not return here, let sys call fails and set errno.
}
void *handle = NULL;
boost::filesystem::path fname(fullName, qi::unicodeFacet());
qiLogDebug("qi.dlopen") << "opening " << fname;
#ifdef _WIN32
handle = LoadLibraryW(fname.wstring(qi::unicodeFacet()).c_str());
#else
if (flag == -1)
flag = RTLD_NOW;
handle = ::dlopen(fname.string(qi::unicodeFacet()).c_str(), flag);
#endif
return handle;
}
int dlclose(void *handle) {
if (!handle)
return 0;
#ifdef _WIN32
// Mimic unix dlclose (0 on success)
return FreeLibrary((HINSTANCE) handle) != 0 ? 0 : -1;
#else
return ::dlclose(handle);
#endif
}
void *dlsym(void *handle, const char *symbol) {
void* function = NULL;
if(!handle)
return 0;
#ifdef _WIN32
function = (void *)GetProcAddress((HINSTANCE) handle, symbol);
#else
function = ::dlsym(handle, symbol);
#endif
return function;
}
#ifdef _WIN32
void cleanup(char* ptr)
{
delete[] ptr;
}
#endif // !_WIN32
const char *dlerror(void) {
#ifdef _WIN32
DWORD lastError = GetLastError();
// Unix dlerror() return null if error code is 0
if (lastError == 0)
return NULL;
static boost::thread_specific_ptr<char> err(cleanup);
if (!err.get())
err.reset(static_cast<char*>(new char[255]));
DWORD result = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, lastError, 0, err.get(), sizeof(err.get()), 0);
// Unix dlerror() resets its value after a call, ensure same behavior
SetLastError(0);
return err.get();
#else
return ::dlerror();
#endif
}
}
}
|
make dlerror threadsafe on windows
|
make dlerror threadsafe on windows
Change-Id: I023dbc2a5023cbab10447fd1c71d39438c8c8502
Reviewed-on: http://gerrit.aldebaran.lan/19497
Reviewed-by: proullon <[email protected]>
Tested-by: gerrit
Reviewed-by: llec <[email protected]>
|
C++
|
bsd-3-clause
|
bsautron/libqi,aldebaran/libqi,aldebaran/libqi,aldebaran/libqi,vbarbaresi/libqi
|
ffd6d6867fe5a3aad31f42710685aa94a342f0e5
|
src/gurpy.cpp
|
src/gurpy.cpp
|
/******************************************************************************
* Copyright (C) 2015 Sahil Kang <[email protected]>
*
* This file is part of gurpy.
*
* gurpy is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* gurpy 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with gurpy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <Python.h>
#include <gur.hpp>
#include <gurmukhi.hpp>
#include <sstream>
template<typename T>
PyObject* tuple_of_word(PyObject *args, T method)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
gur::Word word = (gur::Word(str).*method)();
PyObject *py_word = PyTuple_New(word.size());
for (std::size_t i = 0; i != word.size(); ++i)
{
PyTuple_SetItem(py_word, i, PyUnicode_FromString(
word[i].str().c_str()));
}
return py_word;
}
static PyObject* gp_letters(PyObject *self, PyObject *args)
{
return tuple_of_word(args, &gur::Word::letters);
}
static PyObject* gp_accents(PyObject *self, PyObject *args)
{
return tuple_of_word(args, &gur::Word::accents);
}
static PyObject* gp_puncs(PyObject *self, PyObject *args)
{
return tuple_of_word(args, &gur::Word::punctuations);
}
static PyObject* gp_digits(PyObject *self, PyObject *args)
{
return tuple_of_word(args, &gur::Word::digits);
}
static PyObject* gp_symbols(PyObject *self, PyObject *args)
{
return tuple_of_word(args, &gur::Word::symbols);
}
static PyObject* gp_comp(PyObject *self, PyObject *args)
{
return tuple_of_word(args, &gur::Word::composition);
}
static PyObject* gp_clobber(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
gur::Word word(str);
std::ostringstream oss;
oss << word;
return PyUnicode_FromString(oss.str().c_str());
}
static PyObject* gp_unclobber(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
gur::Word word(str);
std::ostringstream oss(std::ostringstream::ate);
for (auto &c : word)
{
oss << c;
}
return PyUnicode_FromString(oss.str().c_str());
}
static PyMethodDef gp_methods[] =
{
{"letters", gp_letters, METH_VARARGS, "Get the letters in a word."},
{"accents", gp_accents, METH_VARARGS, "Get the accents in a word."},
{"puncs", gp_puncs, METH_VARARGS, "Get the punctuations in a word."},
{"digits", gp_digits, METH_VARARGS, "Get the digits in a word."},
{"symbols", gp_symbols, METH_VARARGS, "Get the symbols in a word."},
{"comp", gp_comp, METH_VARARGS, "Get a word's composition."},
{"clobber", gp_clobber, METH_VARARGS, "Combine diacritics."},
{"unclobber", gp_unclobber, METH_VARARGS, "Separate diacritics."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef gp_module =
{
PyModuleDef_HEAD_INIT,
"gurpy", //name of the module
"Python extension for libgur", //module doc
-1,
gp_methods
};
PyMODINIT_FUNC PyInit_gurpy(void)
{
PyObject *mod = PyModule_Create(&gp_module);
PyObject_SetAttrString(mod, "a1", PyUnicode_FromString(gur::A1));
PyObject_SetAttrString(mod, "a2", PyUnicode_FromString(gur::A2));
PyObject_SetAttrString(mod, "a3", PyUnicode_FromString(gur::A3));
PyObject_SetAttrString(mod, "a4", PyUnicode_FromString(gur::A4));
PyObject_SetAttrString(mod, "a5", PyUnicode_FromString(gur::A5));
PyObject_SetAttrString(mod, "b1", PyUnicode_FromString(gur::B1));
PyObject_SetAttrString(mod, "b2", PyUnicode_FromString(gur::B2));
PyObject_SetAttrString(mod, "b3", PyUnicode_FromString(gur::B3));
PyObject_SetAttrString(mod, "b4", PyUnicode_FromString(gur::B4));
PyObject_SetAttrString(mod, "b5", PyUnicode_FromString(gur::B5));
PyObject_SetAttrString(mod, "c1", PyUnicode_FromString(gur::C1));
PyObject_SetAttrString(mod, "c2", PyUnicode_FromString(gur::C2));
PyObject_SetAttrString(mod, "c3", PyUnicode_FromString(gur::C3));
PyObject_SetAttrString(mod, "c4", PyUnicode_FromString(gur::C4));
PyObject_SetAttrString(mod, "c5", PyUnicode_FromString(gur::C5));
PyObject_SetAttrString(mod, "d1", PyUnicode_FromString(gur::D1));
PyObject_SetAttrString(mod, "d2", PyUnicode_FromString(gur::D2));
PyObject_SetAttrString(mod, "d3", PyUnicode_FromString(gur::D3));
PyObject_SetAttrString(mod, "d4", PyUnicode_FromString(gur::D4));
PyObject_SetAttrString(mod, "d5", PyUnicode_FromString(gur::D5));
PyObject_SetAttrString(mod, "e1", PyUnicode_FromString(gur::E1));
PyObject_SetAttrString(mod, "e2", PyUnicode_FromString(gur::E2));
PyObject_SetAttrString(mod, "e3", PyUnicode_FromString(gur::E3));
PyObject_SetAttrString(mod, "e4", PyUnicode_FromString(gur::E4));
PyObject_SetAttrString(mod, "e5", PyUnicode_FromString(gur::E5));
PyObject_SetAttrString(mod, "f1", PyUnicode_FromString(gur::F1));
PyObject_SetAttrString(mod, "f2", PyUnicode_FromString(gur::F2));
PyObject_SetAttrString(mod, "f3", PyUnicode_FromString(gur::F3));
PyObject_SetAttrString(mod, "f4", PyUnicode_FromString(gur::F4));
PyObject_SetAttrString(mod, "f5", PyUnicode_FromString(gur::F5));
PyObject_SetAttrString(mod, "g1", PyUnicode_FromString(gur::G1));
PyObject_SetAttrString(mod, "g2", PyUnicode_FromString(gur::G2));
PyObject_SetAttrString(mod, "g3", PyUnicode_FromString(gur::G3));
PyObject_SetAttrString(mod, "g4", PyUnicode_FromString(gur::G4));
PyObject_SetAttrString(mod, "g5", PyUnicode_FromString(gur::G5));
PyObject_SetAttrString(mod, "h1", PyUnicode_FromString(gur::H1));
PyObject_SetAttrString(mod, "h2", PyUnicode_FromString(gur::H2));
PyObject_SetAttrString(mod, "h3", PyUnicode_FromString(gur::H3));
PyObject_SetAttrString(mod, "h4", PyUnicode_FromString(gur::H4));
PyObject_SetAttrString(mod, "h5", PyUnicode_FromString(gur::H5));
PyObject_SetAttrString(mod, "i1", PyUnicode_FromString(gur::I1));
PyObject_SetAttrString(mod, "i2", PyUnicode_FromString(gur::I2));
PyObject_SetAttrString(mod, "i3", PyUnicode_FromString(gur::I3));
PyObject_SetAttrString(mod, "i4", PyUnicode_FromString(gur::I4));
PyObject_SetAttrString(mod, "i5", PyUnicode_FromString(gur::I5));
PyObject_SetAttrString(mod, "j1", PyUnicode_FromString(gur::J1));
PyObject_SetAttrString(mod, "j2", PyUnicode_FromString(gur::J2));
PyObject_SetAttrString(mod, "j3", PyUnicode_FromString(gur::J3));
PyObject_SetAttrString(mod, "j4", PyUnicode_FromString(gur::J4));
PyObject_SetAttrString(mod, "j5", PyUnicode_FromString(gur::J5));
PyObject_SetAttrString(mod, "k1", PyUnicode_FromString(gur::K1));
PyObject_SetAttrString(mod, "k2", PyUnicode_FromString(gur::K2));
PyObject_SetAttrString(mod, "k3", PyUnicode_FromString(gur::K3));
PyObject_SetAttrString(mod, "k4", PyUnicode_FromString(gur::K4));
PyObject_SetAttrString(mod, "k5", PyUnicode_FromString(gur::K5));
PyObject_SetAttrString(mod, "l1", PyUnicode_FromString(gur::L1));
PyObject_SetAttrString(mod, "l2", PyUnicode_FromString(gur::L2));
PyObject_SetAttrString(mod, "l3", PyUnicode_FromString(gur::L3));
PyObject_SetAttrString(mod, "l4", PyUnicode_FromString(gur::L4));
PyObject_SetAttrString(mod, "l5", PyUnicode_FromString(gur::L5));
PyObject_SetAttrString(mod, "m1", PyUnicode_FromString(gur::M1));
PyObject_SetAttrString(mod, "m2", PyUnicode_FromString(gur::M2));
PyObject_SetAttrString(mod, "m3", PyUnicode_FromString(gur::M3));
PyObject_SetAttrString(mod, "m4", PyUnicode_FromString(gur::M4));
PyObject_SetAttrString(mod, "m5", PyUnicode_FromString(gur::M5));
PyObject_SetAttrString(mod, "n1", PyUnicode_FromString(gur::N1));
PyObject_SetAttrString(mod, "n2", PyUnicode_FromString(gur::N2));
PyObject_SetAttrString(mod, "n3", PyUnicode_FromString(gur::N3));
PyObject_SetAttrString(mod, "n4", PyUnicode_FromString(gur::N4));
PyObject_SetAttrString(mod, "n5", PyUnicode_FromString(gur::N5));
PyObject_SetAttrString(mod, "o1", PyUnicode_FromString(gur::O1));
PyObject_SetAttrString(mod, "o2", PyUnicode_FromString(gur::O2));
PyObject_SetAttrString(mod, "o3", PyUnicode_FromString(gur::O3));
PyObject_SetAttrString(mod, "o4", PyUnicode_FromString(gur::O4));
PyObject_SetAttrString(mod, "o5", PyUnicode_FromString(gur::O5));
PyObject_SetAttrString(mod, "p1", PyUnicode_FromString(gur::P1));
PyObject_SetAttrString(mod, "p2", PyUnicode_FromString(gur::P2));
PyObject_SetAttrString(mod, "p3", PyUnicode_FromString(gur::P3));
PyObject_SetAttrString(mod, "p4", PyUnicode_FromString(gur::P4));
PyObject_SetAttrString(mod, "p5", PyUnicode_FromString(gur::P5));
PyObject_SetAttrString(mod, "q1", PyUnicode_FromString(gur::Q1));
PyObject_SetAttrString(mod, "q2", PyUnicode_FromString(gur::Q2));
return mod;
}
|
/******************************************************************************
* Copyright (C) 2015 Sahil Kang <[email protected]>
*
* This file is part of gurpy.
*
* gurpy is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* gurpy 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with gurpy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <Python.h>
#include <gur.hpp>
#include <gurmukhi.hpp>
static PyObject* gp_letters(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::letters(str));
}
static PyObject* gp_accents(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::accents(str));
}
static PyObject* gp_puncs(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::puncs(str));
}
static PyObject* gp_digits(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::digits(str));
}
static PyObject* gp_symbols(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::symbols(str));
}
static PyObject* gp_comp(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::comp(str));
}
static PyObject* gp_clobber(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::clobber(str));
}
static PyObject* gp_unclobber(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::unclobber(str));
}
static PyMethodDef gp_methods[] =
{
{"letters", gp_letters, METH_VARARGS, "Get the letters in a word."},
{"accents", gp_accents, METH_VARARGS, "Get the accents in a word."},
{"puncs", gp_puncs, METH_VARARGS, "Get the punctuations in a word."},
{"digits", gp_digits, METH_VARARGS, "Get the digits in a word."},
{"symbols", gp_symbols, METH_VARARGS, "Get the symbols in a word."},
{"comp", gp_comp, METH_VARARGS, "Get a word's composition."},
{"clobber", gp_clobber, METH_VARARGS, "Combine diacritics."},
{"unclobber", gp_unclobber, METH_VARARGS, "Separate diacritics."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef gp_module =
{
PyModuleDef_HEAD_INIT,
"gurpy", //name of the module
"Python extension for libgur", //module doc
-1,
gp_methods
};
PyMODINIT_FUNC PyInit_gurpy(void)
{
PyObject *mod = PyModule_Create(&gp_module);
PyObject_SetAttrString(mod, "a1", PyUnicode_FromString(gur::A1));
PyObject_SetAttrString(mod, "a2", PyUnicode_FromString(gur::A2));
PyObject_SetAttrString(mod, "a3", PyUnicode_FromString(gur::A3));
PyObject_SetAttrString(mod, "a4", PyUnicode_FromString(gur::A4));
PyObject_SetAttrString(mod, "a5", PyUnicode_FromString(gur::A5));
PyObject_SetAttrString(mod, "b1", PyUnicode_FromString(gur::B1));
PyObject_SetAttrString(mod, "b2", PyUnicode_FromString(gur::B2));
PyObject_SetAttrString(mod, "b3", PyUnicode_FromString(gur::B3));
PyObject_SetAttrString(mod, "b4", PyUnicode_FromString(gur::B4));
PyObject_SetAttrString(mod, "b5", PyUnicode_FromString(gur::B5));
PyObject_SetAttrString(mod, "c1", PyUnicode_FromString(gur::C1));
PyObject_SetAttrString(mod, "c2", PyUnicode_FromString(gur::C2));
PyObject_SetAttrString(mod, "c3", PyUnicode_FromString(gur::C3));
PyObject_SetAttrString(mod, "c4", PyUnicode_FromString(gur::C4));
PyObject_SetAttrString(mod, "c5", PyUnicode_FromString(gur::C5));
PyObject_SetAttrString(mod, "d1", PyUnicode_FromString(gur::D1));
PyObject_SetAttrString(mod, "d2", PyUnicode_FromString(gur::D2));
PyObject_SetAttrString(mod, "d3", PyUnicode_FromString(gur::D3));
PyObject_SetAttrString(mod, "d4", PyUnicode_FromString(gur::D4));
PyObject_SetAttrString(mod, "d5", PyUnicode_FromString(gur::D5));
PyObject_SetAttrString(mod, "e1", PyUnicode_FromString(gur::E1));
PyObject_SetAttrString(mod, "e2", PyUnicode_FromString(gur::E2));
PyObject_SetAttrString(mod, "e3", PyUnicode_FromString(gur::E3));
PyObject_SetAttrString(mod, "e4", PyUnicode_FromString(gur::E4));
PyObject_SetAttrString(mod, "e5", PyUnicode_FromString(gur::E5));
PyObject_SetAttrString(mod, "f1", PyUnicode_FromString(gur::F1));
PyObject_SetAttrString(mod, "f2", PyUnicode_FromString(gur::F2));
PyObject_SetAttrString(mod, "f3", PyUnicode_FromString(gur::F3));
PyObject_SetAttrString(mod, "f4", PyUnicode_FromString(gur::F4));
PyObject_SetAttrString(mod, "f5", PyUnicode_FromString(gur::F5));
PyObject_SetAttrString(mod, "g1", PyUnicode_FromString(gur::G1));
PyObject_SetAttrString(mod, "g2", PyUnicode_FromString(gur::G2));
PyObject_SetAttrString(mod, "g3", PyUnicode_FromString(gur::G3));
PyObject_SetAttrString(mod, "g4", PyUnicode_FromString(gur::G4));
PyObject_SetAttrString(mod, "g5", PyUnicode_FromString(gur::G5));
PyObject_SetAttrString(mod, "h1", PyUnicode_FromString(gur::H1));
PyObject_SetAttrString(mod, "h2", PyUnicode_FromString(gur::H2));
PyObject_SetAttrString(mod, "h3", PyUnicode_FromString(gur::H3));
PyObject_SetAttrString(mod, "h4", PyUnicode_FromString(gur::H4));
PyObject_SetAttrString(mod, "h5", PyUnicode_FromString(gur::H5));
PyObject_SetAttrString(mod, "i1", PyUnicode_FromString(gur::I1));
PyObject_SetAttrString(mod, "i2", PyUnicode_FromString(gur::I2));
PyObject_SetAttrString(mod, "i3", PyUnicode_FromString(gur::I3));
PyObject_SetAttrString(mod, "i4", PyUnicode_FromString(gur::I4));
PyObject_SetAttrString(mod, "i5", PyUnicode_FromString(gur::I5));
PyObject_SetAttrString(mod, "j1", PyUnicode_FromString(gur::J1));
PyObject_SetAttrString(mod, "j2", PyUnicode_FromString(gur::J2));
PyObject_SetAttrString(mod, "j3", PyUnicode_FromString(gur::J3));
PyObject_SetAttrString(mod, "j4", PyUnicode_FromString(gur::J4));
PyObject_SetAttrString(mod, "j5", PyUnicode_FromString(gur::J5));
PyObject_SetAttrString(mod, "k1", PyUnicode_FromString(gur::K1));
PyObject_SetAttrString(mod, "k2", PyUnicode_FromString(gur::K2));
PyObject_SetAttrString(mod, "k3", PyUnicode_FromString(gur::K3));
PyObject_SetAttrString(mod, "k4", PyUnicode_FromString(gur::K4));
PyObject_SetAttrString(mod, "k5", PyUnicode_FromString(gur::K5));
PyObject_SetAttrString(mod, "l1", PyUnicode_FromString(gur::L1));
PyObject_SetAttrString(mod, "l2", PyUnicode_FromString(gur::L2));
PyObject_SetAttrString(mod, "l3", PyUnicode_FromString(gur::L3));
PyObject_SetAttrString(mod, "l4", PyUnicode_FromString(gur::L4));
PyObject_SetAttrString(mod, "l5", PyUnicode_FromString(gur::L5));
PyObject_SetAttrString(mod, "m1", PyUnicode_FromString(gur::M1));
PyObject_SetAttrString(mod, "m2", PyUnicode_FromString(gur::M2));
PyObject_SetAttrString(mod, "m3", PyUnicode_FromString(gur::M3));
PyObject_SetAttrString(mod, "m4", PyUnicode_FromString(gur::M4));
PyObject_SetAttrString(mod, "m5", PyUnicode_FromString(gur::M5));
PyObject_SetAttrString(mod, "n1", PyUnicode_FromString(gur::N1));
PyObject_SetAttrString(mod, "n2", PyUnicode_FromString(gur::N2));
PyObject_SetAttrString(mod, "n3", PyUnicode_FromString(gur::N3));
PyObject_SetAttrString(mod, "n4", PyUnicode_FromString(gur::N4));
PyObject_SetAttrString(mod, "n5", PyUnicode_FromString(gur::N5));
PyObject_SetAttrString(mod, "o1", PyUnicode_FromString(gur::O1));
PyObject_SetAttrString(mod, "o2", PyUnicode_FromString(gur::O2));
PyObject_SetAttrString(mod, "o3", PyUnicode_FromString(gur::O3));
PyObject_SetAttrString(mod, "o4", PyUnicode_FromString(gur::O4));
PyObject_SetAttrString(mod, "o5", PyUnicode_FromString(gur::O5));
PyObject_SetAttrString(mod, "p1", PyUnicode_FromString(gur::P1));
PyObject_SetAttrString(mod, "p2", PyUnicode_FromString(gur::P2));
PyObject_SetAttrString(mod, "p3", PyUnicode_FromString(gur::P3));
PyObject_SetAttrString(mod, "p4", PyUnicode_FromString(gur::P4));
PyObject_SetAttrString(mod, "p5", PyUnicode_FromString(gur::P5));
PyObject_SetAttrString(mod, "q1", PyUnicode_FromString(gur::Q1));
PyObject_SetAttrString(mod, "q2", PyUnicode_FromString(gur::Q2));
return mod;
}
|
Use libgur's functional api
|
Use libgur's functional api
|
C++
|
agpl-3.0
|
SahilKang/gurpy
|
4e0979dbe76875297905163615d76fb81821284b
|
src/order.cpp
|
src/order.cpp
|
#include "order.h"
Order::Order(vector<Task> tasks, vector<Maitenance> maitenance_v){
int machine1_ready_time = 10000, first_job_rt_pos = 0;
if (tasks[0].get_ready_t() == 0) {machine1_ready_time = 0;}
else{
//finding smallest ready_time
for (unsigned int i = 0; i < tasks.size(); i++){
if (tasks[i].get_ready_t() < machine1_ready_time) {
machine1_ready_time = task[i].get_ready_t();
first_job_rt_pos = i;
}
}
//swapping jobs with first
iter_swap(tasks.begin()+0, tasks.begin()+first_job_rt_pos);
}
machine1(1, tasks[0].get_ready_t());
machine2(2, tasks[i].get_ready_t());
for (unsigned int i = 0; i < tasks.size(); i++){
if (machine1.get_stop_t() <= task[i].get_ready_t()){ // when fits perfectly
while (machine1.add(task[i], maitenance_v) == false){
tasks.push_back(tasks[i]);
tasks.remove(tasks.begin()+i);
}
machine2.set_start_t(machine1.get_stop_t());
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(task[i], maitenance_v);
}
else{ // if machine1.get_stop_t() > task[i].get_ready_t()
for (unsigned int j = i + 1, j < task.size(); j++){
if(machine1.get_stop_t() <= task[i].get_ready_t()){
iter_swap(tasks.begin()+i, tasks.begin()+j);
break;
}
}
if (machine1.get_stop_t() <= task[i].get_ready_t()){
while (machine1.add(task[i], maitenance_v) == false){
tasks.push_back(tasks[i]);
tasks.remove(tasks.begin()+i);
}
machine2.set_start_t(machine1.get_stop_t());
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(task[i], maitenance_v);
}
else{ //move rt
while (machine1.add(task[i], maitenance_v) == false){
tasks.push_back(tasks[i]);
tasks.remove(tasks.begin()+i);
}
machine2.set_start_t(machine1.get_stop_t());
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(task[i], maitenance_v);
}
}
}
}
int Order::get_exectime(){
return exec_t;
}
vector<Task> Order::get_tasks(){
return machine1.get_tasks();
}
/*
Order::Order(){
}
Order::Order(vector<Task_t> task_m1_v, vector<Task_t> task_m2_v, vector<Maitenance> maitenance_v){
machine1.set_id(1);
machine1.set_start(0);
machine1.set_stop(0);
machine2.set_id(2);
int n = 0;
unsigned int size = (task_m1_v.size() >= task_m2_v.size())?(task_m1_v.size()):(task_m2_v.size());
for(unsigned int i = 0; i < size; i++){
if (task_m1_v.size() < i){
while(!machine1.add(task_m1_v[i+n], maitenance_v)){
task_m1_v.push_back(task_m1_v[i+n]);
n++;
}
n = 0;
}
if (task_m2_v.size() < i){
if( i == 0 ){
machine2.set_start(machine1.get_sop());
machine2.set_stop(machine1.get_sop());
}
if(machine1.get_sop() <= machine2.get_sop()) machine2.add(task_m2_v[i], maitenance_v);
else machine2.addt(machine1.get_sop(), task_m2_v[i]);
}
}
this->exec_t = machine2.get_sop();
}
void Order::initialization(vector<int> O, vector<Task> task_v, vector<Maitenance> maitenance_v){
machine1.set_id(1);
machine1.set_start(0);
machine1.set_stop(0);
machine2.set_id(2);
int n, tmp;
for (vector<int>::size_type i = 0; i < O.size(); i++){
//Machine 1
n = 1;
while(!machine1.add(O[i], task_v, maitenance_v)){
tmp = O[i];
O[i] = O[i + n];
O[i + n] = tmp;
n++;
}
// Machine 2
if( i == 0 ){
machine2.set_start(machine1.get_sop());
machine2.set_stop(machine1.get_sop());
}
if(machine1.get_sop() <= machine2.get_sop()){
machine2.add(O[i], task_v, maitenance_v);
}else{
machine2.addt(machine1.get_sop(), O[i], task_v);
}
}
this->exec_t = machine2.get_sop();
}
*/
|
#include "order.h"
Order::Order(vector<Task> tasks, vector<Maitenance> maitenance_v){
int machine1_ready_time = 10000, first_job_rt_pos = 0;
if (tasks[0].get_ready_t() == 0) {machine1_ready_time = 0;}
else{
//finding smallest ready_time
for (unsigned int i = 0; i < tasks.size(); i++){
if (tasks[i].get_ready_t() < machine1_ready_time) {
machine1_ready_time = task[i].get_ready_t();
first_job_rt_pos = i;
}
}
//swapping jobs with first
iter_swap(tasks.begin()+0, tasks.begin()+first_job_rt_pos);
}
machine1(1, tasks[0].get_ready_t());
machine2(2, tasks[i].get_ready_t());
for (unsigned int i = 0; i < tasks.size(); i++){
if (machine1.get_stop_t() <= task[i].get_ready_t()){ // when fits perfectly
while (machine1.add(task[i], maitenance_v) == false){
tasks.push_back(tasks[i]);
tasks.remove(tasks.begin()+i);
}
machine2.set_start_t(machine1.get_stop_t());
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(task[i], maitenance_v);
}
else{ // if machine1.get_stop_t() > task[i].get_ready_t()
for (unsigned int j = i + 1, j < task.size(); j++){
if(machine1.get_stop_t() <= task[i].get_ready_t()){
iter_swap(tasks.begin()+i, tasks.begin()+j);
break;
}
}
if (machine1.get_stop_t() <= task[i].get_ready_t()){
while (machine1.add(task[i], maitenance_v) == false){
tasks.push_back(tasks[i]);
tasks.remove(tasks.begin()+i);
}
machine2.set_start_t(machine1.get_stop_t());
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(task[i], maitenance_v);
}
else{ //move rt
while (machine1.add(task[i], maitenance_v) == false){
tasks.push_back(tasks[i]);
tasks.remove(tasks.begin()+i);
}
machine2.set_start_t(machine1.get_stop_t());
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(task[i], maitenance_v);
}
}
}
}
int Order::get_exectime(){
return exec_t;
}
vector<Task_t> Order::get_tasks(){
return machine1.get_tasks();
}
/*
Order::Order(){
}
Order::Order(vector<Task_t> task_m1_v, vector<Task_t> task_m2_v, vector<Maitenance> maitenance_v){
machine1.set_id(1);
machine1.set_start(0);
machine1.set_stop(0);
machine2.set_id(2);
int n = 0;
unsigned int size = (task_m1_v.size() >= task_m2_v.size())?(task_m1_v.size()):(task_m2_v.size());
for(unsigned int i = 0; i < size; i++){
if (task_m1_v.size() < i){
while(!machine1.add(task_m1_v[i+n], maitenance_v)){
task_m1_v.push_back(task_m1_v[i+n]);
n++;
}
n = 0;
}
if (task_m2_v.size() < i){
if( i == 0 ){
machine2.set_start(machine1.get_sop());
machine2.set_stop(machine1.get_sop());
}
if(machine1.get_sop() <= machine2.get_sop()) machine2.add(task_m2_v[i], maitenance_v);
else machine2.addt(machine1.get_sop(), task_m2_v[i]);
}
}
this->exec_t = machine2.get_sop();
}
void Order::initialization(vector<int> O, vector<Task> task_v, vector<Maitenance> maitenance_v){
machine1.set_id(1);
machine1.set_start(0);
machine1.set_stop(0);
machine2.set_id(2);
int n, tmp;
for (vector<int>::size_type i = 0; i < O.size(); i++){
//Machine 1
n = 1;
while(!machine1.add(O[i], task_v, maitenance_v)){
tmp = O[i];
O[i] = O[i + n];
O[i + n] = tmp;
n++;
}
// Machine 2
if( i == 0 ){
machine2.set_start(machine1.get_sop());
machine2.set_stop(machine1.get_sop());
}
if(machine1.get_sop() <= machine2.get_sop()){
machine2.add(O[i], task_v, maitenance_v);
}else{
machine2.addt(machine1.get_sop(), O[i], task_v);
}
}
this->exec_t = machine2.get_sop();
}
*/
|
Order constructor added
|
Order constructor added
|
C++
|
mit
|
Druggist/random_project,Druggist/genetic-algorithm,Druggist/random_project,Druggist/genetic-algorithm,Druggist/genetic-algorithm,Druggist/genetic-algorithm,Druggist/random_project
|
d5e41bfc6e6f2d116822f9d030d371f9c3765431
|
src/plugin.cc
|
src/plugin.cc
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2021 katursis
*
* 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 "main.h"
bool Plugin::OnLoad() {
config_ = std::make_shared<Config>("plugins/pawnraknet.cfg");
config_->Read();
InstallPreHooks();
RegisterNative<&Script::PR_Init>("PR_Init");
RegisterNative<&Script::PR_RegHandler>("PR_RegHandler");
RegisterNative<&Script::PR_SendPacket>("PR_SendPacket");
RegisterNative<&Script::PR_SendRPC>("PR_SendRPC");
RegisterNative<&Script::PR_EmulateIncomingPacket>("PR_EmulateIncomingPacket");
RegisterNative<&Script::PR_EmulateIncomingRPC>("PR_EmulateIncomingRPC");
RegisterNative<&Script::BS_New>("BS_New");
RegisterNative<&Script::BS_NewCopy>("BS_NewCopy");
RegisterNative<&Script::BS_Delete>("BS_Delete");
RegisterNative<&Script::BS_Reset>("BS_Reset");
RegisterNative<&Script::BS_ResetReadPointer>("BS_ResetReadPointer");
RegisterNative<&Script::BS_ResetWritePointer>("BS_ResetWritePointer");
RegisterNative<&Script::BS_IgnoreBits>("BS_IgnoreBits");
RegisterNative<&Script::BS_SetWriteOffset>("BS_SetWriteOffset");
RegisterNative<&Script::BS_GetWriteOffset>("BS_GetWriteOffset");
RegisterNative<&Script::BS_SetReadOffset>("BS_SetReadOffset");
RegisterNative<&Script::BS_GetReadOffset>("BS_GetReadOffset");
RegisterNative<&Script::BS_GetNumberOfBitsUsed>("BS_GetNumberOfBitsUsed");
RegisterNative<&Script::BS_GetNumberOfBytesUsed>("BS_GetNumberOfBytesUsed");
RegisterNative<&Script::BS_GetNumberOfUnreadBits>("BS_GetNumberOfUnreadBits");
RegisterNative<&Script::BS_GetNumberOfBitsAllocated>(
"BS_GetNumberOfBitsAllocated");
RegisterNative<&Script::BS_WriteValue, false>("BS_WriteValue");
RegisterNative<&Script::BS_ReadValue, false>("BS_ReadValue");
Log("\n\n"
" | %s %s | omp-beta6 | 2016 - %s"
"\n"
" |--------------------------------------------"
"\n"
" | Author and maintainer: katursis"
"\n\n\n"
" | Compiled: %s at %s"
"\n"
" |--------------------------------------------------------------"
"\n"
" | Repository: https://github.com/katursis/%s/tree/omp"
"\n"
" |--------------------------------------------------------------"
"\n"
" | Wiki: https://github.com/katursis/%s/wiki"
"\n",
Name(), VersionAsString().c_str(), &__DATE__[7], __DATE__, __TIME__,
Name(), Name());
return true;
}
void Plugin::OnUnload() {
config_->Save();
Log("plugin unloaded");
}
void Plugin::OnProcessTick() {}
void Plugin::InstallPreHooks() {
hook_amx_cleanup_ = urmem::hook::make(
reinterpret_cast<urmem::address_t *>(
plugin_data_[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Cleanup],
&Hooks::amx_Cleanup);
}
void Plugin::SetCustomRPC(RPCIndex rpc_id) { custom_rpc_[rpc_id] = true; }
bool Plugin::IsCustomRPC(RPCIndex rpc_id) { return custom_rpc_[rpc_id]; }
const std::shared_ptr<urmem::hook> &Plugin::GetHookAmxCleanup() {
return hook_amx_cleanup_;
}
const std::shared_ptr<Config> &Plugin::GetConfig() { return config_; }
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2021 katursis
*
* 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 "main.h"
bool Plugin::OnLoad() {
config_ = std::make_shared<Config>("components/pawnraknet.cfg");
config_->Read();
InstallPreHooks();
RegisterNative<&Script::PR_Init>("PR_Init");
RegisterNative<&Script::PR_RegHandler>("PR_RegHandler");
RegisterNative<&Script::PR_SendPacket>("PR_SendPacket");
RegisterNative<&Script::PR_SendRPC>("PR_SendRPC");
RegisterNative<&Script::PR_EmulateIncomingPacket>("PR_EmulateIncomingPacket");
RegisterNative<&Script::PR_EmulateIncomingRPC>("PR_EmulateIncomingRPC");
RegisterNative<&Script::BS_New>("BS_New");
RegisterNative<&Script::BS_NewCopy>("BS_NewCopy");
RegisterNative<&Script::BS_Delete>("BS_Delete");
RegisterNative<&Script::BS_Reset>("BS_Reset");
RegisterNative<&Script::BS_ResetReadPointer>("BS_ResetReadPointer");
RegisterNative<&Script::BS_ResetWritePointer>("BS_ResetWritePointer");
RegisterNative<&Script::BS_IgnoreBits>("BS_IgnoreBits");
RegisterNative<&Script::BS_SetWriteOffset>("BS_SetWriteOffset");
RegisterNative<&Script::BS_GetWriteOffset>("BS_GetWriteOffset");
RegisterNative<&Script::BS_SetReadOffset>("BS_SetReadOffset");
RegisterNative<&Script::BS_GetReadOffset>("BS_GetReadOffset");
RegisterNative<&Script::BS_GetNumberOfBitsUsed>("BS_GetNumberOfBitsUsed");
RegisterNative<&Script::BS_GetNumberOfBytesUsed>("BS_GetNumberOfBytesUsed");
RegisterNative<&Script::BS_GetNumberOfUnreadBits>("BS_GetNumberOfUnreadBits");
RegisterNative<&Script::BS_GetNumberOfBitsAllocated>(
"BS_GetNumberOfBitsAllocated");
RegisterNative<&Script::BS_WriteValue, false>("BS_WriteValue");
RegisterNative<&Script::BS_ReadValue, false>("BS_ReadValue");
Log("\n\n"
" | %s %s | omp-beta6 | 2016 - %s"
"\n"
" |--------------------------------------------"
"\n"
" | Author and maintainer: katursis"
"\n\n\n"
" | Compiled: %s at %s"
"\n"
" |--------------------------------------------------------------"
"\n"
" | Repository: https://github.com/katursis/%s/tree/omp"
"\n"
" |--------------------------------------------------------------"
"\n"
" | Wiki: https://github.com/katursis/%s/wiki"
"\n",
Name(), VersionAsString().c_str(), &__DATE__[7], __DATE__, __TIME__,
Name(), Name());
return true;
}
void Plugin::OnUnload() {
config_->Save();
Log("plugin unloaded");
}
void Plugin::OnProcessTick() {}
void Plugin::InstallPreHooks() {
hook_amx_cleanup_ = urmem::hook::make(
reinterpret_cast<urmem::address_t *>(
plugin_data_[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Cleanup],
&Hooks::amx_Cleanup);
}
void Plugin::SetCustomRPC(RPCIndex rpc_id) { custom_rpc_[rpc_id] = true; }
bool Plugin::IsCustomRPC(RPCIndex rpc_id) { return custom_rpc_[rpc_id]; }
const std::shared_ptr<urmem::hook> &Plugin::GetHookAmxCleanup() {
return hook_amx_cleanup_;
}
const std::shared_ptr<Config> &Plugin::GetConfig() { return config_; }
|
load config from components folder
|
load config from components folder
|
C++
|
mit
|
urShadow/RakNetManager,urShadow/RakNetManager
|
135a81b2f95cb2dbd6b839e6e0b9b635d992839d
|
src/scene.cpp
|
src/scene.cpp
|
#include "./scene.h"
#include <QCursor>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./graphics/gl.h"
#include "./input/invoke_manager.h"
#include "./graphics/render_data.h"
#include "./camera_controller.h"
#include "./camera_rotation_controller.h"
#include "./camera_zoom_controller.h"
#include "./camera_move_controller.h"
#include "./nodes.h"
#include "./forces/labeller_frame_data.h"
#include "./label_node.h"
#include "./eigen_qdebug.h"
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,
std::shared_ptr<Forces::Labeller> labeller)
: nodes(nodes), labels(labels), labeller(labeller), frustumOptimizer(nodes)
{
cameraController = std::make_shared<CameraController>(camera);
cameraRotationController = std::make_shared<CameraRotationController>(camera);
cameraZoomController = std::make_shared<CameraZoomController>(camera);
cameraMoveController = std::make_shared<CameraMoveController>(camera);
invokeManager->addHandler("cam", cameraController.get());
invokeManager->addHandler("cameraRotation", cameraRotationController.get());
invokeManager->addHandler("cameraZoom", cameraZoomController.get());
invokeManager->addHandler("cameraMove", cameraMoveController.get());
fbo = std::unique_ptr<Graphics::FrameBufferObject>(
new Graphics::FrameBufferObject());
textureManager = std::make_shared<Graphics::TextureManager>();
bufferManager = std::unique_ptr<Graphics::BufferManager>(
new Graphics::BufferManager(textureManager));
}
Scene::~Scene()
{
qDebug() << "Destructor of Scene";
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
quad = std::make_shared<Graphics::Quad>(":shader/label.vert",
":shader/texture.frag");
fbo->initialize(gl, width, height);
haBuffer =
std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));
haBuffer->initialize(gl);
bufferManager->initialize(gl, 10, 100);
std::vector<float> positions = { 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f };
std::vector<float> normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };
std::vector<float> colors = {
1.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f,
0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f
};
std::vector<float> texCoords = { 1.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f };
std::vector<uint> indices = { 0, 1, 2, 1, 3, 2 };
objectId =
bufferManager->addObject(positions, normals, colors, texCoords, indices);
shader = std::make_shared<Graphics::ShaderProgram>(gl, ":/shader/pass.vert",
":/shader/test.frag");
textureManager->initialize(gl, true, 8);
auto textureId = textureManager->addTexture(
"/home/christof/Documents/master/volyHA5/scenes/tiger/tiger-atlas.jpg");
bufferManager->setObjectTexture(objectId, textureId);
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
this->frameTime = frameTime;
cameraController->setFrameTime(frameTime);
cameraRotationController->setFrameTime(frameTime);
cameraZoomController->setFrameTime(frameTime);
cameraMoveController->setFrameTime(frameTime);
frustumOptimizer.update(camera.getViewMatrix());
camera.updateNearAndFarPlanes(frustumOptimizer.getNear(),
frustumOptimizer.getFar());
haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),
frustumOptimizer.getFar());
auto newPositions = labeller->update(Forces::LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->label.id];
}
}
void Scene::render()
{
if (shouldResize)
{
camera.resize(width, height);
fbo->resize(width, height);
shouldResize = false;
}
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
fbo->bind();
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData;
renderData.projectionMatrix = camera.getProjectionMatrix();
renderData.viewMatrix = camera.getViewMatrix();
renderData.cameraPosition = camera.getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
haBuffer->clearAndPrepare();
nodes->render(gl, haBuffer, renderData);
shader->bind();
Eigen::Matrix4f mvp = renderData.projectionMatrix * renderData.viewMatrix;
shader->setUniform("modelViewProjectionMatrix", mvp);
// shader->setUniform("modelMatrix", renderData.modelMatrix);
haBuffer->begin(shader);
bufferManager->render();
shader->release();
haBuffer->render();
// doPick();
fbo->unbind();
renderScreenQuad();
}
void Scene::renderScreenQuad()
{
RenderData renderData;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix =
Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix();
fbo->bindColorTexture(GL_TEXTURE0);
// fbo->bindDepthTexture(GL_TEXTURE0);
quad->renderToFrameBuffer(gl, renderData);
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
shouldResize = true;
}
void Scene::pick(int id, Eigen::Vector2f position)
{
pickingPosition = position;
performPicking = true;
pickingLabelId = id;
}
void Scene::doPick()
{
if (!performPicking)
return;
float depth = -2.0f;
fbo->bindDepthTexture(GL_TEXTURE0);
glAssert(gl->glReadPixels(pickingPosition.x(),
height - pickingPosition.y() - 1, 1, 1,
GL_DEPTH_COMPONENT, GL_FLOAT, &depth));
Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f,
pickingPosition.y() * -2.0f / height + 1.0f,
depth * 2.0f - 1.0f, 1.0f);
Eigen::Matrix4f viewProjection =
camera.getProjectionMatrix() * camera.getViewMatrix();
Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC;
positionWorld = positionWorld / positionWorld.w();
qWarning() << "picked:" << positionWorld;
performPicking = false;
auto label = labels->getById(pickingLabelId);
label.anchorPosition = toVector3f(positionWorld);
labels->update(label);
}
|
#include "./scene.h"
#include <QCursor>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./graphics/gl.h"
#include "./input/invoke_manager.h"
#include "./graphics/render_data.h"
#include "./camera_controller.h"
#include "./camera_rotation_controller.h"
#include "./camera_zoom_controller.h"
#include "./camera_move_controller.h"
#include "./nodes.h"
#include "./forces/labeller_frame_data.h"
#include "./label_node.h"
#include "./eigen_qdebug.h"
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,
std::shared_ptr<Forces::Labeller> labeller)
: nodes(nodes), labels(labels), labeller(labeller), frustumOptimizer(nodes)
{
cameraController = std::make_shared<CameraController>(camera);
cameraRotationController = std::make_shared<CameraRotationController>(camera);
cameraZoomController = std::make_shared<CameraZoomController>(camera);
cameraMoveController = std::make_shared<CameraMoveController>(camera);
invokeManager->addHandler("cam", cameraController.get());
invokeManager->addHandler("cameraRotation", cameraRotationController.get());
invokeManager->addHandler("cameraZoom", cameraZoomController.get());
invokeManager->addHandler("cameraMove", cameraMoveController.get());
fbo = std::unique_ptr<Graphics::FrameBufferObject>(
new Graphics::FrameBufferObject());
textureManager = std::make_shared<Graphics::TextureManager>();
bufferManager = std::unique_ptr<Graphics::BufferManager>(
new Graphics::BufferManager(textureManager));
}
Scene::~Scene()
{
qDebug() << "Destructor of Scene";
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
quad = std::make_shared<Graphics::Quad>(":shader/label.vert",
":shader/texture.frag");
fbo->initialize(gl, width, height);
haBuffer =
std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));
haBuffer->initialize(gl);
bufferManager->initialize(gl, 128, 1000);
std::vector<float> positions = { 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f };
std::vector<float> normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f };
std::vector<float> colors = {
1.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f,
0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f
};
std::vector<float> texCoords = { 1.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f };
std::vector<uint> indices = { 0, 1, 2, 1, 3, 2 };
objectId =
bufferManager->addObject(positions, normals, colors, texCoords, indices);
shader = std::make_shared<Graphics::ShaderProgram>(gl, ":/shader/pass.vert",
":/shader/test.frag");
textureManager->initialize(gl, true, 8);
auto textureId = textureManager->addTexture(
"/home/christof/Documents/master/volyHA5/scenes/tiger/tiger-atlas.jpg");
bufferManager->setObjectTexture(objectId, textureId);
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
this->frameTime = frameTime;
cameraController->setFrameTime(frameTime);
cameraRotationController->setFrameTime(frameTime);
cameraZoomController->setFrameTime(frameTime);
cameraMoveController->setFrameTime(frameTime);
frustumOptimizer.update(camera.getViewMatrix());
camera.updateNearAndFarPlanes(frustumOptimizer.getNear(),
frustumOptimizer.getFar());
haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),
frustumOptimizer.getFar());
auto newPositions = labeller->update(Forces::LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->label.id];
}
}
void Scene::render()
{
if (shouldResize)
{
camera.resize(width, height);
fbo->resize(width, height);
shouldResize = false;
}
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
fbo->bind();
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData;
renderData.projectionMatrix = camera.getProjectionMatrix();
renderData.viewMatrix = camera.getViewMatrix();
renderData.cameraPosition = camera.getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
haBuffer->clearAndPrepare();
nodes->render(gl, haBuffer, renderData);
shader->bind();
Eigen::Matrix4f mvp = renderData.projectionMatrix * renderData.viewMatrix;
shader->setUniform("modelViewProjectionMatrix", mvp);
// shader->setUniform("modelMatrix", renderData.modelMatrix);
haBuffer->begin(shader);
bufferManager->render();
shader->release();
haBuffer->render();
// doPick();
fbo->unbind();
renderScreenQuad();
}
void Scene::renderScreenQuad()
{
RenderData renderData;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix =
Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix();
fbo->bindColorTexture(GL_TEXTURE0);
// fbo->bindDepthTexture(GL_TEXTURE0);
quad->renderToFrameBuffer(gl, renderData);
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
shouldResize = true;
}
void Scene::pick(int id, Eigen::Vector2f position)
{
pickingPosition = position;
performPicking = true;
pickingLabelId = id;
}
void Scene::doPick()
{
if (!performPicking)
return;
float depth = -2.0f;
fbo->bindDepthTexture(GL_TEXTURE0);
glAssert(gl->glReadPixels(pickingPosition.x(),
height - pickingPosition.y() - 1, 1, 1,
GL_DEPTH_COMPONENT, GL_FLOAT, &depth));
Eigen::Vector4f positionNDC(pickingPosition.x() * 2.0f / width - 1.0f,
pickingPosition.y() * -2.0f / height + 1.0f,
depth * 2.0f - 1.0f, 1.0f);
Eigen::Matrix4f viewProjection =
camera.getProjectionMatrix() * camera.getViewMatrix();
Eigen::Vector4f positionWorld = viewProjection.inverse() * positionNDC;
positionWorld = positionWorld / positionWorld.w();
qWarning() << "picked:" << positionWorld;
performPicking = false;
auto label = labels->getById(pickingLabelId);
label.anchorPosition = toVector3f(positionWorld);
labels->update(label);
}
|
Increase object count to prevent buffer-overflow.
|
Increase object count to prevent buffer-overflow.
|
C++
|
mit
|
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
|
0e43230c2cca27d74cf2f00e80f1f85fd4b6d242
|
src/search.cc
|
src/search.cc
|
#include "defs.h"
#include "search.h"
#include "eval.h"
#include "movegen.h"
#include "transptable.h"
#include <string>
#include <algorithm>
#include <time.h>
#include <iostream>
#include <functional>
Search::Search(const Board& board, bool logUci) {
_logUci = logUci;
_board = board;
_bestScore = 0;
}
void Search::perform(int depth) {
_rootMax(_board, depth);
if (_logUci) {
_logUciInfo(_pv, depth, _bestMove, _bestScore, _nodes);
}
}
void Search::_logUciInfo(const MoveList& pv, int depth, Move bestMove, int bestScore, int nodes) {
std::string pvString;
for(auto move : pv) {
pvString += move.getNotation() + " ";
}
std::string scoreString;
if (bestScore == INF) {
scoreString = "mate " + std::to_string(pv.size());
} else if (_bestScore == -INF) {
scoreString = "mate -" + std::to_string(pv.size());
} else {
scoreString = "cp " + std::to_string(bestScore);
}
std::cout << "info depth " + std::to_string(depth) + " ";
std::cout << "nodes " + std::to_string(nodes) + " ";
std::cout << "score " + scoreString + " ";
std::cout << "pv " + pvString;
std::cout << std::endl;
}
Move Search::getBestMove() {
return _bestMove;
}
int Search::getBestScore() {
return _bestScore;
}
void Search::_rootMax(const Board& board, int depth) {
MoveGen movegen(board);
MoveList legalMoves = movegen.getLegalMoves();
_orderMoves(board, legalMoves);
_nodes = 0;
_pv = MoveList();
MoveList pv;
int alpha = -INF;
int beta = INF;
int currScore;
Move bestMove;
Board movedBoard;
for (auto move : legalMoves) {
movedBoard = board;
movedBoard.doMove(move);
currScore = -_negaMax(movedBoard, depth-1, -beta, -alpha, pv);
if (currScore > alpha) {
bestMove = move;
alpha = currScore;
MoveList newMoves;
newMoves.push_back(move);
for (auto move : pv) {
newMoves.push_back(move);
}
_pv = newMoves;
// Break if we've found a checkmate
if (currScore == INF) {
break;
}
}
}
// If we couldn't find a path other than checkmate, just pick the first legal move
if (bestMove.getFlags() & Move::NULL_MOVE) {
bestMove = legalMoves.at(0);
}
_tt.set(board.getZKey(), alpha, depth, TranspTable::EXACT);
_bestMove = bestMove;
_bestScore = alpha;
}
void Search::_orderMoves(const Board& board, MoveList& moveList) {
// Order moves by tt score
std::sort(moveList.begin(), moveList.end(), std::bind(&Search::_compareMovesTt, this, board, std::placeholders::_1, std::placeholders::_2));
// Ending index of sorted section of moveList
unsigned int i;
// Order captures by MVV/LVA
Board movedBoard;
for (i=0;i<moveList.size();i++) {
movedBoard = board;
movedBoard.doMove(moveList.at(i));
if (!_tt.contains(movedBoard.getZKey())) {
break;
}
}
std::sort(moveList.begin() + i, moveList.end(), std::bind(&Search::_compareMovesMvvLva, this, std::placeholders::_1, std::placeholders::_2));
// Order promotions by promotion value
for(;i<moveList.size();i++) {
if (!(moveList.at(i).getFlags() & Move::CAPTURE)) {
break;
}
}
std::sort(moveList.begin() + i, moveList.end(), std::bind(&Search::_compareMovesPromotionValue, this, std::placeholders::_1, std::placeholders::_2));
}
void Search::_orderMovesQSearch(MoveList& moveList) {
std::sort(moveList.begin(), moveList.end(), std::bind(&Search::_compareMovesMvvLva, this, std::placeholders::_1, std::placeholders::_2));
}
bool Search::_compareMovesTt(Board board, Move a, Move b) {
Board aBoard = board;
Board bBoard = board;
aBoard.doMove(a);
bBoard.doMove(b);
int aScore = _tt.contains(aBoard.getZKey()) ? _tt.getScore(aBoard.getZKey()) : -INF;
int bScore = _tt.contains(bBoard.getZKey()) ? _tt.getScore(bBoard.getZKey()) : -INF;
return aScore > bScore;
}
bool Search::_compareMovesMvvLva(Move a, Move b) {
bool aIsCapture = a.getFlags() & Move::CAPTURE;
bool bIsCapture = b.getFlags() & Move::CAPTURE;
if (aIsCapture && !bIsCapture) {
return true;
} else if (bIsCapture && !aIsCapture) {
return false;
} else { // Both captures
int aCaptureValue = _getPieceValue(a.getCapturedPieceType());
int bCaptureValue = _getPieceValue(b.getCapturedPieceType());
if (aCaptureValue != bCaptureValue) {
return aCaptureValue > bCaptureValue;
} else { // Captured piece type value is the same, order by attacker value
int aPieceValue = _getPieceValue(a.getPieceType());
int bPieceValue = _getPieceValue(b.getPieceType());
return aPieceValue < bPieceValue;
}
}
}
bool Search::_compareMovesPromotionValue(Move a, Move b) {
bool aIsPromotion = a.getFlags() & Move::PROMOTION;
bool bIsPromotion = b.getFlags() & Move::PROMOTION;
if (aIsPromotion && !bIsPromotion) {
return true;
} else if (bIsPromotion && !aIsPromotion) {
return false;
} else { // Both promotions
int aPromotionValue = _getPieceValue(a.getPromotionPieceType());
int bPromotionValue = _getPieceValue(b.getPromotionPieceType());
return aPromotionValue > bPromotionValue;
}
}
int Search::_getPieceValue(PieceType pieceType) {
int score = 0;
switch(pieceType) {
case PAWN: score = 1;
break;
case KNIGHT: score = 3;
break;
case BISHOP: score = 3;
break;
case ROOK: score = 5;
break;
case QUEEN: score = 9;
break;
default: break;
}
return score;
}
int Search::_negaMax(const Board& board, int depth, int alpha, int beta, MoveList &ppv) {
_nodes ++;
int alphaOrig = alpha;
ZKey zKey = board.getZKey();
// Check transposition table cache
if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) {
switch(_tt.getFlag(zKey)) {
case TranspTable::EXACT:
return _tt.getScore(zKey);
case TranspTable::UPPER_BOUND:
beta = std::min(beta, _tt.getScore(zKey));
break;
case TranspTable::LOWER_BOUND:
alpha = std::max(alpha, _tt.getScore(zKey));
break;
}
if (alpha >= beta) {
return _tt.getScore(zKey);
}
}
// Transposition table lookups are inconclusive, generate moves and recurse
MoveGen movegen(board);
MoveList legalMoves = movegen.getLegalMoves();
// Check for checkmate and stalemate
if (legalMoves.size() == 0) {
ppv.clear();
int score = board.colorIsInCheck(board.getActivePlayer()) ? -INF : 0; // -INF = checkmate, 0 = stalemate (draw)
return score;
}
// Eval if depth is 0
if (depth == 0) {
ppv.clear();
int score = _qSearch(board, alpha, beta);
_tt.set(board.getZKey(), score, 0, TranspTable::EXACT);
return score;
}
MoveList pv;
_orderMoves(board, legalMoves);
Board movedBoard;
for (auto move : legalMoves) {
movedBoard = board;
movedBoard.doMove(move);
int score = -_negaMax(movedBoard, depth-1, -beta, -alpha, pv);
if (score >= beta) {
_tt.set(zKey, alpha, depth, TranspTable::LOWER_BOUND);
return beta;
}
// Check if alpha raised (new best move)
if (score > alpha) {
alpha = score;
// Copy PV data (if alpha raised then we're on a new PV node)
MoveList newMoves;
newMoves.push_back(move);
for (auto move : pv) {
newMoves.push_back(move);
}
ppv = newMoves;
}
}
// Store bestScore in transposition table
TranspTable::Flag flag;
if (alpha <= alphaOrig) {
flag = TranspTable::UPPER_BOUND;
} else {
flag = TranspTable::EXACT;
}
_tt.set(zKey, alpha, depth, flag);
return alpha;
}
int Search::_qSearch(const Board& board, int alpha, int beta) {
MoveGen movegen(board);
MoveList legalMoves = movegen.getLegalMoves();
// Check for checkmate / stalemate
if (legalMoves.size() == 0) {
if (board.colorIsInCheck(board.getActivePlayer())) { // Checkmate
return -INF;
} else { // Stalemate
return 0;
}
}
_orderMovesQSearch(legalMoves);
int standPat = Eval(board, board.getActivePlayer()).getScore();
// If node is quiet, just return eval
if (!(legalMoves.at(0).getFlags() & Move::CAPTURE)) {
return standPat;
}
if (standPat >= beta) {
return beta;
}
if (alpha < standPat) {
alpha = standPat;
}
Board movedBoard;
for (auto move : legalMoves) {
if ((move.getFlags() & Move::CAPTURE) == 0) {
break;
}
movedBoard = board;
movedBoard.doMove(move);
int score = -_qSearch(movedBoard, -beta, -alpha);
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
return alpha;
}
|
#include "defs.h"
#include "search.h"
#include "eval.h"
#include "movegen.h"
#include "transptable.h"
#include <string>
#include <algorithm>
#include <time.h>
#include <iostream>
#include <functional>
Search::Search(const Board& board, bool logUci) {
_logUci = logUci;
_board = board;
_bestScore = 0;
}
void Search::perform(int depth) {
_rootMax(_board, depth);
if (_logUci) {
_logUciInfo(_pv, depth, _bestMove, _bestScore, _nodes);
}
}
void Search::_logUciInfo(const MoveList& pv, int depth, Move bestMove, int bestScore, int nodes) {
std::string pvString;
for(auto move : pv) {
pvString += move.getNotation() + " ";
}
std::string scoreString;
if (bestScore == INF) {
scoreString = "mate " + std::to_string(pv.size());
} else if (_bestScore == -INF) {
scoreString = "mate -" + std::to_string(pv.size());
} else {
scoreString = "cp " + std::to_string(bestScore);
}
std::cout << "info depth " + std::to_string(depth) + " ";
std::cout << "nodes " + std::to_string(nodes) + " ";
std::cout << "score " + scoreString + " ";
std::cout << "pv " + pvString;
std::cout << std::endl;
}
Move Search::getBestMove() {
return _bestMove;
}
int Search::getBestScore() {
return _bestScore;
}
void Search::_rootMax(const Board& board, int depth) {
MoveGen movegen(board);
MoveList legalMoves = movegen.getLegalMoves();
_orderMoves(board, legalMoves);
_nodes = 0;
_pv = MoveList();
MoveList pv;
int alpha = -INF;
int beta = INF;
int currScore;
Move bestMove;
Board movedBoard;
for (auto move : legalMoves) {
movedBoard = board;
movedBoard.doMove(move);
currScore = -_negaMax(movedBoard, depth-1, -beta, -alpha, pv);
if (currScore > alpha) {
bestMove = move;
alpha = currScore;
MoveList newMoves;
newMoves.push_back(move);
for (auto move : pv) {
newMoves.push_back(move);
}
_pv = newMoves;
// Break if we've found a checkmate
if (currScore == INF) {
break;
}
}
}
// If we couldn't find a path other than checkmate, just pick the first legal move
if (bestMove.getFlags() & Move::NULL_MOVE) {
bestMove = legalMoves.at(0);
}
_tt.set(board.getZKey(), alpha, depth, TranspTable::EXACT);
_bestMove = bestMove;
_bestScore = alpha;
}
void Search::_orderMoves(const Board& board, MoveList& moveList) {
// Order moves by tt score
std::sort(moveList.begin(), moveList.end(), std::bind(&Search::_compareMovesTt, this, board, std::placeholders::_1, std::placeholders::_2));
// Ending index of sorted section of moveList
unsigned int i;
// Order captures by MVV/LVA
Board movedBoard;
for (i=0;i<moveList.size();i++) {
movedBoard = board;
movedBoard.doMove(moveList.at(i));
if (!_tt.contains(movedBoard.getZKey())) {
break;
}
}
std::sort(moveList.begin() + i, moveList.end(), std::bind(&Search::_compareMovesMvvLva, this, std::placeholders::_1, std::placeholders::_2));
// Order promotions by promotion value
for(;i<moveList.size();i++) {
if (!(moveList.at(i).getFlags() & Move::CAPTURE)) {
break;
}
}
std::sort(moveList.begin() + i, moveList.end(), std::bind(&Search::_compareMovesPromotionValue, this, std::placeholders::_1, std::placeholders::_2));
}
void Search::_orderMovesQSearch(MoveList& moveList) {
std::sort(moveList.begin(), moveList.end(), std::bind(&Search::_compareMovesMvvLva, this, std::placeholders::_1, std::placeholders::_2));
}
bool Search::_compareMovesTt(Board board, Move a, Move b) {
Board aBoard = board;
Board bBoard = board;
aBoard.doMove(a);
bBoard.doMove(b);
ZKey aKey = aBoard.getZKey();
ZKey bKey = bBoard.getZKey();
int aScore = -INF;
int bScore = -INF;
// Get A score
if (_tt.contains(aKey) && _tt.getFlag(aKey) == TranspTable::EXACT) {
aScore = _tt.getScore(aKey);
}
// Get B score
if (_tt.contains(bKey) && _tt.getFlag(bKey) == TranspTable::EXACT) {
bScore = _tt.getScore(bKey);
}
return aScore < bScore;
}
bool Search::_compareMovesMvvLva(Move a, Move b) {
bool aIsCapture = a.getFlags() & Move::CAPTURE;
bool bIsCapture = b.getFlags() & Move::CAPTURE;
if (aIsCapture && !bIsCapture) {
return true;
} else if (bIsCapture && !aIsCapture) {
return false;
} else { // Both captures
int aCaptureValue = _getPieceValue(a.getCapturedPieceType());
int bCaptureValue = _getPieceValue(b.getCapturedPieceType());
if (aCaptureValue != bCaptureValue) {
return aCaptureValue > bCaptureValue;
} else { // Captured piece type value is the same, order by attacker value
int aPieceValue = _getPieceValue(a.getPieceType());
int bPieceValue = _getPieceValue(b.getPieceType());
return aPieceValue < bPieceValue;
}
}
}
bool Search::_compareMovesPromotionValue(Move a, Move b) {
bool aIsPromotion = a.getFlags() & Move::PROMOTION;
bool bIsPromotion = b.getFlags() & Move::PROMOTION;
if (aIsPromotion && !bIsPromotion) {
return true;
} else if (bIsPromotion && !aIsPromotion) {
return false;
} else { // Both promotions
int aPromotionValue = _getPieceValue(a.getPromotionPieceType());
int bPromotionValue = _getPieceValue(b.getPromotionPieceType());
return aPromotionValue > bPromotionValue;
}
}
int Search::_getPieceValue(PieceType pieceType) {
int score = 0;
switch(pieceType) {
case PAWN: score = 1;
break;
case KNIGHT: score = 3;
break;
case BISHOP: score = 3;
break;
case ROOK: score = 5;
break;
case QUEEN: score = 9;
break;
default: break;
}
return score;
}
int Search::_negaMax(const Board& board, int depth, int alpha, int beta, MoveList &ppv) {
_nodes ++;
int alphaOrig = alpha;
ZKey zKey = board.getZKey();
// Check transposition table cache
if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) {
switch(_tt.getFlag(zKey)) {
case TranspTable::EXACT:
return _tt.getScore(zKey);
case TranspTable::UPPER_BOUND:
beta = std::min(beta, _tt.getScore(zKey));
break;
case TranspTable::LOWER_BOUND:
alpha = std::max(alpha, _tt.getScore(zKey));
break;
}
if (alpha >= beta) {
return _tt.getScore(zKey);
}
}
// Transposition table lookups are inconclusive, generate moves and recurse
MoveGen movegen(board);
MoveList legalMoves = movegen.getLegalMoves();
// Check for checkmate and stalemate
if (legalMoves.size() == 0) {
ppv.clear();
int score = board.colorIsInCheck(board.getActivePlayer()) ? -INF : 0; // -INF = checkmate, 0 = stalemate (draw)
return score;
}
// Eval if depth is 0
if (depth == 0) {
ppv.clear();
int score = _qSearch(board, alpha, beta);
_tt.set(board.getZKey(), score, 0, TranspTable::EXACT);
return score;
}
MoveList pv;
_orderMoves(board, legalMoves);
Board movedBoard;
for (auto move : legalMoves) {
movedBoard = board;
movedBoard.doMove(move);
int score = -_negaMax(movedBoard, depth-1, -beta, -alpha, pv);
if (score >= beta) {
_tt.set(zKey, alpha, depth, TranspTable::LOWER_BOUND);
return beta;
}
// Check if alpha raised (new best move)
if (score > alpha) {
alpha = score;
// Copy PV data (if alpha raised then we're on a new PV node)
MoveList newMoves;
newMoves.push_back(move);
for (auto move : pv) {
newMoves.push_back(move);
}
ppv = newMoves;
}
}
// Store bestScore in transposition table
TranspTable::Flag flag;
if (alpha <= alphaOrig) {
flag = TranspTable::UPPER_BOUND;
} else {
flag = TranspTable::EXACT;
}
_tt.set(zKey, alpha, depth, flag);
return alpha;
}
int Search::_qSearch(const Board& board, int alpha, int beta) {
MoveGen movegen(board);
MoveList legalMoves = movegen.getLegalMoves();
// Check for checkmate / stalemate
if (legalMoves.size() == 0) {
if (board.colorIsInCheck(board.getActivePlayer())) { // Checkmate
return -INF;
} else { // Stalemate
return 0;
}
}
_orderMovesQSearch(legalMoves);
int standPat = Eval(board, board.getActivePlayer()).getScore();
// If node is quiet, just return eval
if (!(legalMoves.at(0).getFlags() & Move::CAPTURE)) {
return standPat;
}
if (standPat >= beta) {
return beta;
}
if (alpha < standPat) {
alpha = standPat;
}
Board movedBoard;
for (auto move : legalMoves) {
if ((move.getFlags() & Move::CAPTURE) == 0) {
break;
}
movedBoard = board;
movedBoard.doMove(move);
int score = -_qSearch(movedBoard, -beta, -alpha);
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
return alpha;
}
|
Fix incorrect transposition table move ordering
|
Fix incorrect transposition table move ordering
- Only consider a move for tt move ordering if it is an exact node
(ie. not upper bound or lower bound)
- Fix incorrect trsnaposition table move ordering (reverse)
|
C++
|
mit
|
GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue
|
0f17bd068733c122c5c80f0b9a1dfb6e7f37203c
|
src/table.cpp
|
src/table.cpp
|
#include "includes.h"
#include <algorithm>
// we live in the copernica namespace
namespace AMQP {
/**
* Decode the data from a received frame into a table
*
* @param frame received frame to decode
*/
Table::Table(InBuffer &frame)
{
// table buffer begins with the number of bytes to read
uint32_t bytesToRead = frame.nextUint32();
// keep going until the correct number of bytes is read.
while (bytesToRead > 0)
{
// field name and type
ShortString name(frame);
// subtract number of bytes to read, plus one byte for the decoded type
bytesToRead -= (uint32_t)(name.size() + 1);
// get the field
Field *field = Field::decode(frame);
if (!field) continue;
// add field
_fields[name] = std::shared_ptr<Field>(field);
// subtract size
bytesToRead -= (uint32_t)field->size();
}
}
/**
* Copy constructor
* @param table
*/
Table::Table(const Table &table)
{
// loop through the table records
for (auto iter = table._fields.begin(); iter != table._fields.end(); iter++)
{
// since a map is always ordered, we know that each element will
// be inserted at the end of the new map, so we can simply use
// emplace_hint and hint at insertion at the end of the map
_fields.insert(_fields.end(), std::make_pair(iter->first, iter->second->clone()));
}
}
/**
* Assignment operator
* @param table
* @return Table
*/
Table &Table::operator=(const Table &table)
{
// skip self assignment
if (this == &table) return *this;
// empty current fields
_fields.clear();
// loop through the table records
for (auto iter = table._fields.begin(); iter != table._fields.end(); iter++)
{
// add the field
_fields[iter->first] = std::shared_ptr<Field>(iter->second->clone());
}
// done
return *this;
}
/**
* Move assignment operator
* @param table
* @return Table
*/
Table &Table::operator=(Table &&table)
{
// skip self assignment
if (this == &table) return *this;
// copy fields
_fields = std::move(table._fields);
// done
return *this;
}
/**
* Retrieve all keys in the table
*
* @return Vector with all keys in the table
*/
std::vector<std::string> Table::keys() const
{
// the result vector
std::vector<std::string> result;
result.reserve(_fields.size());
// insert all keys into the result vector
for (auto &iter : _fields) result.push_back(iter.first);
// now return the result
return result;
}
/**
* Get a field
*
* If the field does not exist, an empty string field is returned
*
* @param name field name
* @return the field value
*/
const Field &Table::get(const std::string &name) const
{
// we need an empty string
static ShortString empty;
// locate the element first
auto iter(_fields.find(name));
// check whether the field was found
if (iter == _fields.end()) return empty;
// done
return *iter->second;
}
/**
* Get the size this field will take when
* encoded in the AMQP wire-frame format
*/
size_t Table::size() const
{
// add the size of the uint32_t indicating the size
size_t size = 4;
// iterate over all elements
for (auto iter(_fields.begin()); iter != _fields.end(); ++iter)
{
// get the size of the field name
ShortString name(iter->first);
size += name.size();
// add the size of the field type
size += sizeof(iter->second->typeID());
// add size of element to the total
size += iter->second->size();
}
// return the result
return size;
}
/**
* Write encoded payload to the given buffer.
*/
void Table::fill(OutBuffer& buffer) const
{
// add size
buffer.add(static_cast<uint32_t>(size()-4));
// loop through the fields
for (auto iter(_fields.begin()); iter != _fields.end(); ++iter)
{
// encode the field name
ShortString name(iter->first);
name.fill(buffer);
// encode the element type
buffer.add((uint8_t) iter->second->typeID());
// encode element
iter->second->fill(buffer);
}
}
// end namespace
}
|
#include "includes.h"
#include <algorithm>
// we live in the copernica namespace
namespace AMQP {
/**
* Decode the data from a received frame into a table
*
* @param frame received frame to decode
*/
Table::Table(InBuffer &frame)
{
// table buffer begins with the number of bytes to read
uint32_t bytesToRead = frame.nextUint32();
// keep going until the correct number of bytes is read.
while (bytesToRead > 0)
{
// field name and type
ShortString name(frame);
// subtract number of bytes to read, plus one byte for the decoded type
bytesToRead -= (uint32_t)(name.size() + 1);
// get the field
Field *field = Field::decode(frame);
if (!field) continue;
// add field
_fields[name] = std::shared_ptr<Field>(field);
// subtract size
bytesToRead -= (uint32_t)field->size();
}
}
/**
* Copy constructor
* @param table
*/
Table::Table(const Table &table)
{
// loop through the table records
for (auto iter = table._fields.begin(); iter != table._fields.end(); iter++)
{
// since a map is always ordered, we know that each element will
// be inserted at the end of the new map, so we can simply use
// emplace_hint and hint at insertion at the end of the map
_fields.insert(_fields.end(), std::make_pair(iter->first, iter->second->clone()));
}
}
/**
* Assignment operator
* @param table
* @return Table
*/
Table &Table::operator=(const Table &table)
{
// skip self assignment
if (this == &table) return *this;
// empty current fields
_fields.clear();
// loop through the table records
for (auto iter = table._fields.begin(); iter != table._fields.end(); iter++)
{
// since a map is always ordered, we know that each element will
// be inserted at the end of the new map, so we can simply use
// emplace_hint and hint at insertion at the end of the map
_fields.insert(_fields.end(), std::make_pair(iter->first, iter->second->clone()));
}
// done
return *this;
}
/**
* Move assignment operator
* @param table
* @return Table
*/
Table &Table::operator=(Table &&table)
{
// skip self assignment
if (this == &table) return *this;
// copy fields
_fields = std::move(table._fields);
// done
return *this;
}
/**
* Retrieve all keys in the table
*
* @return Vector with all keys in the table
*/
std::vector<std::string> Table::keys() const
{
// the result vector
std::vector<std::string> result;
result.reserve(_fields.size());
// insert all keys into the result vector
for (auto &iter : _fields) result.push_back(iter.first);
// now return the result
return result;
}
/**
* Get a field
*
* If the field does not exist, an empty string field is returned
*
* @param name field name
* @return the field value
*/
const Field &Table::get(const std::string &name) const
{
// we need an empty string
static ShortString empty;
// locate the element first
auto iter(_fields.find(name));
// check whether the field was found
if (iter == _fields.end()) return empty;
// done
return *iter->second;
}
/**
* Get the size this field will take when
* encoded in the AMQP wire-frame format
*/
size_t Table::size() const
{
// add the size of the uint32_t indicating the size
size_t size = 4;
// iterate over all elements
for (auto iter(_fields.begin()); iter != _fields.end(); ++iter)
{
// get the size of the field name
ShortString name(iter->first);
size += name.size();
// add the size of the field type
size += sizeof(iter->second->typeID());
// add size of element to the total
size += iter->second->size();
}
// return the result
return size;
}
/**
* Write encoded payload to the given buffer.
*/
void Table::fill(OutBuffer& buffer) const
{
// add size
buffer.add(static_cast<uint32_t>(size()-4));
// loop through the fields
for (auto iter(_fields.begin()); iter != _fields.end(); ++iter)
{
// encode the field name
ShortString name(iter->first);
name.fill(buffer);
// encode the element type
buffer.add((uint8_t) iter->second->typeID());
// encode element
iter->second->fill(buffer);
}
}
// end namespace
}
|
Improve Table copy assignment operator
|
Improve Table copy assignment operator
|
C++
|
apache-2.0
|
CopernicaMarketingSoftware/AMQP-CPP,CopernicaMarketingSoftware/AMQP-CPP
|
f5bf46e6a3da6c780931db7aefad8addd40f4ff0
|
paddle/phi/ops/compat/tile_sig.cc
|
paddle/phi/ops/compat/tile_sig.cc
|
/* Copyright (c) 2022 PaddlePaddle 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. */
#include "paddle/phi/core/compat/op_utils.h"
namespace phi {
KernelSignature TileOpArgumentMapping(const ArgumentMappingContext& ctx) {
if (ctx.HasInput("RepeatTimes")) {
return KernelSignature("tile", {"X"}, {"RepeatTimes"}, {"Out"});
} else if (ctx.InputSize("repeat_times_tensor") > 0) {
return KernelSignature("tile", {"X"}, {"repeat_times_tensor"}, {"Out"});
} else {
return KernelSignature("tile", {"X"}, {"repeat_times"}, {"Out"});
}
}
KernelSignature TileGradOpArgumentMapping(const ArgumentMappingContext& ctx) {
if (ctx.HasInput("RepeatTimes")) {
return KernelSignature("tile_grad",
{"X", GradVarName("Out")},
{"RepeatTimes"},
{GradVarName("X")});
} else if (ctx.InputSize("repeat_times_tensor") > 0) {
return KernelSignature("tile_grad",
{"X", GradVarName("Out")},
{"repeat_times_tensor"},
{GradVarName("X")});
} else {
return KernelSignature("tile_grad",
{"X", GradVarName("Out")},
{"repeat_times"},
{GradVarName("X")});
}
}
} // namespace phi
PD_REGISTER_ARG_MAPPING_FN(tile, phi::TileOpArgumentMapping);
PD_REGISTER_ARG_MAPPING_FN(tile_grad, phi::TileGradOpArgumentMapping);
|
/* Copyright (c) 2022 PaddlePaddle 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. */
#include "paddle/phi/core/compat/op_utils.h"
namespace phi {
KernelSignature TileOpArgumentMapping(const ArgumentMappingContext& ctx) {
if (ctx.HasInput("RepeatTimes")) {
return KernelSignature("tile", {"X"}, {"RepeatTimes"}, {"Out"});
} else if (ctx.InputSize("repeat_times_tensor") > 0) {
const auto& repeat_times =
paddle::any_cast<std::vector<int>>(ctx.Attr("repeat_times"));
if (!ctx.IsRuntime() && !repeat_times.empty()) {
return KernelSignature("tile", {"X"}, {"repeat_times"}, {"Out"});
}
return KernelSignature("tile", {"X"}, {"repeat_times_tensor"}, {"Out"});
} else {
return KernelSignature("tile", {"X"}, {"repeat_times"}, {"Out"});
}
}
KernelSignature TileGradOpArgumentMapping(const ArgumentMappingContext& ctx) {
if (ctx.HasInput("RepeatTimes")) {
return KernelSignature("tile_grad",
{"X", GradVarName("Out")},
{"RepeatTimes"},
{GradVarName("X")});
} else if (ctx.InputSize("repeat_times_tensor") > 0) {
return KernelSignature("tile_grad",
{"X", GradVarName("Out")},
{"repeat_times_tensor"},
{GradVarName("X")});
} else {
return KernelSignature("tile_grad",
{"X", GradVarName("Out")},
{"repeat_times"},
{GradVarName("X")});
}
}
} // namespace phi
PD_REGISTER_ARG_MAPPING_FN(tile, phi::TileOpArgumentMapping);
PD_REGISTER_ARG_MAPPING_FN(tile_grad, phi::TileGradOpArgumentMapping);
|
Fix tile_op inferShape (#40589)
|
Fix tile_op inferShape (#40589)
* Fix tile_op inferShape
* fix style
|
C++
|
apache-2.0
|
luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle
|
f03ed2b24bb5237dd0b55163d6f14b681ec659d0
|
flatland_server/test/service_manager_test.cpp
|
flatland_server/test/service_manager_test.cpp
|
/*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name service_manager_test.cpp
* @brief Testing service manager functionalities
* @author Chunshang Li
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* 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 Avidbots Corp. 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 <flatland_msgs/DeleteModel.h>
#include <flatland_msgs/SpawnModel.h>
#include <flatland_server/simulation_manager.h>
#include <flatland_server/timekeeper.h>
#include <flatland_server/world.h>
#include <gtest/gtest.h>
#include <regex>
#include <thread>
namespace fs = boost::filesystem;
using namespace flatland_server;
class ServiceManagerTest : public ::testing::Test {
protected:
SimulationManager* sim_man;
boost::filesystem::path this_file_dir;
boost::filesystem::path world_yaml;
boost::filesystem::path robot_yaml;
Timekeeper timekeeper;
ros::NodeHandle nh;
ros::ServiceClient client;
std::thread simulation_thread;
void SetUp() override {
sim_man = nullptr;
this_file_dir = boost::filesystem::path(__FILE__).parent_path();
timekeeper.SetMaxStepSize(1.0);
}
void TearDown() override {
StopSimulationThread();
if (sim_man) delete sim_man;
}
void StartSimulationThread() {
sim_man =
new SimulationManager(world_yaml.string(), 1000, 1 / 1000.0, false, 0);
simulation_thread = std::thread(&ServiceManagerTest::SimulationThread,
dynamic_cast<ServiceManagerTest*>(this));
}
void StopSimulationThread() {
sim_man->Shutdown();
simulation_thread.join();
}
void SimulationThread() { sim_man->Main(); }
};
/**
* Testing service for loading a model which should succeed
*/
TEST_F(ServiceManagerTest, spawn_valid_model) {
world_yaml =
this_file_dir / fs::path("load_world_tests/simple_test_A/world.yaml");
robot_yaml = this_file_dir /
fs::path("load_world_tests/simple_test_A/person.model.yaml");
flatland_msgs::SpawnModel srv;
srv.request.name = "service_manager_test_robot";
srv.request.ns = "robot123";
srv.request.yaml_path = robot_yaml.string();
srv.request.pose.x = 0.0;
srv.request.pose.y = 0.0;
srv.request.pose.theta = 0.23;
client = nh.serviceClient<flatland_msgs::SpawnModel>("spawn_model");
// Threading is required since client.call blocks executing until return
StartSimulationThread();
ros::service::waitForService("spawn_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_TRUE(srv.response.success);
ASSERT_STREQ("", srv.response.message.c_str());
World* w = sim_man->world_;
ASSERT_EQ(5, w->models_.size());
EXPECT_STREQ("service_manager_test_robot", w->models_[4]->name_.c_str());
EXPECT_STREQ("robot123", w->models_[4]->namespace_.c_str());
EXPECT_FLOAT_EQ(101.1,
w->models_[4]->bodies_[0]->physics_body_->GetPosition().x);
EXPECT_FLOAT_EQ(102.1,
w->models_[4]->bodies_[0]->physics_body_->GetPosition().y);
EXPECT_FLOAT_EQ(0.23, w->models_[4]->bodies_[0]->physics_body_->GetAngle());
EXPECT_EQ(1, w->models_[4]->bodies_.size());
}
/**
* Testing service for loading a model which should fail
*/
TEST_F(ServiceManagerTest, spawn_invalid_model) {
world_yaml =
this_file_dir / fs::path("load_world_tests/simple_test_A/world.yaml");
robot_yaml = this_file_dir / fs::path("random_path/turtlebot.model.yaml");
flatland_msgs::SpawnModel srv;
srv.request.name = "service_manager_test_robot";
srv.request.yaml_path = robot_yaml.string();
srv.request.pose.x = 1;
srv.request.pose.y = 2;
srv.request.pose.theta = 3;
client = nh.serviceClient<flatland_msgs::SpawnModel>("spawn_model");
StartSimulationThread();
ros::service::waitForService("spawn_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_FALSE(srv.response.success);
std::cmatch match;
std::string regex_str =
"Flatland YAML: File does not exist, "
"path=\".*/random_path/turtlebot.model.yaml\".*";
std::regex regex(regex_str);
EXPECT_TRUE(std::regex_match(srv.response.message.c_str(), match, regex))
<< "Error Message '" + srv.response.message + "'" +
" did not match against regex '" + regex_str + "'";
}
/**
* Testing service for deleting a model
*/
TEST_F(ServiceManagerTest, delete_model) {
world_yaml = this_file_dir /
fs::path("plugin_manager_tests/load_dummy_test/world.yaml");
flatland_msgs::DeleteModel srv;
srv.request.name = "turtlebot1";
client = nh.serviceClient<flatland_msgs::DeleteModel>("delete_model");
StartSimulationThread();
ros::service::waitForService("delete_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_TRUE(srv.response.success);
World* w = sim_man->world_;
// after deleting a mode, there should be one less model, and one less plugin
ASSERT_EQ(w->models_.size(), 0);
ASSERT_EQ(w->plugin_manager_.model_plugins_.size(), 0);
int count = std::count_if(w->models_.begin(), w->models_.end(),
[](Model* m) { return m->name_ == "turtlebot1"; });
ASSERT_EQ(count, 0);
}
/**
* Testing service for deleting a model that does not exist, shoudl fail
*/
TEST_F(ServiceManagerTest, delete_nonexistent_model) {
world_yaml = this_file_dir /
fs::path("plugin_manager_tests/load_dummy_test/world.yaml");
flatland_msgs::DeleteModel srv;
srv.request.name = "random_model";
client = nh.serviceClient<flatland_msgs::DeleteModel>("delete_model");
StartSimulationThread();
ros::service::waitForService("delete_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_FALSE(srv.response.success);
EXPECT_STREQ(
"Flatland World: failed to delete model, model with name "
"\"random_model\" does not exist",
srv.response.message.c_str());
}
// Run all the tests that were declared with TEST()
int main(int argc, char** argv) {
ros::init(argc, argv, "service_manager_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name service_manager_test.cpp
* @brief Testing service manager functionalities
* @author Chunshang Li
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* 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 Avidbots Corp. 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 <flatland_msgs/DeleteModel.h>
#include <flatland_msgs/SpawnModel.h>
#include <flatland_server/simulation_manager.h>
#include <flatland_server/timekeeper.h>
#include <flatland_server/world.h>
#include <gtest/gtest.h>
#include <regex>
#include <thread>
namespace fs = boost::filesystem;
using namespace flatland_server;
class ServiceManagerTest : public ::testing::Test {
protected:
SimulationManager* sim_man;
boost::filesystem::path this_file_dir;
boost::filesystem::path world_yaml;
boost::filesystem::path robot_yaml;
Timekeeper timekeeper;
ros::NodeHandle nh;
ros::ServiceClient client;
std::thread simulation_thread;
void SetUp() override {
sim_man = nullptr;
this_file_dir = boost::filesystem::path(__FILE__).parent_path();
timekeeper.SetMaxStepSize(1.0);
}
void TearDown() override {
StopSimulationThread();
if (sim_man) delete sim_man;
}
void StartSimulationThread() {
sim_man =
new SimulationManager(world_yaml.string(), 1000, 1 / 1000.0, false, 0);
simulation_thread = std::thread(&ServiceManagerTest::SimulationThread,
dynamic_cast<ServiceManagerTest*>(this));
}
void StopSimulationThread() {
sim_man->Shutdown();
simulation_thread.join();
}
void SimulationThread() { sim_man->Main(); }
};
/**
* Testing service for loading a model which should succeed
*/
TEST_F(ServiceManagerTest, spawn_valid_model) {
world_yaml =
this_file_dir / fs::path("load_world_tests/simple_test_A/world.yaml");
robot_yaml = this_file_dir /
fs::path("load_world_tests/simple_test_A/person.model.yaml");
flatland_msgs::SpawnModel srv;
srv.request.name = "service_manager_test_robot";
srv.request.ns = "robot123";
srv.request.yaml_path = robot_yaml.string();
srv.request.pose.x = 101.1;
srv.request.pose.y = 102.1;
srv.request.pose.theta = 0.23;
client = nh.serviceClient<flatland_msgs::SpawnModel>("spawn_model");
// Threading is required since client.call blocks executing until return
StartSimulationThread();
ros::service::waitForService("spawn_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_TRUE(srv.response.success);
ASSERT_STREQ("", srv.response.message.c_str());
World* w = sim_man->world_;
ASSERT_EQ(5, w->models_.size());
EXPECT_STREQ("service_manager_test_robot", w->models_[4]->name_.c_str());
EXPECT_STREQ("robot123", w->models_[4]->namespace_.c_str());
EXPECT_FLOAT_EQ(101.1,
w->models_[4]->bodies_[0]->physics_body_->GetPosition().x);
EXPECT_FLOAT_EQ(102.1,
w->models_[4]->bodies_[0]->physics_body_->GetPosition().y);
EXPECT_FLOAT_EQ(0.23, w->models_[4]->bodies_[0]->physics_body_->GetAngle());
EXPECT_EQ(1, w->models_[4]->bodies_.size());
}
/**
* Testing service for loading a model which should fail
*/
TEST_F(ServiceManagerTest, spawn_invalid_model) {
world_yaml =
this_file_dir / fs::path("load_world_tests/simple_test_A/world.yaml");
robot_yaml = this_file_dir / fs::path("random_path/turtlebot.model.yaml");
flatland_msgs::SpawnModel srv;
srv.request.name = "service_manager_test_robot";
srv.request.yaml_path = robot_yaml.string();
srv.request.pose.x = 1;
srv.request.pose.y = 2;
srv.request.pose.theta = 3;
client = nh.serviceClient<flatland_msgs::SpawnModel>("spawn_model");
StartSimulationThread();
ros::service::waitForService("spawn_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_FALSE(srv.response.success);
std::cmatch match;
std::string regex_str =
"Flatland YAML: File does not exist, "
"path=\".*/random_path/turtlebot.model.yaml\".*";
std::regex regex(regex_str);
EXPECT_TRUE(std::regex_match(srv.response.message.c_str(), match, regex))
<< "Error Message '" + srv.response.message + "'" +
" did not match against regex '" + regex_str + "'";
}
/**
* Testing service for deleting a model
*/
TEST_F(ServiceManagerTest, delete_model) {
world_yaml = this_file_dir /
fs::path("plugin_manager_tests/load_dummy_test/world.yaml");
flatland_msgs::DeleteModel srv;
srv.request.name = "turtlebot1";
client = nh.serviceClient<flatland_msgs::DeleteModel>("delete_model");
StartSimulationThread();
ros::service::waitForService("delete_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_TRUE(srv.response.success);
World* w = sim_man->world_;
// after deleting a mode, there should be one less model, and one less plugin
ASSERT_EQ(w->models_.size(), 0);
ASSERT_EQ(w->plugin_manager_.model_plugins_.size(), 0);
int count = std::count_if(w->models_.begin(), w->models_.end(),
[](Model* m) { return m->name_ == "turtlebot1"; });
ASSERT_EQ(count, 0);
}
/**
* Testing service for deleting a model that does not exist, shoudl fail
*/
TEST_F(ServiceManagerTest, delete_nonexistent_model) {
world_yaml = this_file_dir /
fs::path("plugin_manager_tests/load_dummy_test/world.yaml");
flatland_msgs::DeleteModel srv;
srv.request.name = "random_model";
client = nh.serviceClient<flatland_msgs::DeleteModel>("delete_model");
StartSimulationThread();
ros::service::waitForService("delete_model", 1000);
ASSERT_TRUE(client.call(srv));
ASSERT_FALSE(srv.response.success);
EXPECT_STREQ(
"Flatland World: failed to delete model, model with name "
"\"random_model\" does not exist",
srv.response.message.c_str());
}
// Run all the tests that were declared with TEST()
int main(int argc, char** argv) {
ros::init(argc, argv, "service_manager_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Fix broken test
|
Fix broken test
|
C++
|
bsd-3-clause
|
avidbots/flatland,avidbots/flatland,avidbots/flatland
|
fd912239c3ab7ebac2d7f46a99ca8cb76b56833a
|
subsystem.hxx
|
subsystem.hxx
|
#include <boost/scope_exit.hpp>
#include "key.hxx"
#include "key_helper.hxx"
#include "subsystem_base.hxx"
#ifdef WRP_WONDERLAND_SUBSYSTEM_GLFW3
#include "glfw3.hxx"
#elif defined(WRP_WONDERLAND_SUBSYSTEM_GLFW2)
#include "glfw2.hxx"
#endif
|
#include <boost/scope_exit.hpp>
#include "key.hxx"
#include "key_helper.hxx"
#include "subsystem_base.hxx"
#ifdef WRP_WONDERLAND_SUBSYSTEM_GLFW3
#include "glfw3.hxx"
#elif defined(WRP_WONDERLAND_SUBSYSTEM_GLFW2)
#include "glfw2.hxx"
#elif defined(WRP_WONDERLAND_SUBSYSTEM_SDL2)
#include "sdl2.hxx"
#elif defined(WRP_WONDERLAND_SUBSYSTEM_SDL1)
#include "sdl1.hxx"
#elif defined(WRP_WONDERLAND_SUBSYSTEM_GLUT)
#include "glut.hxx"
#endif
|
add entry sdl2 sdl1 glut
|
add entry sdl2 sdl1 glut
|
C++
|
mit
|
usagi/wonderland.subsystem,usagi/wonderland.subsystem
|
45713e805e54d1b148bf59d80ce95016d517ab18
|
distrho/src/DistrhoUIInternal.hpp
|
distrho/src/DistrhoUIInternal.hpp
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DISTRHO_UI_INTERNAL_HPP_INCLUDED
#define DISTRHO_UI_INTERNAL_HPP_INCLUDED
#include "DistrhoUIPrivateData.hpp"
START_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
// Static data, see DistrhoUI.cpp
extern const char* g_nextBundlePath;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
extern uintptr_t g_nextWindowId;
extern double g_nextScaleFactor;
#endif
// -----------------------------------------------------------------------
// UI exporter class
class UIExporter
{
// -------------------------------------------------------------------
// UI Widget and its private data
UI* ui;
UI::PrivateData* uiData;
// -------------------------------------------------------------------
public:
UIExporter(void* const callbacksPtr,
const uintptr_t winId,
const double sampleRate,
const editParamFunc editParamCall,
const setParamFunc setParamCall,
const setStateFunc setStateCall,
const sendNoteFunc sendNoteCall,
const setSizeFunc setSizeCall,
const fileRequestFunc fileRequestCall,
const char* const bundlePath = nullptr,
void* const dspPtr = nullptr,
const double scaleFactor = 0.0,
const uint32_t bgColor = 0,
const uint32_t fgColor = 0xffffffff)
: ui(nullptr),
uiData(new UI::PrivateData())
{
uiData->sampleRate = sampleRate;
uiData->bundlePath = bundlePath != nullptr ? strdup(bundlePath) : nullptr;
uiData->dspPtr = dspPtr;
uiData->bgColor = bgColor;
uiData->fgColor = fgColor;
uiData->scaleFactor = scaleFactor;
uiData->winId = winId;
uiData->callbacksPtr = callbacksPtr;
uiData->editParamCallbackFunc = editParamCall;
uiData->setParamCallbackFunc = setParamCall;
uiData->setStateCallbackFunc = setStateCall;
uiData->sendNoteCallbackFunc = sendNoteCall;
uiData->setSizeCallbackFunc = setSizeCall;
uiData->fileRequestCallbackFunc = fileRequestCall;
g_nextBundlePath = bundlePath;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
g_nextWindowId = winId;
g_nextScaleFactor = scaleFactor;
#endif
UI::PrivateData::s_nextPrivateData = uiData;
UI* const uiPtr = createUI();
g_nextBundlePath = nullptr;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
g_nextWindowId = 0;
g_nextScaleFactor = 0.0;
#else
// enter context called in the PluginWindow constructor, see DistrhoUIPrivateData.hpp
uiData->window->leaveContext();
#endif
UI::PrivateData::s_nextPrivateData = nullptr;
DISTRHO_SAFE_ASSERT_RETURN(uiPtr != nullptr,);
ui = uiPtr;
uiData->initializing = false;
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
// unused
(void)bundlePath;
#endif
}
~UIExporter()
{
quit();
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
uiData->window->enterContextForDeletion();
#endif
delete ui;
delete uiData;
}
// -------------------------------------------------------------------
uint getWidth() const noexcept
{
return uiData->window->getWidth();
}
uint getHeight() const noexcept
{
return uiData->window->getHeight();
}
double getScaleFactor() const noexcept
{
return uiData->window->getScaleFactor();
}
bool getGeometryConstraints(uint& minimumWidth, uint& minimumHeight, bool& keepAspectRatio) const noexcept
{
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
uiData->window->getGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio);
#else
const DGL_NAMESPACE::Size<uint> size(uiData->window->getGeometryConstraints(keepAspectRatio));
minimumWidth = size.getWidth();
minimumHeight = size.getHeight();
#endif
return true;
}
bool isResizable() const noexcept
{
return uiData->window->isResizable();
}
bool isVisible() const noexcept
{
return uiData->window->isVisible();
}
uintptr_t getNativeWindowHandle() const noexcept
{
return uiData->window->getNativeWindowHandle();
}
uint getBackgroundColor() const noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr, 0);
return uiData->bgColor;
}
uint getForegroundColor() const noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr, 0xffffffff);
return uiData->fgColor;
}
// -------------------------------------------------------------------
uint32_t getParameterOffset() const noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr, 0);
return uiData->parameterOffset;
}
// -------------------------------------------------------------------
void parameterChanged(const uint32_t index, const float value)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void programLoaded(const uint32_t index)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->programLoaded(index);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void stateChanged(const char* const key, const char* const value)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
DISTRHO_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
DISTRHO_SAFE_ASSERT_RETURN(value != nullptr,);
ui->stateChanged(key, value);
}
#endif
// -------------------------------------------------------------------
#if DISTRHO_UI_IS_STANDALONE
void exec(DGL_NAMESPACE::IdleCallback* const cb)
{
DISTRHO_SAFE_ASSERT_RETURN(cb != nullptr,);
uiData->window->show();
uiData->window->focus();
uiData->app.addIdleCallback(cb);
uiData->app.exec();
}
void exec_idle()
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr, );
ui->uiIdle();
}
void showAndFocus()
{
uiData->window->show();
uiData->window->focus();
}
#endif
bool plugin_idle()
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr, false);
uiData->app.idle();
ui->uiIdle();
return ! uiData->app.isQuitting();
}
void focus()
{
uiData->window->focus();
}
void quit()
{
uiData->window->close();
uiData->app.quit();
}
// -------------------------------------------------------------------
#if defined(DISTRHO_PLUGIN_TARGET_VST3) && (defined(DISTRHO_OS_MAC) || defined(DISTRHO_OS_WINDOWS))
void idleForVST3()
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
uiData->app.triggerIdleCallbacks();
ui->uiIdle();
}
# if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
void addIdleCallbackForVST3(IdleCallback* const cb, const uint timerFrequencyInMs)
{
uiData->window->addIdleCallback(cb, timerFrequencyInMs);
}
void removeIdleCallbackForVST3(IdleCallback* const cb)
{
uiData->window->removeIdleCallback(cb);
}
# endif
#endif
// -------------------------------------------------------------------
void setWindowOffset(const int x, const int y)
{
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
// TODO
(void)x; (void)y;
#else
uiData->window->setOffset(x, y);
#endif
}
#ifdef DISTRHO_PLUGIN_TARGET_VST3
void setWindowSizeForVST3(const uint width, const uint height)
{
# if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
ui->setSize(width, height);
# else
uiData->window->setSizeForVST3(width, height);
# endif
}
#endif
void setWindowTitle(const char* const uiTitle)
{
uiData->window->setTitle(uiTitle);
}
void setWindowTransientWinId(const uintptr_t transientParentWindowHandle)
{
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
ui->setTransientWindowId(transientParentWindowHandle);
#else
uiData->window->setTransientParent(transientParentWindowHandle);
#endif
}
bool setWindowVisible(const bool yesNo)
{
uiData->window->setVisible(yesNo);
return ! uiData->app.isQuitting();
}
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
bool handlePluginKeyboardVST(const bool press, const bool special, const uint keychar, const uint keycode, const uint16_t mods)
{
DGL_NAMESPACE::Widget::KeyboardEvent ev;
ev.mod = mods;
ev.press = press;
ev.key = keychar;
ev.keycode = keycode;
// keyboard events must always be lowercase
if (ev.key >= 'A' && ev.key <= 'Z')
ev.key += 'a' - 'A'; // A-Z -> a-z
const bool ret = ui->onKeyboard(ev);
if (press && !special && (mods & (kModifierControl|kModifierAlt|kModifierSuper)) == 0x0)
{
DGL_NAMESPACE::Widget::CharacterInputEvent cev;
cev.mod = mods;
cev.character = keychar;
cev.keycode = keycode;
// if shift modifier is on, convert a-z -> A-Z for character input
if (cev.character >= 'a' && cev.character <= 'z' && (mods & DGL_NAMESPACE::kModifierShift) != 0)
cev.character -= 'a' - 'A';
ui->onCharacterInput(cev);
}
return ret;
}
#endif
// -------------------------------------------------------------------
void notifyScaleFactorChanged(const double scaleFactor)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->uiScaleFactorChanged(scaleFactor);
}
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
void notifyFocusChanged(const bool focus)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->uiFocus(focus, DGL_NAMESPACE::kCrossingNormal);
}
#endif
void setSampleRate(const double sampleRate, const bool doCallback = false)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr,);
DISTRHO_SAFE_ASSERT(sampleRate > 0.0);
if (d_isEqual(uiData->sampleRate, sampleRate))
return;
uiData->sampleRate = sampleRate;
if (doCallback)
ui->sampleRateChanged(sampleRate);
}
DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UIExporter)
};
// -----------------------------------------------------------------------
END_NAMESPACE_DISTRHO
#endif // DISTRHO_UI_INTERNAL_HPP_INCLUDED
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DISTRHO_UI_INTERNAL_HPP_INCLUDED
#define DISTRHO_UI_INTERNAL_HPP_INCLUDED
#include "DistrhoUIPrivateData.hpp"
START_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
// Static data, see DistrhoUI.cpp
extern const char* g_nextBundlePath;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
extern uintptr_t g_nextWindowId;
extern double g_nextScaleFactor;
#endif
// -----------------------------------------------------------------------
// UI exporter class
class UIExporter
{
// -------------------------------------------------------------------
// UI Widget and its private data
UI* ui;
UI::PrivateData* uiData;
// -------------------------------------------------------------------
public:
UIExporter(void* const callbacksPtr,
const uintptr_t winId,
const double sampleRate,
const editParamFunc editParamCall,
const setParamFunc setParamCall,
const setStateFunc setStateCall,
const sendNoteFunc sendNoteCall,
const setSizeFunc setSizeCall,
const fileRequestFunc fileRequestCall,
const char* const bundlePath = nullptr,
void* const dspPtr = nullptr,
const double scaleFactor = 0.0,
const uint32_t bgColor = 0,
const uint32_t fgColor = 0xffffffff)
: ui(nullptr),
uiData(new UI::PrivateData())
{
uiData->sampleRate = sampleRate;
uiData->bundlePath = bundlePath != nullptr ? strdup(bundlePath) : nullptr;
uiData->dspPtr = dspPtr;
uiData->bgColor = bgColor;
uiData->fgColor = fgColor;
uiData->scaleFactor = scaleFactor;
uiData->winId = winId;
uiData->callbacksPtr = callbacksPtr;
uiData->editParamCallbackFunc = editParamCall;
uiData->setParamCallbackFunc = setParamCall;
uiData->setStateCallbackFunc = setStateCall;
uiData->sendNoteCallbackFunc = sendNoteCall;
uiData->setSizeCallbackFunc = setSizeCall;
uiData->fileRequestCallbackFunc = fileRequestCall;
g_nextBundlePath = bundlePath;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
g_nextWindowId = winId;
g_nextScaleFactor = scaleFactor;
#endif
UI::PrivateData::s_nextPrivateData = uiData;
UI* const uiPtr = createUI();
g_nextBundlePath = nullptr;
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
g_nextWindowId = 0;
g_nextScaleFactor = 0.0;
#else
// enter context called in the PluginWindow constructor, see DistrhoUIPrivateData.hpp
uiData->window->leaveContext();
#endif
UI::PrivateData::s_nextPrivateData = nullptr;
DISTRHO_SAFE_ASSERT_RETURN(uiPtr != nullptr,);
ui = uiPtr;
uiData->initializing = false;
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
// unused
(void)bundlePath;
#endif
}
~UIExporter()
{
quit();
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
uiData->window->enterContextForDeletion();
#endif
delete ui;
delete uiData;
}
// -------------------------------------------------------------------
uint getWidth() const noexcept
{
return uiData->window->getWidth();
}
uint getHeight() const noexcept
{
return uiData->window->getHeight();
}
double getScaleFactor() const noexcept
{
return uiData->window->getScaleFactor();
}
bool getGeometryConstraints(uint& minimumWidth, uint& minimumHeight, bool& keepAspectRatio) const noexcept
{
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
uiData->window->getGeometryConstraints(minimumWidth, minimumHeight, keepAspectRatio);
#else
const DGL_NAMESPACE::Size<uint> size(uiData->window->getGeometryConstraints(keepAspectRatio));
minimumWidth = size.getWidth();
minimumHeight = size.getHeight();
#endif
return true;
}
bool isResizable() const noexcept
{
return uiData->window->isResizable();
}
bool isVisible() const noexcept
{
return uiData->window->isVisible();
}
uintptr_t getNativeWindowHandle() const noexcept
{
return uiData->window->getNativeWindowHandle();
}
uint getBackgroundColor() const noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr, 0);
return uiData->bgColor;
}
uint getForegroundColor() const noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr, 0xffffffff);
return uiData->fgColor;
}
// -------------------------------------------------------------------
uint32_t getParameterOffset() const noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr, 0);
return uiData->parameterOffset;
}
// -------------------------------------------------------------------
void parameterChanged(const uint32_t index, const float value)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void programLoaded(const uint32_t index)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->programLoaded(index);
}
#endif
#if DISTRHO_PLUGIN_WANT_STATE
void stateChanged(const char* const key, const char* const value)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
DISTRHO_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
DISTRHO_SAFE_ASSERT_RETURN(value != nullptr,);
ui->stateChanged(key, value);
}
#endif
// -------------------------------------------------------------------
#if DISTRHO_UI_IS_STANDALONE
void exec(DGL_NAMESPACE::IdleCallback* const cb)
{
DISTRHO_SAFE_ASSERT_RETURN(cb != nullptr,);
uiData->window->show();
uiData->window->focus();
uiData->app.addIdleCallback(cb);
uiData->app.exec();
}
void exec_idle()
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr, );
ui->uiIdle();
}
void showAndFocus()
{
uiData->window->show();
uiData->window->focus();
}
#endif
bool plugin_idle()
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr, false);
uiData->app.idle();
ui->uiIdle();
return ! uiData->app.isQuitting();
}
void focus()
{
uiData->window->focus();
}
void quit()
{
uiData->window->close();
uiData->app.quit();
}
// -------------------------------------------------------------------
#if defined(DISTRHO_PLUGIN_TARGET_VST3) && (defined(DISTRHO_OS_MAC) || defined(DISTRHO_OS_WINDOWS))
void idleForVST3()
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
uiData->app.triggerIdleCallbacks();
ui->uiIdle();
}
# if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
void addIdleCallbackForVST3(IdleCallback* const cb, const uint timerFrequencyInMs)
{
uiData->window->addIdleCallback(cb, timerFrequencyInMs);
}
void removeIdleCallbackForVST3(IdleCallback* const cb)
{
uiData->window->removeIdleCallback(cb);
}
# endif
#endif
// -------------------------------------------------------------------
void setWindowOffset(const int x, const int y)
{
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
// TODO
(void)x; (void)y;
#else
uiData->window->setOffset(x, y);
#endif
}
#ifdef DISTRHO_PLUGIN_TARGET_VST3
void setWindowSizeForVST3(const uint width, const uint height)
{
# if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
ui->setSize(width, height);
# else
uiData->window->setSizeForVST3(width, height);
# endif
}
#endif
void setWindowTitle(const char* const uiTitle)
{
uiData->window->setTitle(uiTitle);
}
void setWindowTransientWinId(const uintptr_t transientParentWindowHandle)
{
#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI
ui->setTransientWindowId(transientParentWindowHandle);
#else
uiData->window->setTransientParent(transientParentWindowHandle);
#endif
}
bool setWindowVisible(const bool yesNo)
{
uiData->window->setVisible(yesNo);
return ! uiData->app.isQuitting();
}
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
bool handlePluginKeyboardVST(const bool press, const bool special, const uint keychar, const uint keycode, const uint16_t mods)
{
using namespace DGL_NAMESPACE;
Widget::KeyboardEvent ev;
ev.mod = mods;
ev.press = press;
ev.key = keychar;
ev.keycode = keycode;
// keyboard events must always be lowercase
if (ev.key >= 'A' && ev.key <= 'Z')
ev.key += 'a' - 'A'; // A-Z -> a-z
const bool ret = ui->onKeyboard(ev);
if (press && !special && (mods & (kModifierControl|kModifierAlt|kModifierSuper)) == 0)
{
Widget::CharacterInputEvent cev;
cev.mod = mods;
cev.character = keychar;
cev.keycode = keycode;
// if shift modifier is on, convert a-z -> A-Z for character input
if (cev.character >= 'a' && cev.character <= 'z' && (mods & kModifierShift) != 0)
cev.character -= 'a' - 'A';
ui->onCharacterInput(cev);
}
return ret;
}
#endif
// -------------------------------------------------------------------
void notifyScaleFactorChanged(const double scaleFactor)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->uiScaleFactorChanged(scaleFactor);
}
#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI
void notifyFocusChanged(const bool focus)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
ui->uiFocus(focus, DGL_NAMESPACE::kCrossingNormal);
}
#endif
void setSampleRate(const double sampleRate, const bool doCallback = false)
{
DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);
DISTRHO_SAFE_ASSERT_RETURN(uiData != nullptr,);
DISTRHO_SAFE_ASSERT(sampleRate > 0.0);
if (d_isEqual(uiData->sampleRate, sampleRate))
return;
uiData->sampleRate = sampleRate;
if (doCallback)
ui->sampleRateChanged(sampleRate);
}
DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UIExporter)
};
// -----------------------------------------------------------------------
END_NAMESPACE_DISTRHO
#endif // DISTRHO_UI_INTERNAL_HPP_INCLUDED
|
Fix build with without global namespace
|
Fix build with without global namespace
|
C++
|
isc
|
DISTRHO/DPF,DISTRHO/DPF,DISTRHO/DPF,DISTRHO/DPF
|
e30ad8293ca4360bcfc9bf243f39690138d0f735
|
tree/treeplayer/inc/ROOT/TTreeProcessorMT.hxx
|
tree/treeplayer/inc/ROOT/TTreeProcessorMT.hxx
|
// @(#)root/thread:$Id$
// Authors: Enric Tejedor, Enrico Guiraud CERN 05/06/2018
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TTreeProcessorMT
#define ROOT_TTreeProcessorMT
#include "TKey.h"
#include "TTree.h"
#include "TFile.h"
#include "TChain.h"
#include "TTreeReader.h"
#include "TError.h"
#include "TEntryList.h"
#include "TFriendElement.h"
#include "ROOT/RMakeUnique.hxx"
#include "ROOT/TThreadedObject.hxx"
#include <string.h>
#include <functional>
#include <vector>
/** \class TTreeView
\brief A helper class that encapsulates a file and a tree.
A helper class that encapsulates a TFile and a TTree, along with their names.
It is used together with TTProcessor and ROOT::TThreadedObject, so that
in the TTProcessor::Process method each thread can work on its own
<TFile,TTree> pair.
This class can also be used with a collection of file names or a TChain, in case
the tree is stored in more than one file. A view will always contain only the
current (active) tree and file objects.
A copy constructor is defined for TTreeView to work with ROOT::TThreadedObject.
The latter makes a copy of a model object every time a new thread accesses
the threaded object.
*/
namespace ROOT {
namespace Internal {
/// A cluster of entries
struct EntryCluster {
Long64_t start;
Long64_t end;
};
/// Names, aliases, and file names of a TTree's or TChain's friends
using NameAlias = std::pair<std::string, std::string>;
struct FriendInfo {
/// Pairs of names and aliases of friend trees/chains
std::vector<Internal::NameAlias> fFriendNames;
/// Names of the files where each friend is stored. fFriendFileNames[i] is the list of files for friend with
/// name fFriendNames[i]
std::vector<std::vector<std::string>> fFriendFileNames;
};
class TTreeView {
private:
using TreeReaderEntryListPair = std::pair<std::unique_ptr<TTreeReader>, std::unique_ptr<TEntryList>>;
// NOTE: fFriends must come before fChain to be deleted after it, see ROOT-9281 for more details
std::vector<std::unique_ptr<TChain>> fFriends; ///< Friends of the tree/chain
std::unique_ptr<TChain> fChain; ///< Chain on which to operate
////////////////////////////////////////////////////////////////////////////////
/// Construct fChain, also adding friends if needed and injecting knowledge of offsets if available.
void MakeChain(const std::string &treeName, const std::vector<std::string> &fileNames,
const FriendInfo &friendInfo, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries)
{
const std::vector<NameAlias> &friendNames = friendInfo.fFriendNames;
const std::vector<std::vector<std::string>> &friendFileNames = friendInfo.fFriendFileNames;
fChain.reset(new TChain(treeName.c_str()));
const auto nFiles = fileNames.size();
for (auto i = 0u; i < nFiles; ++i) {
fChain->Add(fileNames[i].c_str(), nEntries[i]);
}
fChain->ResetBit(TObject::kMustCleanup);
fFriends.clear();
const auto nFriends = friendNames.size();
for (auto i = 0u; i < nFriends; ++i) {
const auto &friendName = friendNames[i];
const auto &name = friendName.first;
const auto &alias = friendName.second;
// Build a friend chain
auto frChain = std::make_unique<TChain>(name.c_str());
const auto nFileNames = friendFileNames[i].size();
for (auto j = 0u; j < nFileNames; ++j)
frChain->Add(friendFileNames[i][j].c_str(), friendEntries[i][j]);
// Make it friends with the main chain
fChain->AddFriend(frChain.get(), alias.c_str());
fFriends.emplace_back(std::move(frChain));
}
}
TreeReaderEntryListPair MakeReaderWithEntryList(TEntryList &globalList, Long64_t start, Long64_t end)
{
// TEntryList and SetEntriesRange do not work together (the former has precedence).
// We need to construct a TEntryList that contains only those entry numbers in our desired range.
auto localList = std::make_unique<TEntryList>();
Long64_t entry = globalList.GetEntry(0);
do {
if (entry >= end)
break;
else if (entry >= start)
localList->Enter(entry);
} while ((entry = globalList.Next()) >= 0);
auto reader = std::make_unique<TTreeReader>(fChain.get(), localList.get());
return std::make_pair(std::move(reader), std::move(localList));
}
std::unique_ptr<TTreeReader> MakeReader(Long64_t start, Long64_t end)
{
auto reader = std::make_unique<TTreeReader>(fChain.get());
fChain->LoadTree(start - 1);
reader->SetEntriesRange(start, end);
return reader;
}
public:
TTreeView() {}
// no-op, we don't want to copy the local TChains
TTreeView(const TTreeView &) {}
//////////////////////////////////////////////////////////////////////////
/// Get a TTreeReader for the current tree of this view.
TreeReaderEntryListPair GetTreeReader(Long64_t start, Long64_t end, const std::string &treeName,
const std::vector<std::string> &fileNames, const FriendInfo &friendInfo,
TEntryList entryList, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries)
{
const bool usingLocalEntries = friendInfo.fFriendNames.empty() && entryList.GetN() == 0;
if (fChain == nullptr || (usingLocalEntries && fileNames[0] != fChain->GetListOfFiles()->At(0)->GetTitle()))
MakeChain(treeName, fileNames, friendInfo, nEntries, friendEntries);
std::unique_ptr<TTreeReader> reader;
std::unique_ptr<TEntryList> localList;
if (entryList.GetN() > 0) {
std::tie(reader, localList) = MakeReaderWithEntryList(entryList, start, end);
} else {
reader = MakeReader(start, end);
}
// we need to return the entry list too, as it needs to be in scope as long as the reader is
return std::make_pair(std::move(reader), std::move(localList));
}
};
} // End of namespace Internal
class TTreeProcessorMT {
private:
const std::vector<std::string> fFileNames; ///< Names of the files
const std::string fTreeName; ///< Name of the tree
/// User-defined selection of entry numbers to be processed, empty if none was provided
const TEntryList fEntryList; // const to be sure to avoid race conditions among TTreeViews
const Internal::FriendInfo fFriendInfo;
ROOT::TThreadedObject<ROOT::Internal::TTreeView> treeView; ///<! Thread-local TreeViews
Internal::FriendInfo GetFriendInfo(TTree &tree);
std::string FindTreeName();
public:
TTreeProcessorMT(std::string_view filename, std::string_view treename = "");
TTreeProcessorMT(const std::vector<std::string_view> &filenames, std::string_view treename = "");
TTreeProcessorMT(TTree &tree, const TEntryList &entries);
TTreeProcessorMT(TTree &tree);
void Process(std::function<void(TTreeReader &)> func);
};
} // End of namespace ROOT
#endif // defined TTreeProcessorMT
|
// @(#)root/thread:$Id$
// Authors: Enric Tejedor, Enrico Guiraud CERN 05/06/2018
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TTreeProcessorMT
#define ROOT_TTreeProcessorMT
#include "TKey.h"
#include "TTree.h"
#include "TFile.h"
#include "TChain.h"
#include "TTreeReader.h"
#include "TError.h"
#include "TEntryList.h"
#include "TFriendElement.h"
#include "ROOT/RMakeUnique.hxx"
#include "ROOT/TThreadedObject.hxx"
#include <string.h>
#include <functional>
#include <vector>
/** \class TTreeView
\brief A helper class that encapsulates a file and a tree.
A helper class that encapsulates a TFile and a TTree, along with their names.
It is used together with TTProcessor and ROOT::TThreadedObject, so that
in the TTProcessor::Process method each thread can work on its own
<TFile,TTree> pair.
This class can also be used with a collection of file names or a TChain, in case
the tree is stored in more than one file. A view will always contain only the
current (active) tree and file objects.
A copy constructor is defined for TTreeView to work with ROOT::TThreadedObject.
The latter makes a copy of a model object every time a new thread accesses
the threaded object.
*/
namespace ROOT {
namespace Internal {
/// A cluster of entries
struct EntryCluster {
Long64_t start;
Long64_t end;
};
/// Names, aliases, and file names of a TTree's or TChain's friends
using NameAlias = std::pair<std::string, std::string>;
struct FriendInfo {
/// Pairs of names and aliases of friend trees/chains
std::vector<Internal::NameAlias> fFriendNames;
/// Names of the files where each friend is stored. fFriendFileNames[i] is the list of files for friend with
/// name fFriendNames[i]
std::vector<std::vector<std::string>> fFriendFileNames;
};
class TTreeView {
private:
using TreeReaderEntryListPair = std::pair<std::unique_ptr<TTreeReader>, std::unique_ptr<TEntryList>>;
// NOTE: fFriends must come before fChain to be deleted after it, see ROOT-9281 for more details
std::vector<std::unique_ptr<TChain>> fFriends; ///< Friends of the tree/chain
std::unique_ptr<TChain> fChain; ///< Chain on which to operate
////////////////////////////////////////////////////////////////////////////////
/// Construct fChain, also adding friends if needed and injecting knowledge of offsets if available.
void MakeChain(const std::string &treeName, const std::vector<std::string> &fileNames,
const FriendInfo &friendInfo, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries)
{
const std::vector<NameAlias> &friendNames = friendInfo.fFriendNames;
const std::vector<std::vector<std::string>> &friendFileNames = friendInfo.fFriendFileNames;
fChain.reset(new TChain(treeName.c_str()));
const auto nFiles = fileNames.size();
for (auto i = 0u; i < nFiles; ++i) {
fChain->Add(fileNames[i].c_str(), nEntries[i]);
}
fChain->ResetBit(TObject::kMustCleanup);
fFriends.clear();
const auto nFriends = friendNames.size();
for (auto i = 0u; i < nFriends; ++i) {
const auto &friendName = friendNames[i];
const auto &name = friendName.first;
const auto &alias = friendName.second;
// Build a friend chain
auto frChain = std::make_unique<TChain>(name.c_str());
const auto nFileNames = friendFileNames[i].size();
for (auto j = 0u; j < nFileNames; ++j)
frChain->Add(friendFileNames[i][j].c_str(), friendEntries[i][j]);
// Make it friends with the main chain
fChain->AddFriend(frChain.get(), alias.c_str());
fFriends.emplace_back(std::move(frChain));
}
}
TreeReaderEntryListPair MakeReaderWithEntryList(TEntryList &globalList, Long64_t start, Long64_t end)
{
// TEntryList and SetEntriesRange do not work together (the former has precedence).
// We need to construct a TEntryList that contains only those entry numbers in our desired range.
auto localList = std::make_unique<TEntryList>();
Long64_t entry = globalList.GetEntry(0);
do {
if (entry >= end)
break;
else if (entry >= start)
localList->Enter(entry);
} while ((entry = globalList.Next()) >= 0);
auto reader = std::make_unique<TTreeReader>(fChain.get(), localList.get());
return std::make_pair(std::move(reader), std::move(localList));
}
std::unique_ptr<TTreeReader> MakeReader(Long64_t start, Long64_t end)
{
auto reader = std::make_unique<TTreeReader>(fChain.get());
reader->SetEntriesRange(start, end);
return reader;
}
public:
TTreeView() {}
// no-op, we don't want to copy the local TChains
TTreeView(const TTreeView &) {}
//////////////////////////////////////////////////////////////////////////
/// Get a TTreeReader for the current tree of this view.
TreeReaderEntryListPair GetTreeReader(Long64_t start, Long64_t end, const std::string &treeName,
const std::vector<std::string> &fileNames, const FriendInfo &friendInfo,
TEntryList entryList, const std::vector<Long64_t> &nEntries,
const std::vector<std::vector<Long64_t>> &friendEntries)
{
const bool usingLocalEntries = friendInfo.fFriendNames.empty() && entryList.GetN() == 0;
if (fChain == nullptr || (usingLocalEntries && fileNames[0] != fChain->GetListOfFiles()->At(0)->GetTitle()))
MakeChain(treeName, fileNames, friendInfo, nEntries, friendEntries);
std::unique_ptr<TTreeReader> reader;
std::unique_ptr<TEntryList> localList;
if (entryList.GetN() > 0) {
std::tie(reader, localList) = MakeReaderWithEntryList(entryList, start, end);
} else {
reader = MakeReader(start, end);
}
// we need to return the entry list too, as it needs to be in scope as long as the reader is
return std::make_pair(std::move(reader), std::move(localList));
}
};
} // End of namespace Internal
class TTreeProcessorMT {
private:
const std::vector<std::string> fFileNames; ///< Names of the files
const std::string fTreeName; ///< Name of the tree
/// User-defined selection of entry numbers to be processed, empty if none was provided
const TEntryList fEntryList; // const to be sure to avoid race conditions among TTreeViews
const Internal::FriendInfo fFriendInfo;
ROOT::TThreadedObject<ROOT::Internal::TTreeView> treeView; ///<! Thread-local TreeViews
Internal::FriendInfo GetFriendInfo(TTree &tree);
std::string FindTreeName();
public:
TTreeProcessorMT(std::string_view filename, std::string_view treename = "");
TTreeProcessorMT(const std::vector<std::string_view> &filenames, std::string_view treename = "");
TTreeProcessorMT(TTree &tree, const TEntryList &entries);
TTreeProcessorMT(TTree &tree);
void Process(std::function<void(TTreeReader &)> func);
};
} // End of namespace ROOT
#endif // defined TTreeProcessorMT
|
Remove LoadTree, TTreeReader does not warn anymore
|
[TreeProcMT] Remove LoadTree, TTreeReader does not warn anymore
|
C++
|
lgpl-2.1
|
olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,karies/root,karies/root,olifre/root,olifre/root,karies/root,olifre/root,root-mirror/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,karies/root,root-mirror/root,root-mirror/root,karies/root,karies/root,olifre/root,olifre/root,karies/root,root-mirror/root,olifre/root,karies/root,karies/root,olifre/root,olifre/root
|
b0032b930f37ec1987339d601f94b061f664228d
|
harlan.hpp
|
harlan.hpp
|
/**
Runtime library for Harlan.
*/
#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <assert.h>
#include "gc.h"
enum error {
HARLAN_ERR_OUT_OF_BOUNDS,
HARLAN_ERR_MISPLACED_VECTOR
};
#include "cl++.h"
// FIXME: These global variables will cause link errors if we ever
// combine multiple files into a Harlan program.
cl::device_list g_devices(CL_DEVICE_TYPE_GPU |
CL_DEVICE_TYPE_CPU |
CL_DEVICE_TYPE_ACCELERATOR |
0);
cl::context g_ctx(g_devices);
cl::command_queue g_queue(g_ctx.createCommandQueue(g_devices[0]));
template<typename T>
class vector {
size_t len;
T *data;
bool on_gpu;
cl::buffer<T> gpu_buffer;
public:
vector()
: len(0), data(NULL), on_gpu(false),
gpu_buffer(g_ctx.createBuffer<T>(sizeof(T) * 1, CL_MEM_READ_WRITE))
{}
vector(size_t len)
: len(len), data(new T[len]),
on_gpu(false),
gpu_buffer(g_ctx.createBuffer<T>(sizeof(T) * len, CL_MEM_READ_WRITE))
{}
vector(const vector<T> &v)
: len(v.len), on_gpu(false),
gpu_buffer(g_ctx.createBuffer<T>(sizeof(T) * len, CL_MEM_READ_WRITE))
{
assert(!v.on_gpu);
data = new T[len];
std::copy(v.data, v.data + len, data);
}
~vector() {
if(data)
delete [] data;
}
vector<T> &operator=(const vector<T> &rhs) {
assert(!rhs.on_gpu);
len = rhs.len;
if(data)
delete [] data;
data = new T[len];
std::copy(rhs.data, rhs.data + len, data);
on_gpu = false;
gpu_buffer = g_ctx.createBuffer<T>(sizeof(T) * len, CL_MEM_READ_WRITE);
return *this;
}
T &operator[](size_t index) const {
assert(!on_gpu);
assert(index < len);
return data[index];
}
size_t length() const { return len; }
cl::buffer<T> &get_buffer() {
assert(on_gpu);
return gpu_buffer;
}
void to_gpu() {
assert(!on_gpu);
on_gpu = true;
g_queue.write_buffer(get_buffer(), data);
}
void from_gpu() {
assert(on_gpu);
g_queue.read_buffer(get_buffer(), data);
on_gpu = false;
}
};
template<typename T>
void print(T n) {
std::cout << n << std::endl;
}
template<typename T1, typename T2>
void print(T1 n1, T2 n2) {
std::cout << n1 << "\t" << n2 << std::endl;
}
void print(void *) {
// We no longer have enough information to actually print the
// contents of vectors.
std::cout << "[vector]" << std::endl;
}
template<typename T>
void print(const vector<T> &v) {
std::cout << "[" << std::endl;
for(int i = 0; i < v.length(); ++i) {
print(v[i]);
}
std::cout << "]" << std::endl;
}
template<typename T>
void print(const vector<T> &v1, const vector<T> &v2) {
std::cout << "[" << std::endl;
for(int i = 0; i < v1.length(); ++i) {
print(v1[i]);
}
std::cout << "\t";
for(int i = 0; i < v2.length(); ++i) {
print(v2[i]);
}
std::cout << "]" << std::endl;
}
#ifdef __APPLE__
#include <mach/mach_time.h>
#endif
uint64_t nanotime() {
#ifdef __APPLE__
uint64_t time = mach_absolute_time();
mach_timebase_info_data_t info = {0, 0};
if (info.denom == 0) {
mach_timebase_info(&info);
}
uint64_t time_nano = time * (info.numer / info.denom);
return time_nano;
#else
uint64_t ns_per_s = 1000000000LL;
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (ts.tv_sec * ns_per_s + ts.tv_nsec);
#endif
}
struct free_this {
void *p;
free_this(void *p) : p(p) {}
~free_this() { GC_FREE(p); }
};
#define __global
|
/**
Runtime library for Harlan.
*/
#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <assert.h>
#include <string.h>
#include "gc.h"
enum error {
HARLAN_ERR_OUT_OF_BOUNDS,
HARLAN_ERR_MISPLACED_VECTOR
};
#include "cl++.h"
// FIXME: These global variables will cause link errors if we ever
// combine multiple files into a Harlan program.
cl::device_list g_devices(CL_DEVICE_TYPE_GPU |
CL_DEVICE_TYPE_CPU |
CL_DEVICE_TYPE_ACCELERATOR |
0);
cl::context g_ctx(g_devices);
cl::command_queue g_queue(g_ctx.createCommandQueue(g_devices[0]));
template<typename T>
class vector {
size_t len;
T *data;
bool on_gpu;
cl::buffer<T> gpu_buffer;
public:
vector()
: len(0), data(NULL), on_gpu(false),
gpu_buffer(g_ctx.createBuffer<T>(sizeof(T) * 1, CL_MEM_READ_WRITE))
{}
vector(size_t len)
: len(len), data(new T[len]),
on_gpu(false),
gpu_buffer(g_ctx.createBuffer<T>(sizeof(T) * len, CL_MEM_READ_WRITE))
{}
vector(const vector<T> &v)
: len(v.len), on_gpu(false),
gpu_buffer(g_ctx.createBuffer<T>(sizeof(T) * len, CL_MEM_READ_WRITE))
{
assert(!v.on_gpu);
data = new T[len];
std::copy(v.data, v.data + len, data);
}
~vector() {
if(data)
delete [] data;
}
vector<T> &operator=(const vector<T> &rhs) {
assert(!rhs.on_gpu);
len = rhs.len;
if(data)
delete [] data;
data = new T[len];
std::copy(rhs.data, rhs.data + len, data);
on_gpu = false;
gpu_buffer = g_ctx.createBuffer<T>(sizeof(T) * len, CL_MEM_READ_WRITE);
return *this;
}
T &operator[](size_t index) const {
assert(!on_gpu);
assert(index < len);
return data[index];
}
size_t length() const { return len; }
cl::buffer<T> &get_buffer() {
assert(on_gpu);
return gpu_buffer;
}
void to_gpu() {
assert(!on_gpu);
on_gpu = true;
g_queue.write_buffer(get_buffer(), data);
}
void from_gpu() {
assert(on_gpu);
g_queue.read_buffer(get_buffer(), data);
on_gpu = false;
}
};
template<typename T>
void print(T n) {
std::cout << n << std::endl;
}
template<typename T1, typename T2>
void print(T1 n1, T2 n2) {
std::cout << n1 << "\t" << n2 << std::endl;
}
void print(void *) {
// We no longer have enough information to actually print the
// contents of vectors.
std::cout << "[vector]" << std::endl;
}
template<typename T>
void print(const vector<T> &v) {
std::cout << "[" << std::endl;
for(int i = 0; i < v.length(); ++i) {
print(v[i]);
}
std::cout << "]" << std::endl;
}
template<typename T>
void print(const vector<T> &v1, const vector<T> &v2) {
std::cout << "[" << std::endl;
for(int i = 0; i < v1.length(); ++i) {
print(v1[i]);
}
std::cout << "\t";
for(int i = 0; i < v2.length(); ++i) {
print(v2[i]);
}
std::cout << "]" << std::endl;
}
#ifdef __APPLE__
#include <mach/mach_time.h>
#endif
uint64_t nanotime() {
#ifdef __APPLE__
uint64_t time = mach_absolute_time();
mach_timebase_info_data_t info = {0, 0};
if (info.denom == 0) {
mach_timebase_info(&info);
}
uint64_t time_nano = time * (info.numer / info.denom);
return time_nano;
#else
uint64_t ns_per_s = 1000000000LL;
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (ts.tv_sec * ns_per_s + ts.tv_nsec);
#endif
}
struct free_this {
void *p;
free_this(void *p) : p(p) {}
~free_this() { GC_FREE(p); }
};
#define __global
|
Include string.h to make tests pass on Linux.
|
Include string.h to make tests pass on Linux.
|
C++
|
bsd-3-clause
|
eholk/harlan,eholk/harlan,eholk/harlan,ghxandsky/harlan,ghxandsky/harlan,ghxandsky/harlan,eholk/harlan,eholk/harlan
|
e1c58c6aa9b778d8f1d89e74eedae86d6bbe010a
|
opt/remove-unreachable/RemoveUnreachable.cpp
|
opt/remove-unreachable/RemoveUnreachable.cpp
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "ReachableClasses.h"
#include "RemoveUnreachable.h"
#include "DexUtil.h"
#include "Resolver.h"
namespace {
bool is_canary(const DexClass* cls) {
return strstr(cls->get_name()->c_str(), "Canary");
}
bool implements_library_method(const DexMethod* to_check, const DexClass* cls) {
if (!cls) return false;
if (cls->is_external()) {
for (auto const& m : cls->get_vmethods()) {
if (signatures_match(to_check, m)) {
return true;
}
}
}
auto const& superclass = type_class(cls->get_super_class());
if (implements_library_method(to_check, superclass)) {
return true;
}
for (auto const& interface : cls->get_interfaces()->get_type_list()) {
if (implements_library_method(to_check, type_class(interface))) {
return true;
}
}
return false;
}
DexMethod* resolve(const DexMethod* method, const DexClass* cls) {
if (!cls) return nullptr;
for (auto const& m : cls->get_vmethods()) {
if (signatures_match(method, m)) {
return m;
}
}
{
auto const& superclass = type_class(cls->get_super_class());
auto const resolved = resolve(method, superclass);
if (resolved) {
return resolved;
}
}
for (auto const& interface : cls->get_interfaces()->get_type_list()) {
auto const resolved = resolve(method, type_class(interface));
if (resolved) {
return resolved;
}
}
return nullptr;
}
struct deleted_stats {
size_t nclasses{0};
size_t nfields{0};
size_t nmethods{0};
};
deleted_stats trace_stats(const char* label, DexStoresVector& stores) {
deleted_stats stats;
for (auto const& dex : DexStoreClassesIterator(stores)) {
stats.nclasses += dex.size();
for (auto const& cls : dex) {
stats.nfields += cls->get_ifields().size();
stats.nfields += cls->get_sfields().size();
stats.nmethods += cls->get_dmethods().size();
stats.nmethods += cls->get_vmethods().size();
}
}
TRACE(RMU, 1, "%s: %lu classes, %lu fields, %lu methods\n",
label, stats.nclasses, stats.nfields, stats.nmethods);
return stats;
}
struct InheritanceGraph {
InheritanceGraph(DexStoresVector& stores) {
for (auto const& dex : DexStoreClassesIterator(stores)) {
for (auto const& cls : dex) {
add_child(cls->get_type(), cls->get_type());
}
}
}
const std::unordered_set<DexType*>& get_descendants(DexType* type) {
return m_inheritors[type];
}
private:
void add_child(DexType* child, DexType* ancestor) {
auto const& ancestor_cls = type_class(ancestor);
if (!ancestor_cls) return;
auto const& super_type = ancestor_cls->get_super_class();
if (super_type) {
TRACE(RMU, 4, "Child %s of %s\n", SHOW(child), SHOW(super_type));
m_inheritors[super_type].insert(child);
add_child(child, super_type);
}
auto const& interfaces = ancestor_cls->get_interfaces()->get_type_list();
for (auto const& interface : interfaces) {
TRACE(RMU, 4, "Child %s of %s\n", SHOW(child), SHOW(interface));
m_inheritors[interface].insert(child);
add_child(child, interface);
}
}
private:
std::unordered_map<DexType*, std::unordered_set<DexType*>> m_inheritors;
};
struct UnreachableCodeRemover {
UnreachableCodeRemover(DexStoresVector& stores)
: m_stores(stores),
m_inheritance_graph(stores)
{}
void mark_sweep() {
mark();
sweep();
}
private:
void mark(const DexClass* cls) {
if (!cls) return;
m_marked_classes.emplace(cls);
}
void mark(const DexField* field) {
if (!field) return;
m_marked_fields.emplace(field);
}
void mark(const DexMethod* method) {
if (!method) return;
m_marked_methods.emplace(method);
}
bool marked(const DexClass* cls) {
return m_marked_classes.count(cls);
}
bool marked(const DexField* field) {
return m_marked_fields.count(field);
}
bool marked(const DexMethod* method) {
return m_marked_methods.count(method);
}
void push(const DexType* type) {
if (is_array(type)) {
type = get_array_type(type);
}
push(type_class(type));
}
void push(const DexClass* cls) {
if (!cls || marked(cls)) return;
mark(cls);
m_class_stack.emplace_back(cls);
}
void push(const DexField* field) {
if (!field || marked(field)) return;
mark(field);
m_field_stack.emplace_back(field);
}
void push(const DexMethod* method) {
if (!method || marked(method)) return;
mark(method);
m_method_stack.emplace_back(method);
}
template<class T>
void gather_and_push(T t) {
std::vector<DexType*> types;
std::vector<DexField*> fields;
std::vector<DexMethod*> methods;
t->gather_types(types);
t->gather_fields(fields);
t->gather_methods(methods);
for (auto const& t : types) {
push(t);
}
for (auto const& f : fields) {
push(f);
}
for (auto const& m : methods) {
push(m);
}
}
void visit(const DexClass* cls) {
TRACE(RMU, 4, "Visiting class: %s\n", SHOW(cls));
for (auto& m : cls->get_dmethods()) {
if (is_init(m)) push(m);
if (is_clinit(m)) push(m);
}
push(type_class(cls->get_super_class()));
for (auto const& t : cls->get_interfaces()->get_type_list()) {
push(type_class(t));
}
const DexAnnotationSet* annoset = cls->get_anno_set();
if (annoset) {
gather_and_push(annoset);
}
}
void visit(DexField* field) {
TRACE(RMU, 4, "Visiting field: %s\n", SHOW(field));
if (!field->is_concrete()) {
auto const& realfield = resolve_field(
field->get_class(), field->get_name(), field->get_type());
push(realfield);
}
gather_and_push(field);
push(field->get_class());
push(field->get_type());
}
void visit(DexMethod* method) {
TRACE(RMU, 4, "Visiting method: %s\n", SHOW(method));
push(resolve(method, type_class(method->get_class())));
gather_and_push(method);
push(method->get_class());
push(method->get_proto()->get_rtype());
for (auto const& t : method->get_proto()->get_args()->get_type_list()) {
push(t);
}
if (method->is_virtual() || !method->is_concrete()) {
// If we're keeping an interface method, we have to keep its
// implementations. Annoyingly, the implementation might be defined on a
// super class of the class that implements the interface.
auto const& cls = method->get_class();
auto const& children = m_inheritance_graph.get_descendants(cls);
for (auto child : children) {
while (true) {
auto child_cls = type_class(child);
if (!child_cls || child_cls->is_external()) {
break;
}
for (auto const& m : child_cls->get_vmethods()) {
if (signatures_match(method, m)) {
push(m);
}
}
child = child_cls->get_super_class();
}
}
}
}
void mark() {
for (auto const& dex : DexStoreClassesIterator(m_stores)) {
for (auto const& cls : dex) {
if (keep(cls) || is_canary(cls)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(cls));
push(cls);
}
for (auto const& f : cls->get_ifields()) {
if (keep(f) || is_volatile(f)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(f));
push(f);
}
}
for (auto const& f : cls->get_sfields()) {
if (keep(f)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(f));
push(f);
}
}
for (auto const& m : cls->get_dmethods()) {
if (keep(m)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(m));
push(m);
}
}
for (auto const& m : cls->get_vmethods()) {
if (keep(m) || implements_library_method(m, cls)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(m));
push(m);
}
}
}
}
while (true) {
if (!m_class_stack.empty()) {
auto cls = m_class_stack.back();
m_class_stack.pop_back();
visit(cls);
continue;
}
if (!m_field_stack.empty()) {
auto field = m_field_stack.back();
m_field_stack.pop_back();
visit(const_cast<DexField*>(field));
continue;
}
if (!m_method_stack.empty()) {
auto method = m_method_stack.back();
m_method_stack.pop_back();
visit(const_cast<DexMethod*>(method));
continue;
}
return;
}
}
template<class Container, class Marked>
void sweep_if_unmarked(
Container& c,
const std::unordered_set<Marked>& marked
) {
c.erase(
std::remove_if(
c.begin(), c.end(),
[&](const Marked& m) {
if (marked.count(m) == 0) {
TRACE(RMU, 2, "Removing %s\n", SHOW(m));
return true;
}
return false;
}),
c.end());
}
void sweep() {
for (auto& dex : DexStoreClassesIterator(m_stores)) {
sweep_if_unmarked(dex, m_marked_classes);
for (auto const& cls : dex) {
sweep_if_unmarked(cls->get_ifields(), m_marked_fields);
sweep_if_unmarked(cls->get_sfields(), m_marked_fields);
sweep_if_unmarked(cls->get_dmethods(), m_marked_methods);
sweep_if_unmarked(cls->get_vmethods(), m_marked_methods);
}
}
}
private:
DexStoresVector& m_stores;
InheritanceGraph m_inheritance_graph;
std::unordered_set<const DexClass*> m_marked_classes;
std::unordered_set<const DexField*> m_marked_fields;
std::unordered_set<const DexMethod*> m_marked_methods;
std::vector<const DexClass*> m_class_stack;
std::vector<const DexField*> m_field_stack;
std::vector<const DexMethod*> m_method_stack;
};
}
void RemoveUnreachablePass::run_pass(
DexStoresVector& stores,
ConfigFiles& cfg,
PassManager& pm
) {
if (pm.no_proguard_rules()) {
TRACE(RMU, 1, "RemoveUnreachablePass not run because no ProGuard configuration was provided.");
return;
}
UnreachableCodeRemover ucr(stores);
deleted_stats before = trace_stats("before", stores);
ucr.mark_sweep();
deleted_stats after = trace_stats("after", stores);
pm.incr_metric("classes_removed", before.nclasses - after.nclasses);
pm.incr_metric("fields_removed", before.nfields - after.nfields);
pm.incr_metric("methods_removed", before.nmethods - after.nmethods);
}
static RemoveUnreachablePass s_pass;
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "ReachableClasses.h"
#include "RemoveUnreachable.h"
#include "DexUtil.h"
#include "Resolver.h"
namespace {
bool is_canary(const DexClass* cls) {
return strstr(cls->get_name()->c_str(), "Canary");
}
bool implements_library_method(const DexMethod* to_check, const DexClass* cls) {
if (!cls) return false;
if (cls->is_external()) {
for (auto const& m : cls->get_vmethods()) {
if (signatures_match(to_check, m)) {
return true;
}
}
}
auto const& superclass = type_class(cls->get_super_class());
if (implements_library_method(to_check, superclass)) {
return true;
}
for (auto const& interface : cls->get_interfaces()->get_type_list()) {
if (implements_library_method(to_check, type_class(interface))) {
return true;
}
}
return false;
}
DexMethod* resolve(const DexMethod* method, const DexClass* cls) {
if (!cls) return nullptr;
for (auto const& m : cls->get_vmethods()) {
if (signatures_match(method, m)) {
return m;
}
}
{
auto const& superclass = type_class(cls->get_super_class());
auto const resolved = resolve(method, superclass);
if (resolved) {
return resolved;
}
}
for (auto const& interface : cls->get_interfaces()->get_type_list()) {
auto const resolved = resolve(method, type_class(interface));
if (resolved) {
return resolved;
}
}
return nullptr;
}
struct deleted_stats {
size_t nclasses{0};
size_t nfields{0};
size_t nmethods{0};
};
deleted_stats trace_stats(const char* label, DexStoresVector& stores) {
deleted_stats stats;
for (auto const& dex : DexStoreClassesIterator(stores)) {
stats.nclasses += dex.size();
for (auto const& cls : dex) {
stats.nfields += cls->get_ifields().size();
stats.nfields += cls->get_sfields().size();
stats.nmethods += cls->get_dmethods().size();
stats.nmethods += cls->get_vmethods().size();
}
}
TRACE(RMU, 1, "%s: %lu classes, %lu fields, %lu methods\n",
label, stats.nclasses, stats.nfields, stats.nmethods);
return stats;
}
struct InheritanceGraph {
InheritanceGraph(DexStoresVector& stores) {
for (auto const& dex : DexStoreClassesIterator(stores)) {
for (auto const& cls : dex) {
add_child(cls->get_type(), cls->get_type());
}
}
}
const std::unordered_set<DexType*>& get_descendants(DexType* type) {
return m_inheritors[type];
}
private:
void add_child(DexType* child, DexType* ancestor) {
auto const& ancestor_cls = type_class(ancestor);
if (!ancestor_cls) return;
auto const& super_type = ancestor_cls->get_super_class();
if (super_type) {
TRACE(RMU, 4, "Child %s of %s\n", SHOW(child), SHOW(super_type));
m_inheritors[super_type].insert(child);
add_child(child, super_type);
}
auto const& interfaces = ancestor_cls->get_interfaces()->get_type_list();
for (auto const& interface : interfaces) {
TRACE(RMU, 4, "Child %s of %s\n", SHOW(child), SHOW(interface));
m_inheritors[interface].insert(child);
add_child(child, interface);
}
}
private:
std::unordered_map<DexType*, std::unordered_set<DexType*>> m_inheritors;
};
struct UnreachableCodeRemover {
UnreachableCodeRemover(DexStoresVector& stores)
: m_stores(stores),
m_inheritance_graph(stores)
{}
void mark_sweep() {
mark();
sweep();
}
private:
void mark(const DexClass* cls) {
if (!cls) return;
m_marked_classes.emplace(cls);
}
void mark(const DexField* field) {
if (!field) return;
m_marked_fields.emplace(field);
}
void mark(const DexMethod* method) {
if (!method) return;
m_marked_methods.emplace(method);
}
bool marked(const DexClass* cls) {
return m_marked_classes.count(cls);
}
bool marked(const DexField* field) {
return m_marked_fields.count(field);
}
bool marked(const DexMethod* method) {
return m_marked_methods.count(method);
}
void push(const DexType* type) {
if (is_array(type)) {
type = get_array_type(type);
}
push(type_class(type));
}
void push(const DexClass* cls) {
if (!cls || marked(cls)) return;
mark(cls);
m_class_stack.emplace_back(cls);
}
void push(const DexField* field) {
if (!field || marked(field)) return;
mark(field);
m_field_stack.emplace_back(field);
}
void push(const DexMethod* method) {
if (!method || marked(method)) return;
mark(method);
m_method_stack.emplace_back(method);
}
template<class T>
void gather_and_push(T t) {
std::vector<DexType*> types;
std::vector<DexField*> fields;
std::vector<DexMethod*> methods;
t->gather_types(types);
t->gather_fields(fields);
t->gather_methods(methods);
for (auto const& type : types) {
push(type);
}
for (auto const& f : fields) {
push(f);
}
for (auto const& m : methods) {
push(m);
}
}
void visit(const DexClass* cls) {
TRACE(RMU, 4, "Visiting class: %s\n", SHOW(cls));
for (auto& m : cls->get_dmethods()) {
if (is_init(m)) push(m);
if (is_clinit(m)) push(m);
}
push(type_class(cls->get_super_class()));
for (auto const& t : cls->get_interfaces()->get_type_list()) {
push(type_class(t));
}
const DexAnnotationSet* annoset = cls->get_anno_set();
if (annoset) {
gather_and_push(annoset);
}
}
void visit(DexField* field) {
TRACE(RMU, 4, "Visiting field: %s\n", SHOW(field));
if (!field->is_concrete()) {
auto const& realfield = resolve_field(
field->get_class(), field->get_name(), field->get_type());
push(realfield);
}
gather_and_push(field);
push(field->get_class());
push(field->get_type());
}
void visit(DexMethod* method) {
TRACE(RMU, 4, "Visiting method: %s\n", SHOW(method));
push(resolve(method, type_class(method->get_class())));
gather_and_push(method);
push(method->get_class());
push(method->get_proto()->get_rtype());
for (auto const& t : method->get_proto()->get_args()->get_type_list()) {
push(t);
}
if (method->is_virtual() || !method->is_concrete()) {
// If we're keeping an interface method, we have to keep its
// implementations. Annoyingly, the implementation might be defined on a
// super class of the class that implements the interface.
auto const& cls = method->get_class();
auto const& children = m_inheritance_graph.get_descendants(cls);
for (auto child : children) {
while (true) {
auto child_cls = type_class(child);
if (!child_cls || child_cls->is_external()) {
break;
}
for (auto const& m : child_cls->get_vmethods()) {
if (signatures_match(method, m)) {
push(m);
}
}
child = child_cls->get_super_class();
}
}
}
}
void mark() {
for (auto const& dex : DexStoreClassesIterator(m_stores)) {
for (auto const& cls : dex) {
if (keep(cls) || is_canary(cls)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(cls));
push(cls);
}
for (auto const& f : cls->get_ifields()) {
if (keep(f) || is_volatile(f)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(f));
push(f);
}
}
for (auto const& f : cls->get_sfields()) {
if (keep(f)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(f));
push(f);
}
}
for (auto const& m : cls->get_dmethods()) {
if (keep(m)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(m));
push(m);
}
}
for (auto const& m : cls->get_vmethods()) {
if (keep(m) || implements_library_method(m, cls)) {
TRACE(RMU, 3, "Visiting seed: %s\n", SHOW(m));
push(m);
}
}
}
}
while (true) {
if (!m_class_stack.empty()) {
auto cls = m_class_stack.back();
m_class_stack.pop_back();
visit(cls);
continue;
}
if (!m_field_stack.empty()) {
auto field = m_field_stack.back();
m_field_stack.pop_back();
visit(const_cast<DexField*>(field));
continue;
}
if (!m_method_stack.empty()) {
auto method = m_method_stack.back();
m_method_stack.pop_back();
visit(const_cast<DexMethod*>(method));
continue;
}
return;
}
}
template<class Container, class Marked>
void sweep_if_unmarked(
Container& c,
const std::unordered_set<Marked>& marked
) {
c.erase(
std::remove_if(
c.begin(), c.end(),
[&](const Marked& m) {
if (marked.count(m) == 0) {
TRACE(RMU, 2, "Removing %s\n", SHOW(m));
return true;
}
return false;
}),
c.end());
}
void sweep() {
for (auto& dex : DexStoreClassesIterator(m_stores)) {
sweep_if_unmarked(dex, m_marked_classes);
for (auto const& cls : dex) {
sweep_if_unmarked(cls->get_ifields(), m_marked_fields);
sweep_if_unmarked(cls->get_sfields(), m_marked_fields);
sweep_if_unmarked(cls->get_dmethods(), m_marked_methods);
sweep_if_unmarked(cls->get_vmethods(), m_marked_methods);
}
}
}
private:
DexStoresVector& m_stores;
InheritanceGraph m_inheritance_graph;
std::unordered_set<const DexClass*> m_marked_classes;
std::unordered_set<const DexField*> m_marked_fields;
std::unordered_set<const DexMethod*> m_marked_methods;
std::vector<const DexClass*> m_class_stack;
std::vector<const DexField*> m_field_stack;
std::vector<const DexMethod*> m_method_stack;
};
}
void RemoveUnreachablePass::run_pass(
DexStoresVector& stores,
ConfigFiles& cfg,
PassManager& pm
) {
if (pm.no_proguard_rules()) {
TRACE(RMU, 1, "RemoveUnreachablePass not run because no ProGuard configuration was provided.");
return;
}
UnreachableCodeRemover ucr(stores);
deleted_stats before = trace_stats("before", stores);
ucr.mark_sweep();
deleted_stats after = trace_stats("after", stores);
pm.incr_metric("classes_removed", before.nclasses - after.nclasses);
pm.incr_metric("fields_removed", before.nfields - after.nfields);
pm.incr_metric("methods_removed", before.nmethods - after.nmethods);
}
static RemoveUnreachablePass s_pass;
|
Fix shadowing declaration in remove-unreachable
|
Fix shadowing declaration in remove-unreachable
Summary: Doesn't cause problems now, but it's never a good idea.
Reviewed By: dariorussi, newobj
Differential Revision: D4410063
fbshipit-source-id: 8a9b0b8e91f2d6617a41da733421ec439a930958
|
C++
|
mit
|
facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex
|
22781ab7e3c5309aa3bbd097d52231f294489770
|
hashers.cc
|
hashers.cc
|
/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hashers.hh"
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
template <typename T> struct hasher_traits;
template <> struct hasher_traits<md5_hasher> { using impl_type = CryptoPP::Weak::MD5; };
template <> struct hasher_traits<sha256_hasher> { using impl_type = CryptoPP::SHA256; };
template<typename H>
concept HashUpdater =
requires(hasher_traits<H>::impl_type& h, const CryptoPP::byte* ptr, size_t size) {
{ h.Update(ptr, size) } noexcept -> std::same_as<void>;
};
template <typename T, size_t size>
requires HashUpdater<T>
struct cryptopp_hasher<T, size>::impl {
using impl_type = typename hasher_traits<T>::impl_type;
impl_type hash{};
void update(const char* ptr, size_t length) noexcept {
using namespace CryptoPP;
static_assert(sizeof(char) == sizeof(byte), "Assuming lengths will be the same");
hash.Update(reinterpret_cast<const byte*>(ptr), length * sizeof(byte));
}
bytes finalize() {
bytes digest{bytes::initialized_later(), size};
hash.Final(reinterpret_cast<unsigned char*>(digest.begin()));
return digest;
}
std::array<uint8_t, size> finalize_array() {
std::array<uint8_t, size> array;
hash.Final(reinterpret_cast<unsigned char*>(array.data()));
return array;
}
};
template <typename T, size_t size> cryptopp_hasher<T, size>::cryptopp_hasher() : _impl(std::make_unique<impl>()) {}
template <typename T, size_t size> cryptopp_hasher<T, size>::~cryptopp_hasher() = default;
template <typename T, size_t size> cryptopp_hasher<T, size>::cryptopp_hasher(cryptopp_hasher&& o) noexcept = default;
template <typename T, size_t size> cryptopp_hasher<T, size>::cryptopp_hasher(const cryptopp_hasher& o) : _impl(std::make_unique<cryptopp_hasher<T, size>::impl>(*o._impl)) {}
template <typename T, size_t size> cryptopp_hasher<T, size>& cryptopp_hasher<T, size>::operator=(cryptopp_hasher&& o) noexcept = default;
template <typename T, size_t size> cryptopp_hasher<T, size>& cryptopp_hasher<T, size>::operator=(const cryptopp_hasher& o) {
_impl = std::make_unique<cryptopp_hasher<T, size>::impl>(*o._impl);
return *this;
}
template <typename T, size_t size> bytes cryptopp_hasher<T, size>::finalize() { return _impl->finalize(); }
template <typename T, size_t size> std::array<uint8_t, size> cryptopp_hasher<T, size>::finalize_array() {
return _impl->finalize_array();
}
template <typename T, size_t size> void cryptopp_hasher<T, size>::update(const char* ptr, size_t length) noexcept { _impl->update(ptr, length); }
template <typename T, size_t size> bytes cryptopp_hasher<T, size>::calculate(const std::string_view& s) {
typename cryptopp_hasher<T, size>::impl::impl_type hash;
unsigned char digest[size];
hash.CalculateDigest(digest, reinterpret_cast<const unsigned char*>(s.data()), s.size());
return std::move(bytes{reinterpret_cast<const int8_t*>(digest), size});
}
template class cryptopp_hasher<md5_hasher, 16>;
template class cryptopp_hasher<sha256_hasher, 32>;
|
/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hashers.hh"
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
template <typename T> struct hasher_traits;
template <> struct hasher_traits<md5_hasher> { using impl_type = CryptoPP::Weak::MD5; };
template <> struct hasher_traits<sha256_hasher> { using impl_type = CryptoPP::SHA256; };
template<typename H>
concept HashUpdater =
requires(typename hasher_traits<H>::impl_type& h, const CryptoPP::byte* ptr, size_t size) {
{ h.Update(ptr, size) } noexcept -> std::same_as<void>;
};
template <typename T, size_t size>
requires HashUpdater<T>
struct cryptopp_hasher<T, size>::impl {
using impl_type = typename hasher_traits<T>::impl_type;
impl_type hash{};
void update(const char* ptr, size_t length) noexcept {
using namespace CryptoPP;
static_assert(sizeof(char) == sizeof(byte), "Assuming lengths will be the same");
hash.Update(reinterpret_cast<const byte*>(ptr), length * sizeof(byte));
}
bytes finalize() {
bytes digest{bytes::initialized_later(), size};
hash.Final(reinterpret_cast<unsigned char*>(digest.begin()));
return digest;
}
std::array<uint8_t, size> finalize_array() {
std::array<uint8_t, size> array;
hash.Final(reinterpret_cast<unsigned char*>(array.data()));
return array;
}
};
template <typename T, size_t size> cryptopp_hasher<T, size>::cryptopp_hasher() : _impl(std::make_unique<impl>()) {}
template <typename T, size_t size> cryptopp_hasher<T, size>::~cryptopp_hasher() = default;
template <typename T, size_t size> cryptopp_hasher<T, size>::cryptopp_hasher(cryptopp_hasher&& o) noexcept = default;
template <typename T, size_t size> cryptopp_hasher<T, size>::cryptopp_hasher(const cryptopp_hasher& o) : _impl(std::make_unique<cryptopp_hasher<T, size>::impl>(*o._impl)) {}
template <typename T, size_t size> cryptopp_hasher<T, size>& cryptopp_hasher<T, size>::operator=(cryptopp_hasher&& o) noexcept = default;
template <typename T, size_t size> cryptopp_hasher<T, size>& cryptopp_hasher<T, size>::operator=(const cryptopp_hasher& o) {
_impl = std::make_unique<cryptopp_hasher<T, size>::impl>(*o._impl);
return *this;
}
template <typename T, size_t size> bytes cryptopp_hasher<T, size>::finalize() { return _impl->finalize(); }
template <typename T, size_t size> std::array<uint8_t, size> cryptopp_hasher<T, size>::finalize_array() {
return _impl->finalize_array();
}
template <typename T, size_t size> void cryptopp_hasher<T, size>::update(const char* ptr, size_t length) noexcept { _impl->update(ptr, length); }
template <typename T, size_t size> bytes cryptopp_hasher<T, size>::calculate(const std::string_view& s) {
typename cryptopp_hasher<T, size>::impl::impl_type hash;
unsigned char digest[size];
hash.CalculateDigest(digest, reinterpret_cast<const unsigned char*>(s.data()), s.size());
return std::move(bytes{reinterpret_cast<const int8_t*>(digest), size});
}
template class cryptopp_hasher<md5_hasher, 16>;
template class cryptopp_hasher<sha256_hasher, 32>;
|
add missing typename in Hashers concept
|
hashers: add missing typename in Hashers concept
Found by clang. Likely due to clang not implementing p0634r3, not a gcc
bug.
|
C++
|
agpl-3.0
|
scylladb/scylla,scylladb/scylla,scylladb/scylla,scylladb/scylla
|
ae9aeb16583feda559b9d736543c5969fa82a7bb
|
IO/Legacy/vtkTreeReader.cxx
|
IO/Legacy/vtkTreeReader.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkTreeReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkTreeReader.h"
#include "vtkByteSwap.h"
#include "vtkCellArray.h"
#include "vtkFieldData.h"
#include "vtkTree.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkStandardNewMacro(vtkTreeReader);
#ifdef read
#undef read
#endif
//----------------------------------------------------------------------------
vtkTreeReader::vtkTreeReader()
{
vtkTree *output = vtkTree::New();
this->SetOutput(output);
// Releasing data for pipeline parallism.
// Filters will know it is empty.
output->ReleaseData();
output->Delete();
}
//----------------------------------------------------------------------------
vtkTreeReader::~vtkTreeReader()
{
}
//----------------------------------------------------------------------------
vtkTree* vtkTreeReader::GetOutput()
{
return this->GetOutput(0);
}
//----------------------------------------------------------------------------
vtkTree* vtkTreeReader::GetOutput(int idx)
{
return vtkTree::SafeDownCast(this->GetOutputDataObject(idx));
}
//----------------------------------------------------------------------------
void vtkTreeReader::SetOutput(vtkTree *output)
{
this->GetExecutive()->SetOutputData(0, output);
}
//----------------------------------------------------------------------------
// I do not think this should be here, but I do not want to remove it now.
int vtkTreeReader::RequestUpdateExtent(
vtkInformation *,
vtkInformationVector **,
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
int piece, numPieces;
piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
// make sure piece is valid
if (piece < 0 || piece >= numPieces)
{
return 1;
}
return 1;
}
//----------------------------------------------------------------------------
int vtkTreeReader::RequestData(
vtkInformation *,
vtkInformationVector **,
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// Return all data in the first piece ...
if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)
{
return 1;
}
vtkDebugMacro(<<"Reading vtk tree ...");
if(!this->OpenVTKFile() || !this->ReadHeader())
{
return 1;
}
// Read table-specific stuff
char line[256];
if(!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile();
return 1;
}
if(strncmp(this->LowerCase(line),"dataset", (unsigned long)7))
{
vtkErrorMacro(<< "Unrecognized keyword: " << line);
this->CloseVTKFile();
return 1;
}
if(!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile ();
return 1;
}
if(strncmp(this->LowerCase(line),"tree", 4))
{
vtkErrorMacro(<< "Cannot read dataset type: " << line);
this->CloseVTKFile();
return 1;
}
vtkTree* const output = vtkTree::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkSmartPointer<vtkMutableDirectedGraph> builder =
vtkSmartPointer<vtkMutableDirectedGraph>::New();
int done = 0;
while(!done)
{
if(!this->ReadString(line))
{
break;
}
if(!strncmp(this->LowerCase(line), "field", 5))
{
vtkFieldData* const field_data = this->ReadFieldData();
builder->SetFieldData(field_data);
field_data->Delete();
continue;
}
if(!strncmp(this->LowerCase(line), "points", 6))
{
int point_count = 0;
if(!this->Read(&point_count))
{
vtkErrorMacro(<<"Cannot read number of points!");
this->CloseVTKFile ();
return 1;
}
this->ReadPoints(builder, point_count);
continue;
}
if(!strncmp(this->LowerCase(line), "edges", 4))
{
int edge_count = 0;
if(!this->Read(&edge_count))
{
vtkErrorMacro(<<"Cannot read number of edges!");
this->CloseVTKFile();
return 1;
}
// Create all of the tree vertices (number of edges + 1)
for(int edge = 0; edge <= edge_count; ++edge)
{
builder->AddVertex();
}
// Reparent the existing vertices so their order and topology match the original
int child = 0;
int parent = 0;
for(int edge = 0; edge != edge_count; ++edge)
{
if(!(this->Read(&child) && this->Read(&parent)))
{
vtkErrorMacro(<<"Cannot read edge!");
this->CloseVTKFile();
return 1;
}
builder->AddEdge(parent, child);
}
if (!output->CheckedShallowCopy(builder))
{
vtkErrorMacro(<<"Edges do not create a valid tree.");
this->CloseVTKFile();
return 1;
}
continue;
}
if(!strncmp(this->LowerCase(line), "vertex_data", 10))
{
int vertex_count = 0;
if(!this->Read(&vertex_count))
{
vtkErrorMacro(<<"Cannot read number of vertices!");
this->CloseVTKFile ();
return 1;
}
this->ReadVertexData(output, vertex_count);
continue;
}
if(!strncmp(this->LowerCase(line), "edge_data", 9))
{
int edge_count = 0;
if(!this->Read(&edge_count))
{
vtkErrorMacro(<<"Cannot read number of edges!");
this->CloseVTKFile ();
return 1;
}
this->ReadEdgeData(output, edge_count);
continue;
}
vtkErrorMacro(<< "Unrecognized keyword: " << line);
}
vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and "
<< output->GetNumberOfEdges() <<" edges.\n");
this->CloseVTKFile ();
return 1;
}
//----------------------------------------------------------------------------
int vtkTreeReader::FillOutputPortInformation(int, vtkInformation* info)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree");
return 1;
}
//----------------------------------------------------------------------------
void vtkTreeReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkTreeReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkTreeReader.h"
#include "vtkByteSwap.h"
#include "vtkCellArray.h"
#include "vtkFieldData.h"
#include "vtkTree.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkObjectFactory.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkStandardNewMacro(vtkTreeReader);
#ifdef read
#undef read
#endif
//----------------------------------------------------------------------------
vtkTreeReader::vtkTreeReader()
{
vtkTree *output = vtkTree::New();
this->SetOutput(output);
// Releasing data for pipeline parallism.
// Filters will know it is empty.
output->ReleaseData();
output->Delete();
}
//----------------------------------------------------------------------------
vtkTreeReader::~vtkTreeReader()
{
}
//----------------------------------------------------------------------------
vtkTree* vtkTreeReader::GetOutput()
{
return this->GetOutput(0);
}
//----------------------------------------------------------------------------
vtkTree* vtkTreeReader::GetOutput(int idx)
{
return vtkTree::SafeDownCast(this->GetOutputDataObject(idx));
}
//----------------------------------------------------------------------------
void vtkTreeReader::SetOutput(vtkTree *output)
{
this->GetExecutive()->SetOutputData(0, output);
}
//----------------------------------------------------------------------------
// I do not think this should be here, but I do not want to remove it now.
int vtkTreeReader::RequestUpdateExtent(
vtkInformation *,
vtkInformationVector **,
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
int piece, numPieces;
piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
// make sure piece is valid
if (piece < 0 || piece >= numPieces)
{
return 1;
}
return 1;
}
//----------------------------------------------------------------------------
int vtkTreeReader::RequestData(
vtkInformation *,
vtkInformationVector **,
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// Return all data in the first piece ...
if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)
{
return 1;
}
vtkDebugMacro(<<"Reading vtk tree ...");
if(!this->OpenVTKFile() || !this->ReadHeader())
{
return 1;
}
// Read table-specific stuff
char line[256];
if(!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile();
return 1;
}
if(strncmp(this->LowerCase(line),"dataset", (unsigned long)7))
{
vtkErrorMacro(<< "Unrecognized keyword: " << line);
this->CloseVTKFile();
return 1;
}
if(!this->ReadString(line))
{
vtkErrorMacro(<<"Data file ends prematurely!");
this->CloseVTKFile ();
return 1;
}
if(strncmp(this->LowerCase(line),"tree", 4))
{
vtkErrorMacro(<< "Cannot read dataset type: " << line);
this->CloseVTKFile();
return 1;
}
vtkTree* const output = vtkTree::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkSmartPointer<vtkMutableDirectedGraph> builder =
vtkSmartPointer<vtkMutableDirectedGraph>::New();
int done = 0;
while(!done)
{
if(!this->ReadString(line))
{
break;
}
if(!strncmp(this->LowerCase(line), "field", 5))
{
vtkFieldData* const field_data = this->ReadFieldData();
builder->SetFieldData(field_data);
field_data->Delete();
continue;
}
if(!strncmp(this->LowerCase(line), "points", 6))
{
int point_count = 0;
if(!this->Read(&point_count))
{
vtkErrorMacro(<<"Cannot read number of points!");
this->CloseVTKFile ();
return 1;
}
this->ReadPoints(builder, point_count);
continue;
}
if(!strncmp(this->LowerCase(line), "edges", 5))
{
int edge_count = 0;
if(!this->Read(&edge_count))
{
vtkErrorMacro(<<"Cannot read number of edges!");
this->CloseVTKFile();
return 1;
}
// Create all of the tree vertices (number of edges + 1)
for(int edge = 0; edge <= edge_count; ++edge)
{
builder->AddVertex();
}
// Reparent the existing vertices so their order and topology match the original
int child = 0;
int parent = 0;
for(int edge = 0; edge != edge_count; ++edge)
{
if(!(this->Read(&child) && this->Read(&parent)))
{
vtkErrorMacro(<<"Cannot read edge!");
this->CloseVTKFile();
return 1;
}
builder->AddEdge(parent, child);
}
if (!output->CheckedShallowCopy(builder))
{
vtkErrorMacro(<<"Edges do not create a valid tree.");
this->CloseVTKFile();
return 1;
}
continue;
}
if(!strncmp(this->LowerCase(line), "vertex_data", 10))
{
int vertex_count = 0;
if(!this->Read(&vertex_count))
{
vtkErrorMacro(<<"Cannot read number of vertices!");
this->CloseVTKFile ();
return 1;
}
this->ReadVertexData(output, vertex_count);
continue;
}
if(!strncmp(this->LowerCase(line), "edge_data", 9))
{
int edge_count = 0;
if(!this->Read(&edge_count))
{
vtkErrorMacro(<<"Cannot read number of edges!");
this->CloseVTKFile ();
return 1;
}
this->ReadEdgeData(output, edge_count);
continue;
}
vtkErrorMacro(<< "Unrecognized keyword: " << line);
}
vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and "
<< output->GetNumberOfEdges() <<" edges.\n");
this->CloseVTKFile ();
return 1;
}
//----------------------------------------------------------------------------
int vtkTreeReader::FillOutputPortInformation(int, vtkInformation* info)
{
info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree");
return 1;
}
//----------------------------------------------------------------------------
void vtkTreeReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
|
Fix strncmp(...) length when looking for "edges"
|
Fix strncmp(...) length when looking for "edges"
Any tree contain edge data would fail to read. As the
strncmp(...) to look for "edges" was passing a length
of 4, this would also match "edge_data"! Use a length
of 5 instead.
Change-Id: I3ad38600edbadb4a8cd89f5bb4f448cff64f0f23
|
C++
|
bsd-3-clause
|
candy7393/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,sankhesh/VTK,jmerkow/VTK,sankhesh/VTK,sankhesh/VTK,johnkit/vtk-dev,biddisco/VTK,collects/VTK,SimVascular/VTK,mspark93/VTK,mspark93/VTK,ashray/VTK-EVM,keithroe/vtkoptix,keithroe/vtkoptix,sankhesh/VTK,johnkit/vtk-dev,collects/VTK,berendkleinhaneveld/VTK,sumedhasingla/VTK,sumedhasingla/VTK,jmerkow/VTK,sumedhasingla/VTK,johnkit/vtk-dev,biddisco/VTK,msmolens/VTK,jmerkow/VTK,gram526/VTK,keithroe/vtkoptix,ashray/VTK-EVM,berendkleinhaneveld/VTK,msmolens/VTK,johnkit/vtk-dev,keithroe/vtkoptix,candy7393/VTK,mspark93/VTK,demarle/VTK,demarle/VTK,candy7393/VTK,mspark93/VTK,demarle/VTK,johnkit/vtk-dev,hendradarwin/VTK,demarle/VTK,collects/VTK,sankhesh/VTK,sumedhasingla/VTK,collects/VTK,mspark93/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,msmolens/VTK,hendradarwin/VTK,demarle/VTK,jmerkow/VTK,mspark93/VTK,demarle/VTK,ashray/VTK-EVM,gram526/VTK,SimVascular/VTK,biddisco/VTK,SimVascular/VTK,gram526/VTK,gram526/VTK,jmerkow/VTK,hendradarwin/VTK,sumedhasingla/VTK,ashray/VTK-EVM,mspark93/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,gram526/VTK,gram526/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,candy7393/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,biddisco/VTK,biddisco/VTK,candy7393/VTK,ashray/VTK-EVM,candy7393/VTK,biddisco/VTK,candy7393/VTK,msmolens/VTK,keithroe/vtkoptix,keithroe/vtkoptix,sankhesh/VTK,hendradarwin/VTK,hendradarwin/VTK,biddisco/VTK,SimVascular/VTK,sumedhasingla/VTK,jmerkow/VTK,ashray/VTK-EVM,demarle/VTK,msmolens/VTK,johnkit/vtk-dev,keithroe/vtkoptix,ashray/VTK-EVM,msmolens/VTK,sankhesh/VTK,mspark93/VTK,gram526/VTK,msmolens/VTK,hendradarwin/VTK,sankhesh/VTK,jmerkow/VTK,johnkit/vtk-dev,gram526/VTK,SimVascular/VTK,SimVascular/VTK,msmolens/VTK,collects/VTK,candy7393/VTK,SimVascular/VTK,demarle/VTK,collects/VTK,keithroe/vtkoptix
|
7f865766bab8345269a392900ecc19c84610db7c
|
browser/browser_context.cc
|
browser/browser_context.cc
|
// 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-CHROMIUM file.
#include "browser/browser_context.h"
#include "browser/download_manager_delegate.h"
#include "browser/inspectable_web_contents_impl.h"
#include "browser/network_delegate.h"
#include "browser/url_request_context_getter.h"
#include "common/application_info.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/prefs/json_pref_store.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/pref_service_builder.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#if defined(OS_LINUX)
#include "base/nix/xdg_util.h"
#endif
namespace brightray {
class BrowserContext::ResourceContext : public content::ResourceContext {
public:
ResourceContext() : getter_(nullptr) {}
void set_url_request_context_getter(URLRequestContextGetter* getter) {
getter_ = getter;
}
private:
virtual net::HostResolver* GetHostResolver() OVERRIDE {
return getter_->host_resolver();
}
virtual net::URLRequestContext* GetRequestContext() OVERRIDE {
return getter_->GetURLRequestContext();
}
// FIXME: We should probably allow clients to override this to implement more
// restrictive policies.
virtual bool AllowMicAccess(const GURL& origin) OVERRIDE {
return true;
}
// FIXME: We should probably allow clients to override this to implement more
// restrictive policies.
virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE {
return true;
}
URLRequestContextGetter* getter_;
};
BrowserContext::BrowserContext() : resource_context_(new ResourceContext) {
}
void BrowserContext::Initialize() {
base::FilePath path;
#if defined(OS_LINUX)
scoped_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
#else
CHECK(PathService::Get(base::DIR_APP_DATA, &path));
#endif
path_ = path.Append(base::FilePath::FromUTF8Unsafe(GetApplicationName()));
auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences"));
PrefServiceBuilder builder;
builder.WithUserFilePrefs(prefs_path,
JsonPrefStore::GetTaskRunnerForFile(
prefs_path, content::BrowserThread::GetBlockingPool()));
auto registry = make_scoped_refptr(new PrefRegistrySimple);
RegisterInternalPrefs(registry);
RegisterPrefs(registry);
prefs_.reset(builder.Create(registry));
}
BrowserContext::~BrowserContext() {
}
void BrowserContext::RegisterInternalPrefs(PrefRegistrySimple* registry) {
InspectableWebContentsImpl::RegisterPrefs(registry);
}
net::URLRequestContextGetter* BrowserContext::CreateRequestContext(
content::ProtocolHandlerMap* protocol_handlers) {
DCHECK(!url_request_getter_);
auto io_loop = content::BrowserThread::UnsafeGetMessageLoopForThread(
content::BrowserThread::IO);
auto file_loop = content::BrowserThread::UnsafeGetMessageLoopForThread(
content::BrowserThread::FILE);
url_request_getter_ = new URLRequestContextGetter(
GetPath(),
io_loop,
file_loop,
base::Bind(&BrowserContext::CreateNetworkDelegate, base::Unretained(this)),
protocol_handlers);
resource_context_->set_url_request_context_getter(url_request_getter_.get());
return url_request_getter_.get();
}
scoped_ptr<NetworkDelegate> BrowserContext::CreateNetworkDelegate() {
return make_scoped_ptr(new NetworkDelegate).Pass();
}
base::FilePath BrowserContext::GetPath() const {
return path_;
}
bool BrowserContext::IsOffTheRecord() const {
return false;
}
net::URLRequestContextGetter* BrowserContext::GetRequestContext() {
return GetDefaultStoragePartition(this)->GetURLRequestContext();
}
net::URLRequestContextGetter* BrowserContext::GetRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter* BrowserContext::GetMediaRequestContext() {
return GetRequestContext();
}
net::URLRequestContextGetter*
BrowserContext::GetMediaRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter*
BrowserContext::GetMediaRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory) {
return GetRequestContext();
}
void BrowserContext::RequestMIDISysExPermission(
int render_process_id,
int render_view_id,
const GURL& requesting_frame,
const MIDISysExPermissionCallback& callback) {
callback.Run(false);
}
content::ResourceContext* BrowserContext::GetResourceContext() {
return resource_context_.get();
}
content::DownloadManagerDelegate* BrowserContext::GetDownloadManagerDelegate() {
if (!download_manager_delegate_)
download_manager_delegate_.reset(new DownloadManagerDelegate);
return download_manager_delegate_.get();
}
content::GeolocationPermissionContext*
BrowserContext::GetGeolocationPermissionContext() {
return nullptr;
}
quota::SpecialStoragePolicy* BrowserContext::GetSpecialStoragePolicy() {
return nullptr;
}
} // namespace brightray
|
// 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-CHROMIUM file.
#include "browser/browser_context.h"
#include "browser/download_manager_delegate.h"
#include "browser/inspectable_web_contents_impl.h"
#include "browser/network_delegate.h"
#include "browser/url_request_context_getter.h"
#include "common/application_info.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/prefs/json_pref_store.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/pref_service_builder.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#if defined(OS_LINUX)
#include "base/nix/xdg_util.h"
#endif
namespace brightray {
class BrowserContext::ResourceContext : public content::ResourceContext {
public:
ResourceContext() : getter_(nullptr) {}
void set_url_request_context_getter(URLRequestContextGetter* getter) {
getter_ = getter;
}
private:
virtual net::HostResolver* GetHostResolver() OVERRIDE {
return getter_->host_resolver();
}
virtual net::URLRequestContext* GetRequestContext() OVERRIDE {
return getter_->GetURLRequestContext();
}
// FIXME: We should probably allow clients to override this to implement more
// restrictive policies.
virtual bool AllowMicAccess(const GURL& origin) OVERRIDE {
return true;
}
// FIXME: We should probably allow clients to override this to implement more
// restrictive policies.
virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE {
return true;
}
URLRequestContextGetter* getter_;
};
BrowserContext::BrowserContext() : resource_context_(new ResourceContext) {
}
void BrowserContext::Initialize() {
base::FilePath path;
#if defined(OS_LINUX)
scoped_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
#else
CHECK(PathService::Get(base::DIR_APP_DATA, &path));
#endif
path_ = path.Append(base::FilePath::FromUTF8Unsafe(GetApplicationName()));
auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences"));
PrefServiceBuilder builder;
builder.WithUserFilePrefs(prefs_path,
JsonPrefStore::GetTaskRunnerForFile(
prefs_path, content::BrowserThread::GetBlockingPool()));
auto registry = make_scoped_refptr(new PrefRegistrySimple);
RegisterInternalPrefs(registry);
RegisterPrefs(registry);
prefs_.reset(builder.Create(registry));
}
BrowserContext::~BrowserContext() {
content::BrowserThread::DeleteSoon(content::BrowserThread::IO,
FROM_HERE,
resource_context_.release());
}
void BrowserContext::RegisterInternalPrefs(PrefRegistrySimple* registry) {
InspectableWebContentsImpl::RegisterPrefs(registry);
}
net::URLRequestContextGetter* BrowserContext::CreateRequestContext(
content::ProtocolHandlerMap* protocol_handlers) {
DCHECK(!url_request_getter_);
auto io_loop = content::BrowserThread::UnsafeGetMessageLoopForThread(
content::BrowserThread::IO);
auto file_loop = content::BrowserThread::UnsafeGetMessageLoopForThread(
content::BrowserThread::FILE);
url_request_getter_ = new URLRequestContextGetter(
GetPath(),
io_loop,
file_loop,
base::Bind(&BrowserContext::CreateNetworkDelegate, base::Unretained(this)),
protocol_handlers);
resource_context_->set_url_request_context_getter(url_request_getter_.get());
return url_request_getter_.get();
}
scoped_ptr<NetworkDelegate> BrowserContext::CreateNetworkDelegate() {
return make_scoped_ptr(new NetworkDelegate).Pass();
}
base::FilePath BrowserContext::GetPath() const {
return path_;
}
bool BrowserContext::IsOffTheRecord() const {
return false;
}
net::URLRequestContextGetter* BrowserContext::GetRequestContext() {
return GetDefaultStoragePartition(this)->GetURLRequestContext();
}
net::URLRequestContextGetter* BrowserContext::GetRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter* BrowserContext::GetMediaRequestContext() {
return GetRequestContext();
}
net::URLRequestContextGetter*
BrowserContext::GetMediaRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter*
BrowserContext::GetMediaRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory) {
return GetRequestContext();
}
void BrowserContext::RequestMIDISysExPermission(
int render_process_id,
int render_view_id,
const GURL& requesting_frame,
const MIDISysExPermissionCallback& callback) {
callback.Run(false);
}
content::ResourceContext* BrowserContext::GetResourceContext() {
return resource_context_.get();
}
content::DownloadManagerDelegate* BrowserContext::GetDownloadManagerDelegate() {
if (!download_manager_delegate_)
download_manager_delegate_.reset(new DownloadManagerDelegate);
return download_manager_delegate_.get();
}
content::GeolocationPermissionContext*
BrowserContext::GetGeolocationPermissionContext() {
return nullptr;
}
quota::SpecialStoragePolicy* BrowserContext::GetSpecialStoragePolicy() {
return nullptr;
}
} // namespace brightray
|
Destroy ResourceContext on the IO thread
|
Destroy ResourceContext on the IO thread
This matches content_shell and fixes a debug assertion (and maybe even a
crash).
|
C++
|
mit
|
paulcbetts/brightray,bbondy/brightray,deepak1556/brightray,brave/brightray,deepak1556/brightray,tejaspathak/brightray,paulcbetts/brightray,hokein/brightray,hokein/brightray,atom/brightray,lakshmi-srinivas/brightray,lakshmi-srinivas/brightray,lakshmi-srinivas/brightray,atom/brightray,bbondy/brightray,brave/brightray,tejaspathak/brightray
|
cdde5b89aed66db069a09ab4008688af3bf9f3d4
|
game/temporary_systems/physics_system.cpp
|
game/temporary_systems/physics_system.cpp
|
#include "physics_system.h"
#include "game/transcendental/entity_id.h"
#include "game/transcendental/cosmos.h"
#include "game/components/item_component.h"
#include "game/components/driver_component.h"
#include "game/components/fixtures_component.h"
#include "game/components/special_physics_component.h"
#include "game/messages/collision_message.h"
#include "game/messages/queue_destruction.h"
#include "game/messages/new_entity_message.h"
#include "game/messages/will_soon_be_deleted.h"
#include "game/transcendental/cosmos.h"
#include "game/transcendental/step.h"
#include "game/transcendental/entity_handle.h"
double METERS_TO_PIXELS = 100.0;
double PIXELS_TO_METERS = 1.0 / METERS_TO_PIXELS;
float METERS_TO_PIXELSf = 100.f;
float PIXELS_TO_METERSf = 1.0f / METERS_TO_PIXELSf;
bool physics_system::is_constructed_rigid_body(const_entity_handle handle) const {
return handle.alive() && get_rigid_body_cache(handle).body != nullptr;
}
bool physics_system::is_constructed_colliders(const_entity_handle handle) const {
return
handle.alive() // && is_constructed_rigid_body(handle.get<components::fixtures>().get_owner_body())
&&
get_colliders_cache(handle).fixtures_per_collider.size()> 0 &&
get_colliders_cache(handle).fixtures_per_collider[0].size() > 0;
}
rigid_body_cache& physics_system::get_rigid_body_cache(entity_id id) {
return rigid_body_caches[id.pool.indirection_index];
}
colliders_cache& physics_system::get_colliders_cache(entity_id id) {
return colliders_caches[id.pool.indirection_index];
}
const rigid_body_cache& physics_system::get_rigid_body_cache(entity_id id) const {
return rigid_body_caches[id.pool.indirection_index];
}
const colliders_cache& physics_system::get_colliders_cache(entity_id id) const {
return colliders_caches[id.pool.indirection_index];
}
void physics_system::destruct(const_entity_handle handle) {
if (is_constructed_rigid_body(handle)) {
auto& cache = get_rigid_body_cache(handle);
for (auto& colliders_cache_id : cache.correspondent_colliders_caches)
colliders_caches[colliders_cache_id] = colliders_cache();
b2world.DestroyBody(cache.body);
cache = rigid_body_cache();
}
if (is_constructed_colliders(handle)) {
auto this_cache_id = handle.get_id().pool.indirection_index;
auto& cache = colliders_caches[this_cache_id];
ensure(cache.correspondent_rigid_body_cache != -1);
auto& owner_body_cache = rigid_body_caches[cache.correspondent_rigid_body_cache];
for (auto& f_per_c : cache.fixtures_per_collider)
for (auto f : f_per_c)
owner_body_cache.body->DestroyFixture(f);
remove_element(owner_body_cache.correspondent_colliders_caches, this_cache_id);
cache = colliders_cache();
}
}
void physics_system::fixtures_construct(const_entity_handle handle) {
//ensure(!is_constructed_colliders(handle));
if (is_constructed_colliders(handle))
return;
if (handle.has<components::fixtures>()) {
auto& colliders = handle.get<components::fixtures>();
if (colliders.is_activated() && is_constructed_rigid_body(colliders.get_owner_body())) {
auto& colliders_data = colliders.get_data();
auto& cache = get_colliders_cache(handle);
auto owner_body_entity = colliders.get_owner_body();
ensure(owner_body_entity.alive());
auto& owner_cache = get_rigid_body_cache(owner_body_entity);
auto this_cache_id = handle.get_id().pool.indirection_index;
auto owner_cache_id = owner_body_entity.get_id().pool.indirection_index;
owner_cache.correspondent_colliders_caches.push_back(this_cache_id);
cache.correspondent_rigid_body_cache = owner_cache_id;
for (const auto& c : colliders_data.colliders) {
b2PolygonShape shape;
b2FixtureDef fixdef;
fixdef.density = c.density;
fixdef.friction = c.friction;
fixdef.isSensor = c.sensor;
fixdef.filter = c.filter;
fixdef.restitution = c.restitution;
fixdef.shape = &shape;
fixdef.userData = handle.get_id();
auto transformed_shape = c.shape;
transformed_shape.offset_vertices(colliders.get_total_offset());
std::vector<b2Fixture*> partitioned_collider;
for (auto convex : transformed_shape.convex_polys) {
std::vector<b2Vec2> b2verts(convex.begin(), convex.end());
for (auto& v : b2verts)
v *= PIXELS_TO_METERSf;
shape.Set(b2verts.data(), b2verts.size());
partitioned_collider.push_back(owner_cache.body->CreateFixture(&fixdef));
}
cache.fixtures_per_collider.push_back(partitioned_collider);
}
}
}
}
void physics_system::construct(const_entity_handle handle) {
//ensure(!is_constructed_rigid_body(handle));
if (is_constructed_rigid_body(handle))
return;
fixtures_construct(handle);
if (handle.has<components::physics>()) {
const auto& physics = handle.get<components::physics>();
const auto& fixture_entities = physics.get_fixture_entities();
if (physics.is_activated() && fixture_entities.size() > 0) {
auto& physics_data = physics.get_data();
auto& cache = get_rigid_body_cache(handle);
b2BodyDef def;
switch (physics_data.body_type) {
case components::physics::type::DYNAMIC: def.type = b2BodyType::b2_dynamicBody; break;
case components::physics::type::STATIC: def.type = b2BodyType::b2_staticBody; break;
case components::physics::type::KINEMATIC: def.type = b2BodyType::b2_kinematicBody; break;
default:ensure(false) break;
}
def.userData = handle.get_id();
def.bullet = physics_data.bullet;
def.position = physics_data.transform.pos * PIXELS_TO_METERSf;
def.angle = physics_data.transform.rotation * DEG_TO_RADf;
def.angularDamping = physics_data.angular_damping;
def.linearDamping = physics_data.linear_damping;
def.fixedRotation = physics_data.fixed_rotation;
def.gravityScale = physics_data.gravity_scale;
def.active = true;
def.linearVelocity = physics_data.velocity * PIXELS_TO_METERSf;
def.angularVelocity = physics_data.angular_velocity * DEG_TO_RADf;
cache.body = b2world.CreateBody(&def);
cache.body->SetAngledDampingEnabled(physics_data.angled_damping);
/* notice that all fixtures must be unconstructed at this moment since we assert that the rigid body itself is not */
for (const auto& f : fixture_entities)
fixtures_construct(f);
}
}
}
void physics_system::reserve_caches_for_entities(size_t n) {
rigid_body_caches.resize(n);
colliders_caches.resize(n);
}
physics_system::physics_system() :
b2world(b2Vec2(0.f, 0.f)), ray_casts_since_last_step(0) {
b2world.SetAllowSleeping(false);
b2world.SetAutoClearForces(false);
}
void physics_system::post_and_clear_accumulated_collision_messages(fixed_step& step) {
step.messages.post(accumulated_messages);
accumulated_messages.clear();
}
physics_system& physics_system::contact_listener::get_sys() const {
return cosm.temporary_systems.get<physics_system>();
}
physics_system::contact_listener::contact_listener(cosmos& cosm) : cosm(cosm) {
get_sys().b2world.SetContactListener(this);
}
physics_system::contact_listener::~contact_listener() {
get_sys().b2world.SetContactListener(nullptr);
}
void physics_system::step_and_set_new_transforms(fixed_step& step) {
auto& cosmos = step.cosm;
auto& delta = step.get_delta();
int32 velocityIterations = 8;
int32 positionIterations = 3;
for (b2Body* b = b2world.GetBodyList(); b != nullptr; b = b->GetNext()) {
if (b->GetType() == b2_staticBody) continue;
entity_handle entity = cosmos[b->GetUserData()];
auto& physics = entity.get<components::physics>();
auto& special = entity.get<components::special_physics>();
special.measured_carried_mass = 0.f;
b2Vec2 vel(b->GetLinearVelocity());
float32 speed = vel.Normalize();
float32 angular_speed = b->GetAngularVelocity();
//if (physics.air_resistance > 0.f) {
// auto force_dir = physics.get_mass() * -vel;
// auto force_components = (physics.air_resistance * speed * speed);
//
// //if (speed > 1.0)
// // force_components += (0.5f * sqrt(std::abs(speed)));
//
// physics.body->ApplyForce(force_components * force_dir, physics.body->GetWorldCenter(), true);
//}
auto angular_resistance = special.angular_air_resistance;
if (angular_resistance < 0.f) angular_resistance = special.air_resistance;
if (angular_resistance > 0.f) {
//physics.body->ApplyTorque((angular_resistance * sqrt(sqrt(angular_speed * angular_speed)) + 0.2 * angular_speed * angular_speed)* -sgn(angular_speed) * b->GetInertia(), true);
b->ApplyTorque((angular_resistance * angular_speed * angular_speed)* -sgn(angular_speed) * b->GetInertia(), true);
}
if (special.enable_angle_motor) {
b->SetTransform(b->GetPosition(), special.target_angle * DEG_TO_RADf);
b->SetAngularVelocity(0);
}
}
ray_casts_since_last_step = 0;
b2world.Step(static_cast<float32>(delta.in_seconds()), velocityIterations, positionIterations);
b2world.ClearForces();
post_and_clear_accumulated_collision_messages(step);
for (b2Body* b = b2world.GetBodyList(); b != nullptr; b = b->GetNext()) {
if (b->GetType() == b2_staticBody) continue;
entity_handle entity = cosmos[b->GetUserData()];
auto& physics = entity.get<components::physics>();
recurential_friction_handler(step, entity, entity.get_owner_friction_ground());
auto body_pos = METERS_TO_PIXELSf * b->GetPosition();
auto body_angle = b->GetAngle() * RAD_TO_DEGf;
auto& transform = entity.get<components::transform>();
transform.pos = body_pos;
if (!b->IsFixedRotation())
transform.rotation = body_angle;
physics.component.transform = transform;
physics.component.velocity = METERS_TO_PIXELSf * b->GetLinearVelocity();
physics.component.angular_velocity = RAD_TO_DEGf * b->GetAngularVelocity();
for (const auto& fe : physics.get_fixture_entities()) {
auto& fixtures = fe.get<components::fixtures>();
auto total_offset = fixtures.get_total_offset();
auto& fix_transform = fe.get<components::transform>();
fix_transform.pos = body_pos;
if (!b->IsFixedRotation())
fix_transform.rotation = body_angle;
fix_transform.pos += total_offset.pos;
fix_transform.rotation += total_offset.rotation;
fix_transform.pos.rotate(body_angle, body_pos);
}
}
}
|
#include "physics_system.h"
#include "game/transcendental/entity_id.h"
#include "game/transcendental/cosmos.h"
#include "game/components/item_component.h"
#include "game/components/driver_component.h"
#include "game/components/fixtures_component.h"
#include "game/components/special_physics_component.h"
#include "game/messages/collision_message.h"
#include "game/messages/queue_destruction.h"
#include "game/messages/new_entity_message.h"
#include "game/messages/will_soon_be_deleted.h"
#include "game/transcendental/cosmos.h"
#include "game/transcendental/step.h"
#include "game/transcendental/entity_handle.h"
double METERS_TO_PIXELS = 100.0;
double PIXELS_TO_METERS = 1.0 / METERS_TO_PIXELS;
float METERS_TO_PIXELSf = 100.f;
float PIXELS_TO_METERSf = 1.0f / METERS_TO_PIXELSf;
bool physics_system::is_constructed_rigid_body(const_entity_handle handle) const {
return handle.alive() && get_rigid_body_cache(handle).body != nullptr;
}
bool physics_system::is_constructed_colliders(const_entity_handle handle) const {
return
handle.alive() // && is_constructed_rigid_body(handle.get<components::fixtures>().get_owner_body())
&&
get_colliders_cache(handle).fixtures_per_collider.size()> 0 &&
get_colliders_cache(handle).fixtures_per_collider[0].size() > 0;
}
rigid_body_cache& physics_system::get_rigid_body_cache(entity_id id) {
return rigid_body_caches[id.pool.indirection_index];
}
colliders_cache& physics_system::get_colliders_cache(entity_id id) {
return colliders_caches[id.pool.indirection_index];
}
const rigid_body_cache& physics_system::get_rigid_body_cache(entity_id id) const {
return rigid_body_caches[id.pool.indirection_index];
}
const colliders_cache& physics_system::get_colliders_cache(entity_id id) const {
return colliders_caches[id.pool.indirection_index];
}
void physics_system::destruct(const_entity_handle handle) {
if (is_constructed_rigid_body(handle)) {
auto& cache = get_rigid_body_cache(handle);
for (auto& colliders_cache_id : cache.correspondent_colliders_caches)
colliders_caches[colliders_cache_id] = colliders_cache();
b2world.DestroyBody(cache.body);
cache = rigid_body_cache();
}
if (is_constructed_colliders(handle)) {
auto this_cache_id = handle.get_id().pool.indirection_index;
auto& cache = colliders_caches[this_cache_id];
ensure(cache.correspondent_rigid_body_cache != -1);
auto& owner_body_cache = rigid_body_caches[cache.correspondent_rigid_body_cache];
for (auto& f_per_c : cache.fixtures_per_collider)
for (auto f : f_per_c)
owner_body_cache.body->DestroyFixture(f);
remove_element(owner_body_cache.correspondent_colliders_caches, this_cache_id);
cache = colliders_cache();
}
}
void physics_system::fixtures_construct(const_entity_handle handle) {
//ensure(!is_constructed_colliders(handle));
if (is_constructed_colliders(handle))
return;
if (handle.has<components::fixtures>()) {
auto& colliders = handle.get<components::fixtures>();
if (colliders.is_activated() && is_constructed_rigid_body(colliders.get_owner_body())) {
auto& colliders_data = colliders.get_data();
auto& cache = get_colliders_cache(handle);
auto owner_body_entity = colliders.get_owner_body();
ensure(owner_body_entity.alive());
auto& owner_cache = get_rigid_body_cache(owner_body_entity);
auto this_cache_id = handle.get_id().pool.indirection_index;
auto owner_cache_id = owner_body_entity.get_id().pool.indirection_index;
owner_cache.correspondent_colliders_caches.push_back(this_cache_id);
cache.correspondent_rigid_body_cache = owner_cache_id;
for (const auto& c : colliders_data.colliders) {
b2PolygonShape shape;
b2FixtureDef fixdef;
fixdef.density = c.density;
fixdef.friction = c.friction;
fixdef.isSensor = c.sensor;
fixdef.filter = c.filter;
fixdef.restitution = c.restitution;
fixdef.shape = &shape;
fixdef.userData = handle.get_id();
auto transformed_shape = c.shape;
transformed_shape.offset_vertices(colliders.get_total_offset());
std::vector<b2Fixture*> partitioned_collider;
for (auto convex : transformed_shape.convex_polys) {
std::vector<b2Vec2> b2verts(convex.begin(), convex.end());
for (auto& v : b2verts)
v *= PIXELS_TO_METERSf;
shape.Set(b2verts.data(), b2verts.size());
partitioned_collider.push_back(owner_cache.body->CreateFixture(&fixdef));
}
cache.fixtures_per_collider.push_back(partitioned_collider);
}
}
}
}
void physics_system::construct(const_entity_handle handle) {
//ensure(!is_constructed_rigid_body(handle));
if (is_constructed_rigid_body(handle))
return;
fixtures_construct(handle);
if (handle.has<components::physics>()) {
const auto& physics = handle.get<components::physics>();
const auto& fixture_entities = physics.get_fixture_entities();
if (physics.is_activated() && fixture_entities.size() > 0) {
auto& physics_data = physics.get_data();
auto& cache = get_rigid_body_cache(handle);
b2BodyDef def;
switch (physics_data.body_type) {
case components::physics::type::DYNAMIC: def.type = b2BodyType::b2_dynamicBody; break;
case components::physics::type::STATIC: def.type = b2BodyType::b2_staticBody; break;
case components::physics::type::KINEMATIC: def.type = b2BodyType::b2_kinematicBody; break;
default:ensure(false) break;
}
def.userData = handle.get_id();
def.bullet = physics_data.bullet;
def.position = physics_data.transform.pos * PIXELS_TO_METERSf;
def.angle = physics_data.transform.rotation * DEG_TO_RADf;
def.angularDamping = physics_data.angular_damping;
def.linearDamping = physics_data.linear_damping;
def.fixedRotation = physics_data.fixed_rotation;
def.gravityScale = physics_data.gravity_scale;
def.active = true;
def.linearVelocity = physics_data.velocity * PIXELS_TO_METERSf;
def.angularVelocity = physics_data.angular_velocity * DEG_TO_RADf;
cache.body = b2world.CreateBody(&def);
cache.body->SetAngledDampingEnabled(physics_data.angled_damping);
/* notice that all fixtures must be unconstructed at this moment since we assert that the rigid body itself is not */
for (const auto& f : fixture_entities)
fixtures_construct(f);
}
}
}
void physics_system::reserve_caches_for_entities(size_t n) {
rigid_body_caches.resize(n);
colliders_caches.resize(n);
}
physics_system::physics_system() :
b2world(b2Vec2(0.f, 0.f)), ray_casts_since_last_step(0) {
b2world.SetAllowSleeping(true);
b2world.SetAutoClearForces(false);
}
void physics_system::post_and_clear_accumulated_collision_messages(fixed_step& step) {
step.messages.post(accumulated_messages);
accumulated_messages.clear();
}
physics_system& physics_system::contact_listener::get_sys() const {
return cosm.temporary_systems.get<physics_system>();
}
physics_system::contact_listener::contact_listener(cosmos& cosm) : cosm(cosm) {
get_sys().b2world.SetContactListener(this);
}
physics_system::contact_listener::~contact_listener() {
get_sys().b2world.SetContactListener(nullptr);
}
void physics_system::step_and_set_new_transforms(fixed_step& step) {
auto& cosmos = step.cosm;
auto& delta = step.get_delta();
int32 velocityIterations = 8;
int32 positionIterations = 3;
for (b2Body* b = b2world.GetBodyList(); b != nullptr; b = b->GetNext()) {
if (b->GetType() == b2_staticBody) continue;
entity_handle entity = cosmos[b->GetUserData()];
auto& physics = entity.get<components::physics>();
auto& special = entity.get<components::special_physics>();
special.measured_carried_mass = 0.f;
b2Vec2 vel(b->GetLinearVelocity());
float32 speed = vel.Normalize();
float32 angular_speed = b->GetAngularVelocity();
//if (physics.air_resistance > 0.f) {
// auto force_dir = physics.get_mass() * -vel;
// auto force_components = (physics.air_resistance * speed * speed);
//
// //if (speed > 1.0)
// // force_components += (0.5f * sqrt(std::abs(speed)));
//
// physics.body->ApplyForce(force_components * force_dir, physics.body->GetWorldCenter(), true);
//}
auto angular_resistance = special.angular_air_resistance;
if (angular_resistance < 0.f) angular_resistance = special.air_resistance;
if (angular_resistance > 0.f) {
//physics.body->ApplyTorque((angular_resistance * sqrt(sqrt(angular_speed * angular_speed)) + 0.2 * angular_speed * angular_speed)* -sgn(angular_speed) * b->GetInertia(), true);
b->ApplyTorque((angular_resistance * angular_speed * angular_speed)* -sgn(angular_speed) * b->GetInertia(), true);
}
if (special.enable_angle_motor) {
b->SetTransform(b->GetPosition(), special.target_angle * DEG_TO_RADf);
b->SetAngularVelocity(0);
}
}
ray_casts_since_last_step = 0;
b2world.Step(static_cast<float32>(delta.in_seconds()), velocityIterations, positionIterations);
b2world.ClearForces();
post_and_clear_accumulated_collision_messages(step);
for (b2Body* b = b2world.GetBodyList(); b != nullptr; b = b->GetNext()) {
if (b->GetType() == b2_staticBody) continue;
entity_handle entity = cosmos[b->GetUserData()];
auto& physics = entity.get<components::physics>();
recurential_friction_handler(step, entity, entity.get_owner_friction_ground());
auto body_pos = METERS_TO_PIXELSf * b->GetPosition();
auto body_angle = b->GetAngle() * RAD_TO_DEGf;
auto& transform = entity.get<components::transform>();
transform.pos = body_pos;
if (!b->IsFixedRotation())
transform.rotation = body_angle;
physics.component.transform = transform;
physics.component.velocity = METERS_TO_PIXELSf * b->GetLinearVelocity();
physics.component.angular_velocity = RAD_TO_DEGf * b->GetAngularVelocity();
for (const auto& fe : physics.get_fixture_entities()) {
auto& fixtures = fe.get<components::fixtures>();
auto total_offset = fixtures.get_total_offset();
auto& fix_transform = fe.get<components::transform>();
fix_transform.pos = body_pos;
if (!b->IsFixedRotation())
fix_transform.rotation = body_angle;
fix_transform.pos += total_offset.pos;
fix_transform.rotation += total_offset.rotation;
fix_transform.pos.rotate(body_angle, body_pos);
}
}
}
|
allow sleeping for better stability of the universe
|
allow sleeping for better stability of the universe
|
C++
|
agpl-3.0
|
TeamHypersomnia/Hypersomnia,TeamHypersomnia/Augmentations,DaTa-/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Augmentations,DaTa-/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,TeamHypersomnia/Hypersomnia,DaTa-/Hypersomnia
|
e46cf4cbccc8dbc998ae6edc49c9e425879ec4c8
|
framework/src/geomsearch/PenetrationLocator.C
|
framework/src/geomsearch/PenetrationLocator.C
|
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PenetrationLocator.h"
#include "ArbitraryQuadrature.h"
#include "LineSegment.h"
#include "NearestNodeLocator.h"
#include "MooseMesh.h"
#include "SubProblem.h"
#include "GeometricSearchData.h"
#include "PenetrationThread.h"
#include "Moose.h"
PenetrationLocator::PenetrationLocator(SubProblem & subproblem, GeometricSearchData & geom_search_data, MooseMesh & mesh, const unsigned int master_id, const unsigned int slave_id, Order order, NearestNodeLocator & nearest_node) :
_subproblem(subproblem),
_mesh(mesh),
_master_boundary(master_id),
_slave_boundary(slave_id),
_fe_type(order),
_nearest_node(nearest_node),
_update_location(true),
_tangential_tolerance(0.0)
{
// Preconstruct an FE object for each thread we're going to use
// This is a time savings so that the thread objects don't do this themselves multiple times
_fe.resize(libMesh::n_threads());
for(unsigned int i=0; i < libMesh::n_threads(); i++)
_fe[i] = FEBase::build(_mesh.dimension()-1, _fe_type).release();
}
PenetrationLocator::~PenetrationLocator()
{
for(unsigned int i=0; i < libMesh::n_threads(); i++)
delete _fe[i];
for (std::map<unsigned int, PenetrationInfo *>::iterator it = _penetration_info.begin(); it != _penetration_info.end(); ++it)
delete it->second;
}
void
PenetrationLocator::detectPenetration()
{
Moose::perf_log.push("detectPenetration()","Solve");
// Data structures to hold the element boundary information
std::vector< unsigned int > elem_list;
std::vector< unsigned short int > side_list;
std::vector< short int > id_list;
// Retrieve the Element Boundary data structures from the mesh
_mesh.build_side_list(elem_list, side_list, id_list);
// Grab the slave nodes we need to worry about from the NearestNodeLocator
NodeIdRange & slave_node_range = _nearest_node.slaveNodeRange();
PenetrationThread pt(_mesh,
_master_boundary,
_slave_boundary,
_penetration_info,
_update_location,
_tangential_tolerance,
_fe,
_fe_type,
_nearest_node,
_mesh.nodeToElemMap(),
elem_list,
side_list,
id_list);
Threads::parallel_reduce(slave_node_range, pt);
Moose::perf_log.pop("detectPenetration()","Solve");
}
Real
PenetrationLocator::penetrationDistance(unsigned int node_id)
{
PenetrationInfo * info = _penetration_info[node_id];
if (info)
return info->_distance;
else
return 0;
}
RealVectorValue
PenetrationLocator::penetrationNormal(unsigned int node_id)
{
std::map<unsigned int, PenetrationInfo *>::const_iterator found_it( _penetration_info.find(node_id) );
if (found_it != _penetration_info.end())
return found_it->second->_normal;
else
return RealVectorValue(0, 0, 0);
}
void
PenetrationLocator::setUpdate( bool update )
{
_update_location = update;
}
void
PenetrationLocator::setTangentialTolerance(Real tangential_tolerance)
{
_tangential_tolerance = tangential_tolerance;
}
void
PenetrationLocator::setStartingContactPoint()
{
std::map<unsigned int, PenetrationInfo *>::iterator it( _penetration_info.begin() );
const std::map<unsigned int, PenetrationInfo *>::iterator it_end( _penetration_info.end() );
for ( ; it != it_end; ++it )
{
it->second->_starting_elem = it->second->_elem;
it->second->_starting_side_num = it->second->_side_num;
it->second->_starting_closest_point_ref = it->second->_closest_point_ref;
}
}
void
PenetrationLocator::saveContactForce()
{
std::map<unsigned int, PenetrationInfo *>::iterator it( _penetration_info.begin() );
const std::map<unsigned int, PenetrationInfo *>::iterator it_end( _penetration_info.end() );
for ( ; it != it_end; ++it )
{
it->second->_contact_force_old = it->second->_contact_force;
}
}
PenetrationLocator::PenetrationInfo::PenetrationInfo(const Node * node, const Elem * elem, Elem * side, unsigned int side_num, RealVectorValue norm, Real norm_distance, Real tangential_distance, const Point & closest_point, const Point & closest_point_ref, const Point & closest_point_on_face_ref, std::vector<Node*> off_edge_nodes, const std::vector<std::vector<Real> > & side_phi, const std::vector<RealGradient> & dxyzdxi, const std::vector<RealGradient> & dxyzdeta, const std::vector<RealGradient> & d2xyzdxideta)
:_node(node),
_elem(elem),
_side(side),
_side_num(side_num),
_normal(norm),
_distance(norm_distance),
_tangential_distance(tangential_distance),
_closest_point(closest_point),
_closest_point_ref(closest_point_ref),
_closest_point_on_face_ref(closest_point_on_face_ref),
_off_edge_nodes(off_edge_nodes),
_side_phi(side_phi),
_dxyzdxi(dxyzdxi),
_dxyzdeta(dxyzdeta),
_d2xyzdxideta(d2xyzdxideta),
_update(true)
{}
PenetrationLocator::PenetrationInfo::PenetrationInfo(const PenetrationInfo & p) :
_node(p._node),
_elem(p._elem),
_side(p._side), // Which one now owns _side? There will be trouble if (when)
// both delete _side
_side_num(p._side_num),
_normal(p._normal),
_distance(p._distance),
_tangential_distance(p._tangential_distance),
_closest_point(p._closest_point),
_closest_point_ref(p._closest_point_ref),
_closest_point_on_face_ref(p._closest_point_on_face_ref),
_off_edge_nodes(p._off_edge_nodes),
_side_phi(p._side_phi),
_dxyzdxi(p._dxyzdxi),
_dxyzdeta(p._dxyzdeta),
_d2xyzdxideta(p._d2xyzdxideta),
_starting_elem(p._starting_elem),
_starting_side_num(p._starting_side_num),
_starting_closest_point_ref(p._starting_closest_point_ref),
_contact_force(p._contact_force),
_contact_force_old(p._contact_force_old),
_update(p._update)
{}
PenetrationLocator::PenetrationInfo::~PenetrationInfo()
{
delete _side;
}
|
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PenetrationLocator.h"
#include "ArbitraryQuadrature.h"
#include "LineSegment.h"
#include "NearestNodeLocator.h"
#include "MooseMesh.h"
#include "SubProblem.h"
#include "GeometricSearchData.h"
#include "PenetrationThread.h"
#include "Moose.h"
PenetrationLocator::PenetrationLocator(SubProblem & subproblem, GeometricSearchData & geom_search_data, MooseMesh & mesh, const unsigned int master_id, const unsigned int slave_id, Order order, NearestNodeLocator & nearest_node) :
_subproblem(subproblem),
_mesh(mesh),
_master_boundary(master_id),
_slave_boundary(slave_id),
_fe_type(order),
_nearest_node(nearest_node),
_update_location(true),
_tangential_tolerance(0.0)
{
// Preconstruct an FE object for each thread we're going to use
// This is a time savings so that the thread objects don't do this themselves multiple times
_fe.resize(libMesh::n_threads());
for(unsigned int i=0; i < libMesh::n_threads(); i++)
_fe[i] = FEBase::build(_mesh.dimension()-1, _fe_type).release();
}
PenetrationLocator::~PenetrationLocator()
{
for(unsigned int i=0; i < libMesh::n_threads(); i++)
delete _fe[i];
for (std::map<unsigned int, PenetrationInfo *>::iterator it = _penetration_info.begin(); it != _penetration_info.end(); ++it)
delete it->second;
}
void
PenetrationLocator::detectPenetration()
{
Moose::perf_log.push("detectPenetration()","Solve");
// Data structures to hold the element boundary information
std::vector< unsigned int > elem_list;
std::vector< unsigned short int > side_list;
std::vector< short int > id_list;
// Retrieve the Element Boundary data structures from the mesh
_mesh.build_side_list(elem_list, side_list, id_list);
// Grab the slave nodes we need to worry about from the NearestNodeLocator
NodeIdRange & slave_node_range = _nearest_node.slaveNodeRange();
PenetrationThread pt(_mesh,
_master_boundary,
_slave_boundary,
_penetration_info,
_update_location,
_tangential_tolerance,
_fe,
_fe_type,
_nearest_node,
_mesh.nodeToElemMap(),
elem_list,
side_list,
id_list);
Threads::parallel_reduce(slave_node_range, pt);
Moose::perf_log.pop("detectPenetration()","Solve");
}
Real
PenetrationLocator::penetrationDistance(unsigned int node_id)
{
PenetrationInfo * info = _penetration_info[node_id];
if (info)
return info->_distance;
else
return 0;
}
RealVectorValue
PenetrationLocator::penetrationNormal(unsigned int node_id)
{
std::map<unsigned int, PenetrationInfo *>::const_iterator found_it( _penetration_info.find(node_id) );
if (found_it != _penetration_info.end())
return found_it->second->_normal;
else
return RealVectorValue(0, 0, 0);
}
void
PenetrationLocator::setUpdate( bool update )
{
_update_location = update;
}
void
PenetrationLocator::setTangentialTolerance(Real tangential_tolerance)
{
_tangential_tolerance = tangential_tolerance;
}
void
PenetrationLocator::setStartingContactPoint()
{
std::map<unsigned int, PenetrationInfo *>::iterator it( _penetration_info.begin() );
const std::map<unsigned int, PenetrationInfo *>::iterator it_end( _penetration_info.end() );
for ( ; it != it_end; ++it )
{
if (it->second != NULL)
{
it->second->_starting_elem = it->second->_elem;
it->second->_starting_side_num = it->second->_side_num;
it->second->_starting_closest_point_ref = it->second->_closest_point_ref;
}
}
}
void
PenetrationLocator::saveContactForce()
{
std::map<unsigned int, PenetrationInfo *>::iterator it( _penetration_info.begin() );
const std::map<unsigned int, PenetrationInfo *>::iterator it_end( _penetration_info.end() );
for ( ; it != it_end; ++it )
{
if (it->second != NULL)
{
it->second->_contact_force_old = it->second->_contact_force;
}
}
}
PenetrationLocator::PenetrationInfo::PenetrationInfo(const Node * node, const Elem * elem, Elem * side, unsigned int side_num, RealVectorValue norm, Real norm_distance, Real tangential_distance, const Point & closest_point, const Point & closest_point_ref, const Point & closest_point_on_face_ref, std::vector<Node*> off_edge_nodes, const std::vector<std::vector<Real> > & side_phi, const std::vector<RealGradient> & dxyzdxi, const std::vector<RealGradient> & dxyzdeta, const std::vector<RealGradient> & d2xyzdxideta)
:_node(node),
_elem(elem),
_side(side),
_side_num(side_num),
_normal(norm),
_distance(norm_distance),
_tangential_distance(tangential_distance),
_closest_point(closest_point),
_closest_point_ref(closest_point_ref),
_closest_point_on_face_ref(closest_point_on_face_ref),
_off_edge_nodes(off_edge_nodes),
_side_phi(side_phi),
_dxyzdxi(dxyzdxi),
_dxyzdeta(dxyzdeta),
_d2xyzdxideta(d2xyzdxideta),
_update(true)
{}
PenetrationLocator::PenetrationInfo::PenetrationInfo(const PenetrationInfo & p) :
_node(p._node),
_elem(p._elem),
_side(p._side), // Which one now owns _side? There will be trouble if (when)
// both delete _side
_side_num(p._side_num),
_normal(p._normal),
_distance(p._distance),
_tangential_distance(p._tangential_distance),
_closest_point(p._closest_point),
_closest_point_ref(p._closest_point_ref),
_closest_point_on_face_ref(p._closest_point_on_face_ref),
_off_edge_nodes(p._off_edge_nodes),
_side_phi(p._side_phi),
_dxyzdxi(p._dxyzdxi),
_dxyzdeta(p._dxyzdeta),
_d2xyzdxideta(p._d2xyzdxideta),
_starting_elem(p._starting_elem),
_starting_side_num(p._starting_side_num),
_starting_closest_point_ref(p._starting_closest_point_ref),
_contact_force(p._contact_force),
_contact_force_old(p._contact_force_old),
_update(p._update)
{}
PenetrationLocator::PenetrationInfo::~PenetrationInfo()
{
delete _side;
}
|
Adjust Penetration code
|
Adjust Penetration code
Ticket #1470
r14948
|
C++
|
lgpl-2.1
|
wgapl/moose,permcody/moose,joshua-cogliati-inl/moose,zzyfisherman/moose,apc-llc/moose,lindsayad/moose,shanestafford/moose,wgapl/moose,roystgnr/moose,capitalaslash/moose,backmari/moose,liuwenf/moose,sapitts/moose,WilkAndy/moose,katyhuff/moose,bwspenc/moose,backmari/moose,markr622/moose,tonkmr/moose,raghavaggarwal/moose,danielru/moose,idaholab/moose,jiangwen84/moose,sapitts/moose,roystgnr/moose,andrsd/moose,friedmud/moose,jiangwen84/moose,dschwen/moose,giopastor/moose,shanestafford/moose,jhbradley/moose,backmari/moose,dschwen/moose,liuwenf/moose,joshua-cogliati-inl/moose,nuclear-wizard/moose,waxmanr/moose,cpritam/moose,Chuban/moose,Chuban/moose,WilkAndy/moose,bwspenc/moose,andrsd/moose,stimpsonsg/moose,milljm/moose,sapitts/moose,tonkmr/moose,yipenggao/moose,apc-llc/moose,YaqiWang/moose,jessecarterMOOSE/moose,tonkmr/moose,jasondhales/moose,SudiptaBiswas/moose,kasra83/moose,cpritam/moose,permcody/moose,WilkAndy/moose,laagesen/moose,raghavaggarwal/moose,friedmud/moose,harterj/moose,danielru/moose,apc-llc/moose,jhbradley/moose,friedmud/moose,xy515258/moose,capitalaslash/moose,cpritam/moose,stimpsonsg/moose,jhbradley/moose,SudiptaBiswas/moose,raghavaggarwal/moose,zzyfisherman/moose,zzyfisherman/moose,harterj/moose,lindsayad/moose,lindsayad/moose,roystgnr/moose,andrsd/moose,capitalaslash/moose,jessecarterMOOSE/moose,jinmm1992/moose,shanestafford/moose,waxmanr/moose,cpritam/moose,stimpsonsg/moose,idaholab/moose,bwspenc/moose,jinmm1992/moose,xy515258/moose,roystgnr/moose,laagesen/moose,andrsd/moose,kasra83/moose,jbair34/moose,tonkmr/moose,giopastor/moose,giopastor/moose,sapitts/moose,zzyfisherman/moose,jinmm1992/moose,milljm/moose,adamLange/moose,liuwenf/moose,shanestafford/moose,laagesen/moose,WilkAndy/moose,cpritam/moose,jasondhales/moose,dschwen/moose,zzyfisherman/moose,friedmud/moose,katyhuff/moose,YaqiWang/moose,mellis13/moose,giopastor/moose,yipenggao/moose,apc-llc/moose,dschwen/moose,xy515258/moose,milljm/moose,shanestafford/moose,joshua-cogliati-inl/moose,katyhuff/moose,andrsd/moose,wgapl/moose,bwspenc/moose,WilkAndy/moose,waxmanr/moose,mellis13/moose,jbair34/moose,roystgnr/moose,nuclear-wizard/moose,idaholab/moose,markr622/moose,jbair34/moose,jessecarterMOOSE/moose,Chuban/moose,permcody/moose,cpritam/moose,stimpsonsg/moose,markr622/moose,waxmanr/moose,markr622/moose,nuclear-wizard/moose,zzyfisherman/moose,WilkAndy/moose,adamLange/moose,jiangwen84/moose,harterj/moose,mellis13/moose,tonkmr/moose,permcody/moose,jessecarterMOOSE/moose,yipenggao/moose,SudiptaBiswas/moose,raghavaggarwal/moose,harterj/moose,lindsayad/moose,dschwen/moose,sapitts/moose,YaqiWang/moose,jasondhales/moose,wgapl/moose,SudiptaBiswas/moose,adamLange/moose,milljm/moose,danielru/moose,kasra83/moose,kasra83/moose,jinmm1992/moose,jbair34/moose,mellis13/moose,xy515258/moose,danielru/moose,joshua-cogliati-inl/moose,jessecarterMOOSE/moose,idaholab/moose,YaqiWang/moose,nuclear-wizard/moose,bwspenc/moose,yipenggao/moose,capitalaslash/moose,liuwenf/moose,roystgnr/moose,liuwenf/moose,backmari/moose,milljm/moose,liuwenf/moose,laagesen/moose,SudiptaBiswas/moose,tonkmr/moose,harterj/moose,shanestafford/moose,jiangwen84/moose,adamLange/moose,Chuban/moose,laagesen/moose,jhbradley/moose,katyhuff/moose,idaholab/moose,jasondhales/moose,roystgnr/moose,lindsayad/moose
|
af839aff43b03b51df24d6699efea291fb3cd245
|
Modules/IO/IOGDAL/src/otbGDALRPCTransformer.cxx
|
Modules/IO/IOGDAL/src/otbGDALRPCTransformer.cxx
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbGDALRPCTransformer.h"
#include <assert.h>
#include "cpl_string.h"
#include "otbDEMHandler.h"
namespace otb
{
GDALRPCTransformer::GDALRPCTransformer(double LineOffset, double SampleOffset, double LatOffset, double LonOffset, double HeightOffset,
double LineScale, double SampleScale, double LatScale, double LonScale, double HeightScale,
const double (&LineNum)[20], const double (&LineDen)[20], const double (&SampleNum)[20], const double (&SampleDen)[20])
{
// Offsets
this->m_GDALRPCInfo.dfLINE_OFF = LineOffset;
this->m_GDALRPCInfo.dfSAMP_OFF = SampleOffset;
this->m_GDALRPCInfo.dfLAT_OFF = LatOffset;
this->m_GDALRPCInfo.dfLONG_OFF = LonOffset;
this->m_GDALRPCInfo.dfHEIGHT_OFF = HeightOffset;
// Scales
this->m_GDALRPCInfo.dfLINE_SCALE = LineScale;
this->m_GDALRPCInfo.dfSAMP_SCALE = SampleScale;
this->m_GDALRPCInfo.dfLAT_SCALE = LatScale;
this->m_GDALRPCInfo.dfLONG_SCALE = LonScale;
this->m_GDALRPCInfo.dfHEIGHT_SCALE = HeightScale;
// Coefficients
std::copy_n(LineNum, 20, this->m_GDALRPCInfo.adfLINE_NUM_COEFF);
std::copy_n(LineDen, 20, this->m_GDALRPCInfo.adfLINE_DEN_COEFF);
std::copy_n(SampleNum, 20, this->m_GDALRPCInfo.adfSAMP_NUM_COEFF);
std::copy_n(SampleDen, 20, this->m_GDALRPCInfo.adfSAMP_DEN_COEFF);
auto & demHandler = otb::DEMHandler::GetInstance();
if (demHandler.GetDEMCount() > 0)
{
this->SetOption("RPC_DEM", demHandler.DEM_DATASET_PATH);
this->SetOption("RPC_DEM_MISSING_VALUE", std::to_string(demHandler.GetDefaultHeightAboveEllipsoid()));
}
}
GDALRPCTransformer::~GDALRPCTransformer()
{
if(m_TransformArg != nullptr)
GDALDestroyTransformer(m_TransformArg);
CSLDestroy(m_Options);
}
void GDALRPCTransformer::SetOption(const std::string& Name, const std::string& Value)
{
this->m_Options = CSLSetNameValue(m_Options, Name.c_str(), Value.c_str());
this->m_Modified = true;
}
void GDALRPCTransformer::SetPixErrThreshold(double PixErrThreshold)
{
this->m_PixErrThreshold = PixErrThreshold;
this->m_Modified = true;
}
void GDALRPCTransformer::Update()
{
if(m_TransformArg != nullptr)
GDALDestroyTransformer(m_TransformArg);
this->m_TransformArg = GDALCreateRPCTransformer(&this->m_GDALRPCInfo, false, this->m_PixErrThreshold, this->m_Options);
this->m_Modified = false;
}
bool GDALRPCTransformer::ForwardTransform(double* x, double* y, double* z, int nPointCount)
{
assert(x);
assert(y);
assert(z);
if (this->m_Modified)
this->Update();
std::vector<int> success(nPointCount);
GDALRPCTransform(this->m_TransformArg, false, nPointCount, x, y, z, success.data());
bool finalSuccess = std::all_of(success.begin(), success.end(), [](int i){return i;});
return finalSuccess;
}
GDALRPCTransformer::PointType GDALRPCTransformer::ForwardTransform(GDALRPCTransformer::PointType p)
{
if (m_Modified)
this->Update();
int success;
GDALRPCTransform(this->m_TransformArg, false, 1, &p[0], &p[1], &p[2], &success);
if (!success)
throw std::runtime_error("GDALRPCTransform was not able to process the ForwardTransform.");
return p;
}
bool GDALRPCTransformer::InverseTransform(double* x, double* y, double* z, int nPointCount)
{
assert(x);
assert(y);
assert(z);
if (this->m_Modified)
this->Update();
std::vector<int> success(nPointCount);
GDALRPCTransform(this->m_TransformArg, true, nPointCount, x, y, z, success.data());
bool finalSuccess = std::all_of(success.begin(), success.end(), [](int i){return i;});
return finalSuccess;
}
GDALRPCTransformer::PointType GDALRPCTransformer::InverseTransform(GDALRPCTransformer::PointType p)
{
if (m_Modified)
this->Update();
int success;
GDALRPCTransform(this->m_TransformArg, true, 1, &p[0], &p[1], &p[2], &success);
if (!success)
throw std::runtime_error("GDALRPCTransform was not able to process the InverseTransform.");
return p;
}
}
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbGDALRPCTransformer.h"
#include <assert.h>
#include "cpl_string.h"
#include "otbDEMHandler.h"
namespace otb
{
GDALRPCTransformer::GDALRPCTransformer(double LineOffset, double SampleOffset, double LatOffset, double LonOffset, double HeightOffset,
double LineScale, double SampleScale, double LatScale, double LonScale, double HeightScale,
const double (&LineNum)[20], const double (&LineDen)[20], const double (&SampleNum)[20], const double (&SampleDen)[20])
{
// Offsets
this->m_GDALRPCInfo.dfLINE_OFF = LineOffset;
this->m_GDALRPCInfo.dfSAMP_OFF = SampleOffset;
this->m_GDALRPCInfo.dfLAT_OFF = LatOffset;
this->m_GDALRPCInfo.dfLONG_OFF = LonOffset;
this->m_GDALRPCInfo.dfHEIGHT_OFF = HeightOffset;
// Scales
this->m_GDALRPCInfo.dfLINE_SCALE = LineScale;
this->m_GDALRPCInfo.dfSAMP_SCALE = SampleScale;
this->m_GDALRPCInfo.dfLAT_SCALE = LatScale;
this->m_GDALRPCInfo.dfLONG_SCALE = LonScale;
this->m_GDALRPCInfo.dfHEIGHT_SCALE = HeightScale;
// Coefficients
std::copy_n(LineNum, 20, this->m_GDALRPCInfo.adfLINE_NUM_COEFF);
std::copy_n(LineDen, 20, this->m_GDALRPCInfo.adfLINE_DEN_COEFF);
std::copy_n(SampleNum, 20, this->m_GDALRPCInfo.adfSAMP_NUM_COEFF);
std::copy_n(SampleDen, 20, this->m_GDALRPCInfo.adfSAMP_DEN_COEFF);
auto & demHandler = otb::DEMHandler::GetInstance();
if (demHandler.GetDEMCount() > 0)
{
this->SetOption("RPC_DEM", demHandler.DEM_DATASET_PATH);
this->SetOption("RPC_DEM_MISSING_VALUE", std::to_string(demHandler.GetDefaultHeightAboveEllipsoid()));
}
else
{
this->SetOption("RPC_HEIGHT", std::to_string(demHandler.GetDefaultHeightAboveEllipsoid()));
}
}
GDALRPCTransformer::~GDALRPCTransformer()
{
if(m_TransformArg != nullptr)
GDALDestroyTransformer(m_TransformArg);
CSLDestroy(m_Options);
}
void GDALRPCTransformer::SetOption(const std::string& Name, const std::string& Value)
{
this->m_Options = CSLSetNameValue(m_Options, Name.c_str(), Value.c_str());
this->m_Modified = true;
}
void GDALRPCTransformer::SetPixErrThreshold(double PixErrThreshold)
{
this->m_PixErrThreshold = PixErrThreshold;
this->m_Modified = true;
}
void GDALRPCTransformer::Update()
{
if(m_TransformArg != nullptr)
GDALDestroyTransformer(m_TransformArg);
this->m_TransformArg = GDALCreateRPCTransformer(&this->m_GDALRPCInfo, false, this->m_PixErrThreshold, this->m_Options);
this->m_Modified = false;
}
bool GDALRPCTransformer::ForwardTransform(double* x, double* y, double* z, int nPointCount)
{
assert(x);
assert(y);
assert(z);
if (this->m_Modified)
this->Update();
std::vector<int> success(nPointCount);
GDALRPCTransform(this->m_TransformArg, false, nPointCount, x, y, z, success.data());
bool finalSuccess = std::all_of(success.begin(), success.end(), [](int i){return i;});
return finalSuccess;
}
GDALRPCTransformer::PointType GDALRPCTransformer::ForwardTransform(GDALRPCTransformer::PointType p)
{
if (m_Modified)
this->Update();
int success;
GDALRPCTransform(this->m_TransformArg, false, 1, &p[0], &p[1], &p[2], &success);
if (!success)
throw std::runtime_error("GDALRPCTransform was not able to process the ForwardTransform.");
return p;
}
bool GDALRPCTransformer::InverseTransform(double* x, double* y, double* z, int nPointCount)
{
assert(x);
assert(y);
assert(z);
if (this->m_Modified)
this->Update();
std::vector<int> success(nPointCount);
GDALRPCTransform(this->m_TransformArg, true, nPointCount, x, y, z, success.data());
bool finalSuccess = std::all_of(success.begin(), success.end(), [](int i){return i;});
return finalSuccess;
}
GDALRPCTransformer::PointType GDALRPCTransformer::InverseTransform(GDALRPCTransformer::PointType p)
{
if (m_Modified)
this->Update();
int success;
GDALRPCTransform(this->m_TransformArg, true, 1, &p[0], &p[1], &p[2], &success);
if (!success)
throw std::runtime_error("GDALRPCTransform was not able to process the InverseTransform.");
return p;
}
}
|
use default height above ellipsoid when no DEM is set in GDALRPCTransformer
|
BUG: use default height above ellipsoid when no DEM is set in GDALRPCTransformer
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
48f439697a173e9e282ed59b0a71f63c039b6578
|
framework/src/utils/InputParameterWarehouse.C
|
framework/src/utils/InputParameterWarehouse.C
|
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// MOOSE includes
#include "InputParameterWarehouse.h"
#include "InputParameters.h"
InputParameterWarehouse::InputParameterWarehouse()
: _input_parameters(libMesh::n_threads()), _controllable_items(libMesh::n_threads())
{
}
InputParameters &
InputParameterWarehouse::addInputParameters(const std::string & name,
const InputParameters & parameters,
THREAD_ID tid /* =0 */)
{
// Error if the name contains "::"
if (name.find("::") != std::string::npos)
mooseError("The object name may not contain '::' in the name: ", name);
// Create the actual InputParameters object that will be reference by the objects
std::shared_ptr<InputParameters> ptr = std::make_shared<InputParameters>(parameters);
auto base = ptr->get<std::string>("_moose_base");
// The object name defined by the base class name, this method of storing is used for
// determining the uniqueness of the name
MooseObjectName unique_name(base, name, "::");
// Check that the Parameters do not already exist. We allow duplicate unique_names for
// MooseVariableBase objects because we require duplication of the variable for reference and
// displaced problems. We must also have std::pair(reference_var, reference_params) AND
// std::pair(displaced_var, displaced_params) elements because the two vars will have different
// values for _sys. It's a good thing we are using a multi-map as our underlying storage.
// We also allow duplicate unique_names for Action objects because it is allowed to have
// multiple [Materials] input blocks each of which can add an action but all of these actions
// will have the same unique name.
if (_input_parameters[tid].find(unique_name) != _input_parameters[tid].end() &&
base != "MooseVariableBase" && base != "Action")
mooseError("A '",
unique_name.tag(),
"' object already exists with the name '",
unique_name.name(),
"'.\n");
// Store the parameters according to the base name
_input_parameters[tid].insert(
std::pair<MooseObjectName, std::shared_ptr<InputParameters>>(unique_name, ptr));
// Build a list of object names
std::vector<MooseObjectName> object_names;
object_names.push_back(unique_name);
// Store the object according to the control tags
if (ptr->isParamValid("control_tags"))
{
const std::vector<std::string> & tags = ptr->get<std::vector<std::string>>("control_tags");
for (const auto & tag : tags)
{
if (!tag.empty())
{
auto short_name = MooseUtils::shortName(name);
_input_parameters[tid].insert(std::pair<MooseObjectName, std::shared_ptr<InputParameters>>(
MooseObjectName(tag, short_name), ptr));
object_names.emplace_back(tag, short_name);
}
}
}
// Store controllable parameters using all possible names
for (libMesh::Parameters::iterator map_iter = ptr->begin(); map_iter != ptr->end(); ++map_iter)
{
const std::string & pname = map_iter->first;
libMesh::Parameters::Value * value = MooseUtils::get(map_iter->second);
if (ptr->isControllable(pname))
for (const auto & object_name : object_names)
{
MooseObjectParameterName param_name(object_name, pname);
_controllable_items[tid].emplace_back(std::make_shared<ControllableItem>(
param_name, value, ptr->getControllableExecuteOnTypes(pname)));
}
}
// Set the name and tid parameters, and unique_name
std::stringstream oss;
oss << unique_name;
ptr->addPrivateParam<std::string>("_unique_name", oss.str());
ptr->addPrivateParam<std::string>("_object_name", name);
ptr->addPrivateParam<THREAD_ID>("_tid", tid);
// no more copies allowed
ptr->allowCopy(false);
// Return a reference to the InputParameters object
return *ptr;
}
void
InputParameterWarehouse::removeInputParameters(const MooseObject & moose_object, THREAD_ID tid)
{
auto moose_object_name_string = moose_object.parameters().get<std::string>("_unique_name");
MooseObjectName moose_object_name(moose_object_name_string);
_input_parameters[tid].erase(moose_object_name);
}
const InputParameters &
InputParameterWarehouse::getInputParametersObject(const std::string & name, THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(name), tid);
}
const InputParameters &
InputParameterWarehouse::getInputParametersObject(const std::string & tag,
const std::string & name,
THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(tag, name), tid);
}
const InputParameters &
InputParameterWarehouse::getInputParametersObject(const MooseObjectName & object_name,
THREAD_ID tid) const
{
return getInputParameters(object_name, tid);
}
InputParameters &
InputParameterWarehouse::getInputParameters(const std::string & name, THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(name), tid);
}
InputParameters &
InputParameterWarehouse::getInputParameters(const std::string & tag,
const std::string & name,
THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(tag, name), tid);
}
InputParameters &
InputParameterWarehouse::getInputParameters(const MooseObjectName & object_name,
THREAD_ID tid) const
{
// Locate the InputParameters object and error if it was not located
const auto iter = _input_parameters[tid].find(object_name);
if (iter == _input_parameters[tid].end())
mooseError("Unknown InputParameters object ", object_name);
// Return a reference to the parameter
return *(iter->second.get());
}
const std::multimap<MooseObjectName, std::shared_ptr<InputParameters>> &
InputParameterWarehouse::getInputParameters(THREAD_ID tid) const
{
return _input_parameters[tid];
}
void
InputParameterWarehouse::addControllableParameterConnection(
const MooseObjectParameterName & primary,
const MooseObjectParameterName & secondary,
bool error_on_empty /*=true*/)
{
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
{
std::vector<ControllableItem *> primaries = getControllableItems(primary, tid);
if (primaries.empty() && error_on_empty && tid == 0) // some objects only exist on tid 0
mooseError("Unable to locate primary parameter with name ", primary);
else if (primaries.empty())
return;
std::vector<ControllableItem *> secondaries = getControllableItems(secondary, tid);
if (secondaries.empty() && error_on_empty && tid == 0) // some objects only exist on tid 0
mooseError("Unable to locate secondary parameter with name ", secondary);
else if (secondaries.empty())
return;
for (auto primary_ptr : primaries)
for (auto secondary_ptr : secondaries)
if (primary_ptr != secondary_ptr)
primary_ptr->connect(secondary_ptr);
}
}
void
InputParameterWarehouse::addControllableObjectAlias(const MooseObjectName & alias,
const MooseObjectName & secondary)
{
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
{
std::vector<ControllableItem *> secondaries =
getControllableItems(MooseObjectParameterName(secondary, "*"), tid);
for (auto secondary_ptr : secondaries)
{
MooseObjectParameterName alias_param(alias, secondary_ptr->name().parameter());
MooseObjectParameterName secondary_param(secondary, secondary_ptr->name().parameter());
addControllableParameterAlias(alias_param, secondary_param);
}
}
}
void
InputParameterWarehouse::addControllableParameterAlias(const MooseObjectParameterName & alias,
const MooseObjectParameterName & secondary)
{
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
{
std::vector<ControllableItem *> secondaries = getControllableItems(secondary, tid);
if (secondaries.empty() && tid == 0) // some objects only exist on tid 0
mooseError("Unable to locate secondary parameter with name ", secondary);
for (auto secondary_ptr : secondaries)
_controllable_items[tid].emplace_back(
std::make_unique<ControllableAlias>(alias, secondary_ptr));
}
}
std::vector<ControllableItem *>
InputParameterWarehouse::getControllableItems(const MooseObjectParameterName & input,
THREAD_ID tid /*=0*/) const
{
std::vector<ControllableItem *> output;
for (auto & ptr : _controllable_items[tid])
if (ptr->name() == input)
output.push_back(ptr.get());
return output;
}
ControllableParameter
InputParameterWarehouse::getControllableParameter(const MooseObjectParameterName & input) const
{
ControllableParameter cparam;
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
for (auto it = _controllable_items[tid].begin(); it != _controllable_items[tid].end(); ++it)
if ((*it)->name() == input)
cparam.add(it->get());
return cparam;
}
std::string
InputParameterWarehouse::dumpChangedControls(bool reset_changed) const
{
std::stringstream oss;
oss << std::left;
for (const auto & item : _controllable_items[0])
if (item->isChanged())
{
oss << item->dump(4);
if (reset_changed)
item->resetChanged();
}
return oss.str();
}
std::vector<MooseObjectParameterName>
InputParameterWarehouse::getControllableParameterNames(const MooseObjectParameterName & input) const
{
std::vector<MooseObjectParameterName> names;
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
for (auto it = _controllable_items[tid].begin(); it != _controllable_items[tid].end(); ++it)
if ((*it)->name() == input)
names.push_back((*it)->name());
return names;
}
|
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// MOOSE includes
#include "InputParameterWarehouse.h"
#include "InputParameters.h"
InputParameterWarehouse::InputParameterWarehouse()
: _input_parameters(libMesh::n_threads()), _controllable_items(libMesh::n_threads())
{
}
InputParameters &
InputParameterWarehouse::addInputParameters(const std::string & name,
const InputParameters & parameters,
THREAD_ID tid /* =0 */)
{
// Error if the name contains "::"
if (name.find("::") != std::string::npos)
mooseError("The object name may not contain '::' in the name: ", name);
// Create the actual InputParameters object that will be reference by the objects
std::shared_ptr<InputParameters> ptr = std::make_shared<InputParameters>(parameters);
auto base = ptr->get<std::string>("_moose_base");
// The object name defined by the base class name, this method of storing is used for
// determining the uniqueness of the name
MooseObjectName unique_name(base, name, "::");
// Check that the Parameters do not already exist. We allow duplicate unique_names for
// MooseVariableBase objects because we require duplication of the variable for reference and
// displaced problems. We must also have std::pair(reference_var, reference_params) AND
// std::pair(displaced_var, displaced_params) elements because the two vars will have different
// values for _sys. It's a good thing we are using a multi-map as our underlying storage.
// We also allow duplicate unique_names for Action objects because it is allowed to have
// multiple [Materials] input blocks each of which can add an action but all of these actions
// will have the same unique name.
if (_input_parameters[tid].find(unique_name) != _input_parameters[tid].end() &&
base != "MooseVariableBase" && base != "Action")
mooseError("A '",
unique_name.tag(),
"' object already exists with the name '",
unique_name.name(),
"'.\n");
// Store the parameters according to the base name
_input_parameters[tid].insert(
std::pair<MooseObjectName, std::shared_ptr<InputParameters>>(unique_name, ptr));
// Build a list of object names
std::vector<MooseObjectName> object_names;
object_names.push_back(unique_name);
// Store the object according to the control tags
if (ptr->isParamValid("control_tags"))
{
const std::vector<std::string> & tags = ptr->get<std::vector<std::string>>("control_tags");
for (const auto & tag : tags)
{
if (!tag.empty())
{
auto short_name = MooseUtils::shortName(name);
_input_parameters[tid].insert(std::pair<MooseObjectName, std::shared_ptr<InputParameters>>(
MooseObjectName(tag, short_name), ptr));
object_names.emplace_back(tag, short_name);
}
}
}
// Store controllable parameters using all possible names
for (libMesh::Parameters::iterator map_iter = ptr->begin(); map_iter != ptr->end(); ++map_iter)
{
const std::string & pname = map_iter->first;
libMesh::Parameters::Value * value = MooseUtils::get(map_iter->second);
if (ptr->isControllable(pname))
for (const auto & object_name : object_names)
{
MooseObjectParameterName param_name(object_name, pname);
_controllable_items[tid].emplace_back(std::make_shared<ControllableItem>(
param_name, value, ptr->getControllableExecuteOnTypes(pname)));
}
}
// Set the name and tid parameters, and unique_name
std::stringstream oss;
oss << unique_name;
ptr->addPrivateParam<std::string>("_unique_name", oss.str());
ptr->addPrivateParam<std::string>("_object_name", name);
ptr->addPrivateParam<THREAD_ID>("_tid", tid);
// no more copies allowed
ptr->allowCopy(false);
// Return a reference to the InputParameters object
return *ptr;
}
void
InputParameterWarehouse::removeInputParameters(const MooseObject & moose_object, THREAD_ID tid)
{
auto moose_object_name_string = moose_object.parameters().get<std::string>("_unique_name");
MooseObjectName moose_object_name(moose_object_name_string);
_input_parameters[tid].erase(moose_object_name);
}
const InputParameters &
InputParameterWarehouse::getInputParametersObject(const std::string & name, THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(name), tid);
}
const InputParameters &
InputParameterWarehouse::getInputParametersObject(const std::string & tag,
const std::string & name,
THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(tag, name), tid);
}
const InputParameters &
InputParameterWarehouse::getInputParametersObject(const MooseObjectName & object_name,
THREAD_ID tid) const
{
return getInputParameters(object_name, tid);
}
InputParameters &
InputParameterWarehouse::getInputParameters(const std::string & name, THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(name), tid);
}
InputParameters &
InputParameterWarehouse::getInputParameters(const std::string & tag,
const std::string & name,
THREAD_ID tid) const
{
return getInputParameters(MooseObjectName(tag, name), tid);
}
InputParameters &
InputParameterWarehouse::getInputParameters(const MooseObjectName & object_name,
THREAD_ID tid) const
{
// Locate the InputParameters object and error if it was not located
const auto iter = _input_parameters[tid].find(object_name);
if (iter == _input_parameters[tid].end())
mooseError("Unknown InputParameters object ", object_name);
// Return a reference to the parameter
return *(iter->second.get());
}
const std::multimap<MooseObjectName, std::shared_ptr<InputParameters>> &
InputParameterWarehouse::getInputParameters(THREAD_ID tid) const
{
return _input_parameters[tid];
}
void
InputParameterWarehouse::addControllableParameterConnection(
const MooseObjectParameterName & primary,
const MooseObjectParameterName & secondary,
bool error_on_empty /*=true*/)
{
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
{
std::vector<ControllableItem *> primaries = getControllableItems(primary, tid);
if (primaries.empty() && error_on_empty && tid == 0) // some objects only exist on tid 0
mooseError("Unable to locate primary parameter with name ", primary);
else if (primaries.empty())
{
if (tid == 0)
return;
else
// try to connect non-threaded primary control to secondary controls of all threads
primaries = getControllableItems(primary, 0);
}
std::vector<ControllableItem *> secondaries = getControllableItems(secondary, tid);
if (secondaries.empty() && error_on_empty && tid == 0) // some objects only exist on tid 0
mooseError("Unable to locate secondary parameter with name ", secondary);
else if (secondaries.empty())
return;
for (auto primary_ptr : primaries)
for (auto secondary_ptr : secondaries)
if (primary_ptr != secondary_ptr)
primary_ptr->connect(secondary_ptr);
}
}
void
InputParameterWarehouse::addControllableObjectAlias(const MooseObjectName & alias,
const MooseObjectName & secondary)
{
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
{
std::vector<ControllableItem *> secondaries =
getControllableItems(MooseObjectParameterName(secondary, "*"), tid);
for (auto secondary_ptr : secondaries)
{
MooseObjectParameterName alias_param(alias, secondary_ptr->name().parameter());
MooseObjectParameterName secondary_param(secondary, secondary_ptr->name().parameter());
addControllableParameterAlias(alias_param, secondary_param);
}
}
}
void
InputParameterWarehouse::addControllableParameterAlias(const MooseObjectParameterName & alias,
const MooseObjectParameterName & secondary)
{
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
{
std::vector<ControllableItem *> secondaries = getControllableItems(secondary, tid);
if (secondaries.empty() && tid == 0) // some objects only exist on tid 0
mooseError("Unable to locate secondary parameter with name ", secondary);
for (auto secondary_ptr : secondaries)
_controllable_items[tid].emplace_back(
std::make_unique<ControllableAlias>(alias, secondary_ptr));
}
}
std::vector<ControllableItem *>
InputParameterWarehouse::getControllableItems(const MooseObjectParameterName & input,
THREAD_ID tid /*=0*/) const
{
std::vector<ControllableItem *> output;
for (auto & ptr : _controllable_items[tid])
if (ptr->name() == input)
output.push_back(ptr.get());
return output;
}
ControllableParameter
InputParameterWarehouse::getControllableParameter(const MooseObjectParameterName & input) const
{
ControllableParameter cparam;
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
for (auto it = _controllable_items[tid].begin(); it != _controllable_items[tid].end(); ++it)
if ((*it)->name() == input)
cparam.add(it->get());
return cparam;
}
std::string
InputParameterWarehouse::dumpChangedControls(bool reset_changed) const
{
std::stringstream oss;
oss << std::left;
for (const auto & item : _controllable_items[0])
if (item->isChanged())
{
oss << item->dump(4);
if (reset_changed)
item->resetChanged();
}
return oss.str();
}
std::vector<MooseObjectParameterName>
InputParameterWarehouse::getControllableParameterNames(const MooseObjectParameterName & input) const
{
std::vector<MooseObjectParameterName> names;
for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
for (auto it = _controllable_items[tid].begin(); it != _controllable_items[tid].end(); ++it)
if ((*it)->name() == input)
names.push_back((*it)->name());
return names;
}
|
handle the connected controls with multithreading #22068
|
handle the connected controls with multithreading #22068
|
C++
|
lgpl-2.1
|
sapitts/moose,andrsd/moose,andrsd/moose,sapitts/moose,sapitts/moose,laagesen/moose,sapitts/moose,andrsd/moose,andrsd/moose,idaholab/moose,sapitts/moose,laagesen/moose,andrsd/moose,idaholab/moose,idaholab/moose,laagesen/moose,laagesen/moose,idaholab/moose,laagesen/moose,idaholab/moose
|
c9f2948b15d20242e1c53fa96428d709c32d490f
|
Include/xStl/data/graph.inl
|
Include/xStl/data/graph.inl
|
/*
* Copyright (c) 2008-2016, Integrity Project Ltd. 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 Integrity Project 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
*/
/*
* graph.inl
*
* Implementation code of the cGraph class.
*
*/
template <class T, class S>
cGraph<T,S>::cGraph(uint numberOfPossibleColors) :
m_nodes(),
m_numberOfPossibleColors(numberOfPossibleColors)
{
}
template <class T, class S>
cGraph<T,S>::~cGraph()
{
}
template <class T, class S>
cGraph<T,S>::cGraph(const cGraph<T,S> &other)
{
m_nodes = other.getNodes();
}
template <class T, class S>
void cGraph<T,S>::addNode(const T& id, const S& value)
{
/* Check if the node exists already (if so, don't do anything) */
if (isNodeExists(id)) {
return;
}
GraphNode<T,S> tmp(id, value, m_numberOfPossibleColors); // The new node which will be entered.
m_nodes.append(tmp);
}
template <class T, class S>
bool cGraph<T,S>::isConnected(const T& id1, const T& id2)
{
typename cList<GraphNode<T,S> >::iterator nodesIterator(m_nodes.begin());
for (; nodesIterator != m_nodes.end(); ++nodesIterator)
{
GraphNode<T,S>* graphNode = *nodesIterator;
if (id1 == graphNode.getId())
{
return graphNode.isNeighbor(id2);
}
}
return false;
}
template <class T, class S>
void cGraph<T,S>::connectNodes(const T& id1, const T& id2, bool dup)
{
typename cList<GraphNode<T,S> >::iterator current_node(m_nodes.begin());
GraphNode<T,S>* graphNode1 = NULL;
GraphNode<T,S>* graphNode2 = NULL;
/* Find the graph nodes that correspond to the ids */
for (; current_node != m_nodes.end(); ++current_node)
{
GraphNode<T,S>& graphNode = *current_node;
if (graphNode.getId() == id1)
{
graphNode1 = &graphNode;
}
else if (graphNode.getId() == id2)
{
graphNode2 = &graphNode;
}
}
/* If found, add the edge */
if ((graphNode1 != NULL) && (graphNode2 != NULL))
{
if (dup)
{
graphNode1->addEdge(graphNode2);
graphNode2->addEdge(graphNode1);
}
else
{
graphNode1->addEdgeNoDup(graphNode2);
graphNode2->addEdgeNoDup(graphNode1);
}
}
}
template <class T, class S>
bool cGraph<T,S>::isEmpty() const
{
return m_nodes.isEmpty();
}
template <class T, class S>
uint cGraph<T,S>::getNumberOfNodes() const
{
return m_nodes.length();
}
template <class T, class S>
bool cGraph<T,S>::isNodeExists(const T& id) const
{
typename cList<GraphNode<T,S> >::iterator nodesIterator(m_nodes.begin());
for (; nodesIterator != m_nodes.end(); ++nodesIterator)
{
GraphNode<T,S>& graphNode = *nodesIterator;
if (graphNode.getId() == id)
{
return true;
}
}
return false;
}
template <class T, class S>
void cGraph<T,S>::makeClique(cList<T> ids)
{
typename cList<T>::iterator idsIterator1(ids.begin());
typename cList<T>::iterator idsIterator2(ids.begin());
/* Add edges between every two nodes in the id list */
for (; idsIterator1 != ids.end(); ++idsIterator1)
{
T& id1 = *idsIterator1;
idsIterator2 = ids.begin();
for (; idsIterator2 != ids.end(); ++idsIterator2)
{
T& id2 = *idsIterator2;
connectNodes(id1, id2);
}
}
}
template <class T, class S>
GraphNode<T,S>* cGraph<T,S>::getNode(const T& id) const
{
typename cList<GraphNode<T,S> >::iterator nodesIterator(m_nodes.begin());
for (; nodesIterator != m_nodes.end(); ++nodesIterator)
{
GraphNode<T,S>& graphNode = *nodesIterator;
if (graphNode.getId() == id)
{
return &(graphNode);
}
}
return NULL;
}
template <class T, class S>
cList<GraphNode<T,S> >& cGraph<T,S>::getNodes()
{
return m_nodes;
}
static bool isSetInOnePlace(cSetArray bitArray)
{
bool found = false;
for (uint i = 0 ; i < bitArray.getLength() ; ++i)
{
if (bitArray.isSet(i) && found)
return false;
else if (bitArray.isSet(i))
found = true;
}
return found;
}
|
/*
* Copyright (c) 2008-2016, Integrity Project Ltd. 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 Integrity Project 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
*/
/*
* graph.inl
*
* Implementation code of the cGraph class.
*
*/
template <class T, class S>
cGraph<T,S>::cGraph(uint numberOfPossibleColors) :
m_nodes(),
m_numberOfPossibleColors(numberOfPossibleColors)
{
}
template <class T, class S>
cGraph<T,S>::~cGraph()
{
}
template <class T, class S>
cGraph<T,S>::cGraph(const cGraph<T,S> &other)
{
m_nodes = other.getNodes();
}
template <class T, class S>
void cGraph<T,S>::addNode(const T& id, const S& value)
{
/* Check if the node exists already (if so, don't do anything) */
if (isNodeExists(id)) {
return;
}
GraphNode<T,S> tmp(id, value, m_numberOfPossibleColors); // The new node which will be entered.
m_nodes.append(tmp);
}
template <class T, class S>
bool cGraph<T,S>::isConnected(const T& id1, const T& id2)
{
typename cList<GraphNode<T,S> >::iterator nodesIterator(m_nodes.begin());
for (; nodesIterator != m_nodes.end(); ++nodesIterator)
{
GraphNode<T,S>& graphNode = *nodesIterator;
if (id1 == graphNode.getId())
{
return graphNode.isNeighbor(id2);
}
}
return false;
}
template <class T, class S>
void cGraph<T,S>::connectNodes(const T& id1, const T& id2, bool dup)
{
typename cList<GraphNode<T,S> >::iterator current_node(m_nodes.begin());
GraphNode<T,S>* graphNode1 = NULL;
GraphNode<T,S>* graphNode2 = NULL;
/* Find the graph nodes that correspond to the ids */
for (; current_node != m_nodes.end(); ++current_node)
{
GraphNode<T,S>& graphNode = *current_node;
if (graphNode.getId() == id1)
{
graphNode1 = &graphNode;
}
else if (graphNode.getId() == id2)
{
graphNode2 = &graphNode;
}
}
/* If found, add the edge */
if ((graphNode1 != NULL) && (graphNode2 != NULL))
{
if (dup)
{
graphNode1->addEdge(graphNode2);
graphNode2->addEdge(graphNode1);
}
else
{
graphNode1->addEdgeNoDup(graphNode2);
graphNode2->addEdgeNoDup(graphNode1);
}
}
}
template <class T, class S>
bool cGraph<T,S>::isEmpty() const
{
return m_nodes.isEmpty();
}
template <class T, class S>
uint cGraph<T,S>::getNumberOfNodes() const
{
return m_nodes.length();
}
template <class T, class S>
bool cGraph<T,S>::isNodeExists(const T& id) const
{
typename cList<GraphNode<T,S> >::iterator nodesIterator(m_nodes.begin());
for (; nodesIterator != m_nodes.end(); ++nodesIterator)
{
GraphNode<T,S>& graphNode = *nodesIterator;
if (graphNode.getId() == id)
{
return true;
}
}
return false;
}
template <class T, class S>
void cGraph<T,S>::makeClique(cList<T> ids)
{
typename cList<T>::iterator idsIterator1(ids.begin());
typename cList<T>::iterator idsIterator2(ids.begin());
/* Add edges between every two nodes in the id list */
for (; idsIterator1 != ids.end(); ++idsIterator1)
{
T& id1 = *idsIterator1;
idsIterator2 = ids.begin();
for (; idsIterator2 != ids.end(); ++idsIterator2)
{
T& id2 = *idsIterator2;
connectNodes(id1, id2);
}
}
}
template <class T, class S>
GraphNode<T,S>* cGraph<T,S>::getNode(const T& id) const
{
typename cList<GraphNode<T,S> >::iterator nodesIterator(m_nodes.begin());
for (; nodesIterator != m_nodes.end(); ++nodesIterator)
{
GraphNode<T,S>& graphNode = *nodesIterator;
if (graphNode.getId() == id)
{
return &(graphNode);
}
}
return NULL;
}
template <class T, class S>
cList<GraphNode<T,S> >& cGraph<T,S>::getNodes()
{
return m_nodes;
}
static bool isSetInOnePlace(cSetArray bitArray)
{
bool found = false;
for (uint i = 0 ; i < bitArray.getLength() ; ++i)
{
if (bitArray.isSet(i) && found)
return false;
else if (bitArray.isSet(i))
found = true;
}
return found;
}
|
Fix "cGraph::isConnected()"
|
data: Fix "cGraph::isConnected()"
LLVM compiler, identify a bug, we should have use reference and not a pointer.
Fixes: 71bb728 ("Initialize version 1.0")
Signed-off-by: Elad Raz <[email protected]>
|
C++
|
bsd-3-clause
|
eladraz/xStl,eladraz/xStl,eladraz/xStl
|
02ce7e7d3ad36bda3fbe9327a69b54df1a6dac4c
|
variants/platforms/aerial_v4/pwm_platform.cpp
|
variants/platforms/aerial_v4/pwm_platform.cpp
|
#include "variant/pwm_platform.hpp"
#include "hal.h"
// TODO(yoos): v4.0 will switch these around so we can share a 50 Hz timer
// channel between servos and status LEDs.
static const PWMConfig PWMD1_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
static const PWMConfig PWMD3_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_DISABLED, NULL}, // RSSI
{PWM_OUTPUT_ACTIVE_HIGH, NULL}, // Status R
{PWM_OUTPUT_ACTIVE_HIGH, NULL}, // Status G
{PWM_OUTPUT_ACTIVE_HIGH, NULL} // Status B
}, // Channel configurations
0,0 // HW dependent
};
static const PWMConfig PWMD4_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
PWMPlatform::PWMPlatform() {
// TIM1
pwmStart(&PWMD1, &PWMD1_CONFIG);
palSetPadMode(GPIOA, 8, PAL_MODE_ALTERNATE(1));
palSetPadMode(GPIOA, 9, PAL_MODE_ALTERNATE(1));
palSetPadMode(GPIOA, 10, PAL_MODE_ALTERNATE(1));
palSetPadMode(GPIOA, 11, PAL_MODE_ALTERNATE(1));
// TIM3
pwmStart(&PWMD3, &PWMD3_CONFIG);
palSetPadMode(GPIOA, 6, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOA, 7, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 0, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 1, PAL_MODE_ALTERNATE(2));
// TIM4
pwmStart(&PWMD4, &PWMD4_CONFIG);
palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 8, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 9, PAL_MODE_ALTERNATE(2));
}
void PWMPlatform::set(std::uint8_t ch, float dc) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD1, dc * 10000.0f);
pwmEnableChannel(&PWMD1, ch, width);
}
|
#include "variant/pwm_platform.hpp"
#include "hal.h"
// TODO(yoos): v4.0 will switch these around so we can share a 50 Hz timer
// channel between servos and status LEDs.
static const PWMConfig PWMD1_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
static const PWMConfig PWMD3_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_DISABLED, NULL}, // RSSI
{PWM_OUTPUT_ACTIVE_HIGH, NULL}, // Status R
{PWM_OUTPUT_ACTIVE_HIGH, NULL}, // Status G
{PWM_OUTPUT_ACTIVE_HIGH, NULL} // Status B
}, // Channel configurations
0,0 // HW dependent
};
static const PWMConfig PWMD4_CONFIG {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
PWMPlatform::PWMPlatform() {
// TIM1
pwmStart(&PWMD1, &PWMD1_CONFIG);
palSetPadMode(GPIOA, 8, PAL_MODE_ALTERNATE(1));
palSetPadMode(GPIOA, 9, PAL_MODE_ALTERNATE(1));
palSetPadMode(GPIOA, 10, PAL_MODE_ALTERNATE(1));
palSetPadMode(GPIOA, 11, PAL_MODE_ALTERNATE(1));
// TIM3
pwmStart(&PWMD3, &PWMD3_CONFIG);
palSetPadMode(GPIOA, 6, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOA, 7, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 0, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 1, PAL_MODE_ALTERNATE(2));
// TIM4
pwmStart(&PWMD4, &PWMD4_CONFIG);
palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 8, PAL_MODE_ALTERNATE(2));
palSetPadMode(GPIOB, 9, PAL_MODE_ALTERNATE(2));
}
void PWMPlatform::set(std::uint8_t ch, float dc) {
if (ch < 4) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD1, dc * 10000.0f);
pwmEnableChannel(&PWMD1, ch, width);
}
else if (ch < 8) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD4, dc * 10000.0f);
pwmEnableChannel(&PWMD4, ch-4, width);
}
else if (ch < 12) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD3, dc * 10000.0f);
pwmEnableChannel(&PWMD3, ch-8, width);
}
}
|
Expand PWMPlatform set function for aerial v4.
|
Expand PWMPlatform set function for aerial v4.
|
C++
|
mit
|
OSURoboticsClub/aerial_control,OSURoboticsClub/aerial_control,OSURoboticsClub/aerial_control
|
10881733bca8c8b391e029781389bebba7a19776
|
pycvodes/include/cvodes_anyode_parallel.hpp
|
pycvodes/include/cvodes_anyode_parallel.hpp
|
#pragma once
#include <cstdlib>
#include "anyode/anyode_parallel.hpp"
#include "cvodes_anyode.hpp"
namespace cvodes_anyode_parallel {
using cvodes_cxx::LMM;
using cvodes_cxx::IterType;
using cvodes_anyode::simple_adaptive;
using cvodes_anyode::simple_predefined;
using sa_t = std::pair<std::vector<realtype>, std::vector<realtype> >;
template <class OdeSys>
std::vector<std::pair<sa_t, std::vector<int>>>
multi_adaptive(std::vector<OdeSys *> odesys, // vectorized
const std::vector<realtype> atol,
const realtype rtol,
const LMM lmm,
const realtype * const y0, // vectorized
const realtype * t0, // vectorized
const realtype * tend, // vectorized
const long int mxsteps,
const realtype * dx0, // vectorized
const realtype * dx_min, // vectorized
const realtype * dx_max, // vectorized
const bool with_jacobian=false,
IterType iter_type=IterType::Undecided,
int linear_solver=0,
const int maxl=0,
const realtype eps_lin=0.0,
const unsigned nderiv=0,
bool return_on_root=false,
int autorestart=0, // must be autonomous!
bool return_on_error=false,
bool with_jtimes=false
){
const int ny = odesys[0]->get_ny();
const int nsys = odesys.size();
auto results = std::vector<std::pair<sa_t, std::vector<int>>>(nsys);
anyode_parallel::ThreadException te;
char * num_threads_var = std::getenv("ANYODE_NUM_THREADS");
int nt = (num_threads_var) ? std::atoi(num_threads_var) : 1;
if (nt < 0)
nt = 1;
#pragma omp parallel for num_threads(nt) // OMP_NUM_THREADS should be 1 for openblas LU (small matrices)
for (int idx=0; idx<nsys; ++idx){
std::pair<sa_t, std::vector<int>> local_result;
te.run([&]{
local_result.first = simple_adaptive<OdeSys>(
odesys[idx], atol, rtol, lmm, y0 + idx*ny, t0[idx], tend[idx],
local_result.second, mxsteps, dx0[idx], dx_min[idx], dx_max[idx], with_jacobian,
iter_type, linear_solver, maxl, eps_lin, nderiv, return_on_root,
autorestart, return_on_error, with_jtimes);
});
results[idx] = local_result;
}
te.rethrow();
return results;
}
template <class OdeSys>
std::vector<std::pair<int, std::pair<std::vector<int>, std::vector<double>>>>
multi_predefined(std::vector<OdeSys *> odesys, // vectorized
const std::vector<realtype> atol,
const realtype rtol,
const LMM lmm,
const realtype * const y0, // vectorized
const std::size_t nout,
const realtype * const tout, // vectorized
realtype * const yout, // vectorized
const long int mxsteps,
const realtype * dx0, // vectorized
const realtype * dx_min, // vectorized
const realtype * dx_max, // vectorized
const bool with_jacobian=false,
IterType iter_type=IterType::Undecided,
int linear_solver=0,
const int maxl=0,
const realtype eps_lin=0.0,
const unsigned nderiv=0,
int autorestart=0, // must be autonomous!
bool return_on_error=false,
bool with_jtimes=false
){
const int ny = odesys[0]->get_ny();
const int nsys = odesys.size();
auto nreached_roots = std::vector<std::pair<int, std::pair<std::vector<int>, std::vector<double>>>>(nsys);
anyode_parallel::ThreadException te;
#pragma omp parallel for
for (int idx=0; idx<nsys; ++idx){
te.run([&]{
nreached_roots[idx].first = simple_predefined<OdeSys>(
odesys[idx], atol, rtol, lmm, y0 + idx*ny,
nout, tout + idx*nout, yout + idx*ny*nout*(nderiv+1),
nreached_roots[idx].second.first, nreached_roots[idx].second.second,
mxsteps, dx0[idx], dx_min[idx], dx_max[idx], with_jacobian,
iter_type, linear_solver, maxl, eps_lin, nderiv,
autorestart, return_on_error, with_jtimes);
});
}
if (!return_on_error)
te.rethrow();
return nreached_roots;
}
}
|
#pragma once
#include <cstdlib>
#include "anyode/anyode_parallel.hpp"
#include "cvodes_anyode.hpp"
namespace cvodes_anyode_parallel {
using cvodes_cxx::LMM;
using cvodes_cxx::IterType;
using cvodes_anyode::simple_adaptive;
using cvodes_anyode::simple_predefined;
using sa_t = std::pair<std::vector<realtype>, std::vector<realtype> >;
template <class OdeSys>
std::vector<std::pair<sa_t, std::vector<int>>>
multi_adaptive(std::vector<OdeSys *> odesys, // vectorized
const std::vector<realtype> atol,
const realtype rtol,
const LMM lmm,
const realtype * const y0, // vectorized
const realtype * t0, // vectorized
const realtype * tend, // vectorized
const long int mxsteps,
const realtype * dx0, // vectorized
const realtype * dx_min, // vectorized
const realtype * dx_max, // vectorized
const bool with_jacobian=false,
IterType iter_type=IterType::Undecided,
int linear_solver=0,
const int maxl=0,
const realtype eps_lin=0.0,
const unsigned nderiv=0,
bool return_on_root=false,
int autorestart=0, // must be autonomous!
bool return_on_error=false,
bool with_jtimes=false
){
const int ny = odesys[0]->get_ny();
const int nsys = odesys.size();
auto results = std::vector<std::pair<sa_t, std::vector<int>>>(nsys);
anyode_parallel::ThreadException te;
char * num_threads_var = std::getenv("ANYODE_NUM_THREADS");
int nt = (num_threads_var) ? std::atoi(num_threads_var) : 1;
if (nt < 0)
nt = 1;
#pragma omp parallel for num_threads(nt) // OMP_NUM_THREADS should be 1 for openblas LU (small matrices)
for (int idx=0; idx<nsys; ++idx){
std::pair<sa_t, std::vector<int>> local_result;
te.run([&]{
local_result.first = simple_adaptive<OdeSys>(
odesys[idx], atol, rtol, lmm, y0 + idx*ny, t0[idx], tend[idx],
local_result.second, mxsteps, dx0[idx], dx_min[idx], dx_max[idx], with_jacobian,
iter_type, linear_solver, maxl, eps_lin, nderiv, return_on_root,
autorestart, return_on_error, with_jtimes);
});
results[idx] = local_result;
}
te.rethrow();
return results;
}
template <class OdeSys>
std::vector<std::pair<int, std::pair<std::vector<int>, std::vector<double>>>>
multi_predefined(std::vector<OdeSys *> odesys, // vectorized
const std::vector<realtype> atol,
const realtype rtol,
const LMM lmm,
const realtype * const y0, // vectorized
const std::size_t nout,
const realtype * const tout, // vectorized
realtype * const yout, // vectorized
const long int mxsteps,
const realtype * dx0, // vectorized
const realtype * dx_min, // vectorized
const realtype * dx_max, // vectorized
const bool with_jacobian=false,
IterType iter_type=IterType::Undecided,
int linear_solver=0,
const int maxl=0,
const realtype eps_lin=0.0,
const unsigned nderiv=0,
int autorestart=0, // must be autonomous!
bool return_on_error=false,
bool with_jtimes=false
){
const int ny = odesys[0]->get_ny();
const int nsys = odesys.size();
auto nreached_roots = std::vector<std::pair<int, std::pair<std::vector<int>, std::vector<double>>>>(nsys);
anyode_parallel::ThreadException te;
char * num_threads_var = std::getenv("ANYODE_NUM_THREADS");
int nt = (num_threads_var) ? std::atoi(num_threads_var) : 1;
if (nt < 0)
nt = 1;
#pragma omp parallel for num_threads(nt) // OMP_NUM_THREADS should be 1 for openblas LU (small matrices)
for (int idx=0; idx<nsys; ++idx){
te.run([&]{
nreached_roots[idx].first = simple_predefined<OdeSys>(
odesys[idx], atol, rtol, lmm, y0 + idx*ny,
nout, tout + idx*nout, yout + idx*ny*nout*(nderiv+1),
nreached_roots[idx].second.first, nreached_roots[idx].second.second,
mxsteps, dx0[idx], dx_min[idx], dx_max[idx], with_jacobian,
iter_type, linear_solver, maxl, eps_lin, nderiv,
autorestart, return_on_error, with_jtimes);
});
}
if (!return_on_error)
te.rethrow();
return nreached_roots;
}
}
|
Allow predefined to run in parallel
|
Allow predefined to run in parallel
|
C++
|
bsd-2-clause
|
bjodah/pycvodes,bjodah/pycvodes,bjodah/pycvodes,bjodah/pycvodes
|
f260418d9e4da31cee251dbc9c86130e176520c5
|
src/utils.cpp
|
src/utils.cpp
|
#include "utils.h"
//
#include <fstream> // fstream
#include <boost/tokenizer.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <numeric>
using namespace std;
using namespace boost;
using namespace boost::numeric::ublas;
std::ostream& operator<<(std::ostream& os, const std::map<std::string, double>& string_double_map) {
map<string, double>::const_iterator it = string_double_map.begin();
os << "{";
if(it==string_double_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=string_double_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const map<int, double>& int_double_map) {
map<int, double>::const_iterator it = int_double_map.begin();
os << "{";
if(it==int_double_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=int_double_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const map<int, int>& int_int_map) {
map<int, int>::const_iterator it = int_int_map.begin();
os << "{";
if(it==int_int_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=int_int_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
string int_to_str(int i) {
std::stringstream out;
out << i;
string s = out.str();
return s;
}
// FROM runModel_v2.cpp
/////////////////////////////////////////////////////////////////////
// expect a csv file of data
void LoadData(string file, boost::numeric::ublas::matrix<double>& M) {
ifstream in(file.c_str());
if (!in.is_open()) return;
typedef tokenizer< char_separator<char> > Tokenizer;
char_separator<char> sep(",");
string line;
int nrows = 0;
int ncols = 0;
std::vector<string> vec;
// get the size first
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
ncols = vec.end() - vec.begin();
nrows++;
}
cout << "num rows = "<< nrows << " num cols = " << ncols << endl;
// create a matrix to hold data
matrix<double> Data(nrows, ncols);
// make second pass
in.clear();
in.seekg(0);
int r = 0;
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
int i = 0;
for(i=0; i < vec.size() ; i++) {
Data(r, i) = ::strtod(vec[i].c_str(), 0);
}
r++;
}
M = Data;
}
bool is_almost(double val1, double val2, double precision) {
return abs(val1-val2) < precision;
}
// http://stackoverflow.com/a/11747023/1769715
std::vector<double> linspace(double a, double b, int n) {
std::vector<double> values;
double step = (b-a) / (n-1);
while(a <= b) {
values.push_back(a);
a += step;
}
return values;
}
std::vector<double> log_linspace(double a, double b, int n) {
std::vector<double> values = linspace(log(a), log(b), n);
std::transform(values.begin(), values.end(), values.begin(), (double (*)(double))exp);
return values;
}
std::vector<double> std_vector_sum(std::vector<double> vec1, std::vector<double> vec2) {
assert(vec1.size()==vec2.size());
std::vector<double> sum_vec;
for(int i=0; i<vec1.size(); i++) {
sum_vec.push_back(vec1[i] + vec2[i]);
}
return sum_vec;
}
std::vector<double> std_vector_sum(std::vector<std::vector<double> > vec_vec) {
std::vector<double> sum_vec = vec_vec[0];
std::vector<std::vector<double> >::iterator it = vec_vec.begin();
it++;
for(; it!=vec_vec.end(); it++) {
sum_vec = std_vector_sum(sum_vec, *it);
}
return sum_vec;
}
double calc_sum_sq_deviation(std::vector<double> values) {
double sum = std::accumulate(values.begin(), values.end(), 0.0);
double mean = sum / values.size();
double sum_sq_deviation = 0;
for(std::vector<double>::iterator it = values.begin(); it!=values.end(); it++) {
sum_sq_deviation += pow((*it) - mean, 2) ;
}
return sum_sq_deviation;
}
std::vector<double> extract_row(boost::numeric::ublas::matrix<double> data, int row_idx) {
std::vector<double> row;
for(int j=0;j < data.size2(); j++) {
row.push_back(data(row_idx, j));
}
return row;
}
std::vector<double> extract_col(boost::numeric::ublas::matrix<double> data, int col_idx) {
std::vector<double> col;
for(int j=0;j < data.size1(); j++) {
col.push_back(data(j, col_idx));
}
return col;
}
std::vector<double> append(std::vector<double> vec1, std::vector<double> vec2) {
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
return vec1;
}
|
#include "utils.h"
//
#include <fstream> // fstream
#include <boost/tokenizer.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <numeric>
using namespace std;
using namespace boost;
using namespace boost::numeric::ublas;
template <class K, class V>
std::ostream& operator<<(std::ostream& os, const map<K, V> in_map) {
typename map<K, V>::iterator it;
os << "{";
if(in_map.begin()!=in_map.end()) {
os << it->first << ":" << it->second;
}
for(it=in_map.begin(); it!=in_map.end(); it++) {
os << ", " << it->first << " : " << it->second;
}
os << "}";
return os;
}
string int_to_str(int i) {
std::stringstream out;
out << i;
string s = out.str();
return s;
}
// FROM runModel_v2.cpp
/////////////////////////////////////////////////////////////////////
// expect a csv file of data
void LoadData(string file, boost::numeric::ublas::matrix<double>& M) {
ifstream in(file.c_str());
if (!in.is_open()) return;
typedef tokenizer< char_separator<char> > Tokenizer;
char_separator<char> sep(",");
string line;
int nrows = 0;
int ncols = 0;
std::vector<string> vec;
// get the size first
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
ncols = vec.end() - vec.begin();
nrows++;
}
cout << "num rows = "<< nrows << " num cols = " << ncols << endl;
// create a matrix to hold data
matrix<double> Data(nrows, ncols);
// make second pass
in.clear();
in.seekg(0);
int r = 0;
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
int i = 0;
for(i=0; i < vec.size() ; i++) {
Data(r, i) = ::strtod(vec[i].c_str(), 0);
}
r++;
}
M = Data;
}
bool is_almost(double val1, double val2, double precision) {
return abs(val1-val2) < precision;
}
// http://stackoverflow.com/a/11747023/1769715
std::vector<double> linspace(double a, double b, int n) {
std::vector<double> values;
double step = (b-a) / (n-1);
while(a <= b) {
values.push_back(a);
a += step;
}
return values;
}
std::vector<double> log_linspace(double a, double b, int n) {
std::vector<double> values = linspace(log(a), log(b), n);
std::transform(values.begin(), values.end(), values.begin(), (double (*)(double))exp);
return values;
}
std::vector<double> std_vector_sum(std::vector<double> vec1, std::vector<double> vec2) {
assert(vec1.size()==vec2.size());
std::vector<double> sum_vec;
for(int i=0; i<vec1.size(); i++) {
sum_vec.push_back(vec1[i] + vec2[i]);
}
return sum_vec;
}
std::vector<double> std_vector_sum(std::vector<std::vector<double> > vec_vec) {
std::vector<double> sum_vec = vec_vec[0];
std::vector<std::vector<double> >::iterator it = vec_vec.begin();
it++;
for(; it!=vec_vec.end(); it++) {
sum_vec = std_vector_sum(sum_vec, *it);
}
return sum_vec;
}
double calc_sum_sq_deviation(std::vector<double> values) {
double sum = std::accumulate(values.begin(), values.end(), 0.0);
double mean = sum / values.size();
double sum_sq_deviation = 0;
for(std::vector<double>::iterator it = values.begin(); it!=values.end(); it++) {
sum_sq_deviation += pow((*it) - mean, 2) ;
}
return sum_sq_deviation;
}
std::vector<double> extract_row(boost::numeric::ublas::matrix<double> data, int row_idx) {
std::vector<double> row;
for(int j=0;j < data.size2(); j++) {
row.push_back(data(row_idx, j));
}
return row;
}
std::vector<double> extract_col(boost::numeric::ublas::matrix<double> data, int col_idx) {
std::vector<double> col;
for(int j=0;j < data.size1(); j++) {
col.push_back(data(j, col_idx));
}
return col;
}
std::vector<double> append(std::vector<double> vec1, std::vector<double> vec2) {
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
return vec1;
}
double get(const map<string, double> m, string key) {
map<string, double>::const_iterator it = m.find(key);
if(it == m.end()) return -1;
return it->second;
}
|
remove Cluster,Suffstats dependencies; move get function from Suffstats to utils
|
remove Cluster,Suffstats dependencies; move get function from Suffstats to utils
|
C++
|
apache-2.0
|
probcomp/crosscat,probcomp/crosscat,JDReutt/BayesDB,probcomp/crosscat,poppingtonic/BayesDB,probcomp/crosscat,JDReutt/BayesDB,poppingtonic/BayesDB,mit-probabilistic-computing-project/crosscat,poppingtonic/BayesDB,JDReutt/BayesDB,probcomp/crosscat,mit-probabilistic-computing-project/crosscat,JDReutt/BayesDB,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,probcomp/crosscat,probcomp/crosscat,poppingtonic/BayesDB,JDReutt/BayesDB,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,poppingtonic/BayesDB,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,fivejjs/crosscat,probcomp/crosscat
|
337a36ac7c800c8deb612298104eac175fca6416
|
Source/FacebookParse/Private/FacebookFunctions.cpp
|
Source/FacebookParse/Private/FacebookFunctions.cpp
|
//
// Created by Derek van Vliet on 2014-12-10.
// Copyright (c) 2015 Get Set Games Inc. All rights reserved.
//
#include "FacebookParsePrivatePCH.h"
#if PLATFORM_ANDROID
#include "Android/AndroidJNI.h"
#include "AndroidApplication.h"
#endif
FString UFacebookFunctions::FacebookGetAccessToken()
{
FString Result;
#if PLATFORM_IOS
if ([FBSDKAccessToken currentAccessToken])
{
Result = FString([FBSDKAccessToken currentAccessToken].tokenString);
}
#elif PLATFORM_ANDROID
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
}
#endif
return Result;
}
FString UFacebookFunctions::FacebookGetAccessTokenExpirationDate()
{
FString Result;
#if PLATFORM_IOS
if ([FBSDKAccessToken currentAccessToken])
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
Result = FString([dateFormatter stringFromDate:[FBSDKAccessToken currentAccessToken].expirationDate]);
}
#elif PLATFORM_ANDROID
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
}
#endif
return Result;
}
FString UFacebookFunctions::FacebookGetUserId()
{
FString Result;
#if PLATFORM_IOS
if ([FBSDKAccessToken currentAccessToken])
{
Result = FString([FBSDKAccessToken currentAccessToken].userID);
}
#elif PLATFORM_ANDROID
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
}
#endif
return Result;
}
|
//
// Created by Derek van Vliet on 2014-12-10.
// Copyright (c) 2015 Get Set Games Inc. All rights reserved.
//
#include "FacebookParsePrivatePCH.h"
#if PLATFORM_ANDROID
#include "Android/AndroidJNI.h"
#include "AndroidApplication.h"
#endif
FString UFacebookFunctions::FacebookGetAccessToken()
{
FString Result;
#if PLATFORM_IOS
if ([FBSDKAccessToken currentAccessToken])
{
Result = FString([FBSDKAccessToken currentAccessToken].tokenString);
}
#elif PLATFORM_ANDROID
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
static jmethodID Method = FJavaWrapper::FindMethod(Env,
FJavaWrapper::GameActivityClassID,
"AndroidThunk_Java_FacebookGetAccessToken",
"()Ljava/lang/String;",
false);
jstring AccessToken = (jstring)FJavaWrapper::CallObjectMethod(Env, FJavaWrapper::GameActivityThis, Method);
const char *s = Env->GetStringUTFChars(AccessToken, 0);
Result = FString(UTF8_TO_TCHAR(s));
Env->ReleaseStringUTFChars(AccessToken, s);
}
#endif
return Result;
}
FString UFacebookFunctions::FacebookGetAccessTokenExpirationDate()
{
FString Result;
#if PLATFORM_IOS
if ([FBSDKAccessToken currentAccessToken])
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
Result = FString([dateFormatter stringFromDate:[FBSDKAccessToken currentAccessToken].expirationDate]);
}
#elif PLATFORM_ANDROID
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
}
#endif
return Result;
}
FString UFacebookFunctions::FacebookGetUserId()
{
FString Result;
#if PLATFORM_IOS
if ([FBSDKAccessToken currentAccessToken])
{
Result = FString([FBSDKAccessToken currentAccessToken].userID);
}
#elif PLATFORM_ANDROID
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
}
#endif
return Result;
}
|
call Java function to get Facebook access token
|
[change] call Java function to get Facebook access token
|
C++
|
mit
|
getsetgames/FacebookParse,getsetgames/FacebookParse,getsetgames/FacebookParse
|
b82872bcfbc0a9f9e503c7dd1eb9f470ca177e57
|
pyrtist/pyrtist/deepsurface/depth_buffer.cc
|
pyrtist/pyrtist/deepsurface/depth_buffer.cc
|
#include <algorithm>
#include <math.h>
#include "draw_depth.h"
#include "depth_buffer.h"
void DepthBuffer::DrawStep(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float start_x, float start_y, float start_z,
float end_x, float end_y, float end_z) {
float dx = end_x - start_x;
float dy = end_y - start_y;
float dz = end_z - start_z;
float v2 = dx*dx + dy*dy;
if (v2 == 0.0f)
return;
float increment_x = dx/v2;
float increment_y = dy/v2;
float offset = -(start_x*increment_x + start_y*increment_y);
float matrix[6] = {increment_x, increment_y, offset, 0.0f, 0.0f, 0.0f};
auto depth_fn =
[start_z, dz](float* out, float u, float v) -> void {
if (u >= 0.0 && u <= 1.0)
*out = start_z + u*dz;
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
matrix, depth_fn);
}
void DepthBuffer::DrawCylinder(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float end_radius,
float z_of_axis, float start_radius_z,
float end_radius_z) {
float drz = end_radius_z - start_radius_z;
float dr = end_radius - 1.0f;
auto depth_fn =
[dr, drz, z_of_axis, start_radius_z](float* out,
float u, float v) -> void {
float r = 1.0f + u*dr;
v /= r;
float z2 = 1.0f - v*v;
if (z2 >= 0.0f) {
float rz = start_radius_z + u*drz;
*out = z_of_axis + rz*sqrt(z2);
}
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawPlane(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float z00, float z10, float z01) {
z01 -= z00;
z10 -= z00;
auto depth_fn =
[z00, z10, z01](float* out, float u, float v) -> void {
*out = z00 + u*z01 + v*z10;
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawSphere(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float translate_z, float z_end) {
float scale_z = z_end - translate_z;
auto depth_fn =
[scale_z, translate_z](float* out, float u, float v) -> void {
float z2 = 1.0f - (u*u + v*v);
if (z2 >= 0.0f)
*out = translate_z + scale_z*sqrt(z2);
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawCrescent(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float scale_z, float translate_z,
float y0, float y1) {
constexpr float half_pi = 2.0f*atan(1.0f);
if (y0 > y1)
std::swap(y0, y1);
float delta_y = 0.5f*(y1 - y0);
float y_orig = 0.5f*(y0 + y1);
auto depth_fn =
[scale_z, translate_z, y0, y1, delta_y, y_orig]
(float* out, float u, float v) -> void {
if (fabsf(v) == 0.0f) {
*out = translate_z + scale_z*cos(half_pi*u);
} else {
float cy = (u*u + v*v - 1.0f)/(2.0f*v);
float y = cy + copysign(sqrt(1.0f + cy*cy), v);
if (y0 <= y && y <= y1) {
float pr = (y - y_orig)/delta_y; // Planar radial component.
float z2 = 1.0f - pr*pr; // Normal radial component.
if (z2 >= 0.0f) {
float axial; // Axial component.
if (y >= 0.0)
axial = atan2f(-u, v - cy)/atan2f(-1.0f, -cy);
else
axial = atan2f(u, cy - v)/atan2f(1.0f, cy);
*out = translate_z + scale_z*sqrt(z2)*cos(half_pi*axial);
}
}
}
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawCircular(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float scale_z, float translate_z,
std::function<float(float)> radius_fn) {
auto depth_fn =
[scale_z, translate_z, radius_fn](float* out, float u, float v) -> void {
float r = radius_fn(u);
v /= r;
float z2 = 1.0f - v*v;
if (z2 >= 0.0f)
*out = translate_z + scale_z*r*sqrt(z2);
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
ARGBImageBuffer* DepthBuffer::ComputeNormals() {
auto normals = new ARGBImageBuffer(width_, width_, height_);
if (normals == nullptr || width_ < 3 || height_ < 3)
return normals;
int32_t* out_ptr = reinterpret_cast<int32_t*>(normals->GetPtr());
int nx = width_ - 2;
int ny = height_ - 2;
DepthType* begin_ptr = GetPtr();
DepthType* ptr = &begin_ptr[width_];
for (int iy = 1; iy < ny; iy++) {
DepthType lft = *ptr++;
DepthType* top_ptr = ptr - width_;
DepthType* bot_ptr = ptr + width_;
DepthType ctr = *ptr++;
DepthType rgt;
uint32_t x_mask = ((IsInfiniteDepth(lft) ? 1U : 0U) |
(IsInfiniteDepth(ctr) ? 2U : 0U));
DepthType* final_ptr = ptr + nx;
while (ptr < final_ptr) {
size_t offset = ptr - 1 - begin_ptr;
rgt = *ptr++;
x_mask |= (IsInfiniteDepth(rgt) ? 4U : 0U);
if ((x_mask & 2U) != 0) {
// Point with infinite depth: use default colors.
out_ptr[offset] = 0xff8080ff;
} else {
top_ptr = ptr - 2 - width_;
bot_ptr = ptr - 2 + width_;
DepthType top = *top_ptr;
DepthType bot = *bot_ptr;
bool top_absent = IsInfiniteDepth(top);
bool bot_absent = IsInfiniteDepth(bot);
float dy; // Compute -d/dy depth(x, y) in dy.
if (LIKELY(top_absent == bot_absent))
dy = UNLIKELY(top_absent) ? 0.0f : (bot - top)*0.5f;
else
dy = top_absent ? bot - ctr : ctr - top;
float dx; // Compute -d/dx depth(x, y) in dx.
if (LIKELY(x_mask == 0U))
dx = (rgt - lft)*0.5f;
else if (x_mask == 4U)
dx = ctr - lft;
else if (x_mask == 1U)
dx = rgt - ctr;
else
dx = 0.0f;
// Now compute the norm of the unnormalized normal vector.
float d = sqrtf(1.0f + dx*dx + dy*dy);
uint8_t red = 128 + static_cast<uint8_t>((dx*127.0f)/d);
uint8_t green = 128 + static_cast<uint8_t>((dy*127.0f)/d);
uint8_t blue = 128 + static_cast<uint8_t>(127.0/d);
out_ptr[offset] = ((static_cast<uint32_t>(blue)) |
(static_cast<uint32_t>(green) << 8) |
(static_cast<uint32_t>(red) << 16) |
(UINT32_C(0xff) << 24));
}
lft = ctr;
ctr = rgt;
x_mask >>= 1;
}
}
return normals;
}
|
#include <algorithm>
#include <math.h>
#include "draw_depth.h"
#include "depth_buffer.h"
void DepthBuffer::DrawStep(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float start_x, float start_y, float start_z,
float end_x, float end_y, float end_z) {
float dx = end_x - start_x;
float dy = end_y - start_y;
float dz = end_z - start_z;
float v2 = dx*dx + dy*dy;
if (v2 == 0.0f)
return;
float increment_x = dx/v2;
float increment_y = dy/v2;
float offset = -(start_x*increment_x + start_y*increment_y);
float matrix[6] = {increment_x, increment_y, offset, 0.0f, 0.0f, 0.0f};
auto depth_fn =
[start_z, dz](float* out, float u, float v) -> void {
if (u >= 0.0 && u <= 1.0)
*out = start_z + u*dz;
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
matrix, depth_fn);
}
void DepthBuffer::DrawCylinder(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float end_radius,
float z_of_axis, float start_radius_z,
float end_radius_z) {
float drz = end_radius_z - start_radius_z;
float dr = end_radius - 1.0f;
auto depth_fn =
[dr, drz, z_of_axis, start_radius_z](float* out,
float u, float v) -> void {
float r = 1.0f + u*dr;
v /= r;
float z2 = 1.0f - v*v;
if (z2 >= 0.0f) {
float rz = start_radius_z + u*drz;
*out = z_of_axis + rz*sqrt(z2);
}
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawPlane(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float z00, float z10, float z01) {
z01 -= z00;
z10 -= z00;
auto depth_fn =
[z00, z10, z01](float* out, float u, float v) -> void {
*out = z00 + u*z01 + v*z10;
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawSphere(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float translate_z, float z_end) {
float scale_z = z_end - translate_z;
auto depth_fn =
[scale_z, translate_z](float* out, float u, float v) -> void {
float z2 = 1.0f - (u*u + v*v);
if (z2 >= 0.0f)
*out = translate_z + scale_z*sqrt(z2);
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
/// @brief Compute (sqrt(1 + x*x) - 1)/x without precision losses when x ~ 0.
static float Sqrt1PlusX2Min1DivX(float x) {
constexpr float small_x = 1.0f / (1 << 12);
// small_x as defined above is roughly the point where the linear
// approximation performs better than the actual computation.
return (fabsf(x) > small_x) ? (sqrtf(1.0f + x*x) - 1.0f)/x : 0.5f*x;
}
void DepthBuffer::DrawCrescent(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float scale_z, float translate_z,
float y0, float y1) {
constexpr float half_pi = 2.0f*atan(1.0f);
if (y0 > y1)
std::swap(y0, y1);
float delta_y = 0.5f*(y1 - y0);
float y_orig = 0.5f*(y0 + y1);
auto depth_fn =
[scale_z, translate_z, y0, y1, delta_y, y_orig]
(float* out, float u, float v) -> void {
float v2 = v*v;
float a2 = u*u + v2 - 1.0f;
if (a2 + v2 >= 0.0f) {
// Outside the unit circle: high-curvature long arcs.
// In this case, the center cy and the radius, sqrt(1 + cy^2), are well
// behaved, except in the region v ~ 0, |u| >= 0.
float cy = a2/(2.0f*v);
float y = cy + copysign(sqrt(1.0f + cy*cy), v);
if (y0 <= y && y <= y1) {
float pr = (y - y_orig)/delta_y; // Planar radial component.
float z2 = 1.0f - pr*pr; // Normal radial component.
if (z2 >= 0.0f) {
float axial; // Axial component.
if (y >= 0.0)
axial = atan2f(-u, v - cy)/atan2f(-1.0f, -cy);
else
axial = atan2f(u, cy - v)/atan2f(1.0f, cy);
*out = translate_z + scale_z*sqrt(z2)*cos(half_pi*axial);
}
}
} else {
// Inside the unit circle: low-curvature short arcs.
// In this case, the center cy and the radius, sqrt(1 + cy^2), become
// arbitrarily large when v --> 0, despite these points are part of
// the primitive. Things go better if we reason in terms of curvature,
// except that the curvature is not well defined around (+-1, 0).
float cv = (2.0f*v)/a2; // Curvature.
float y = -Sqrt1PlusX2Min1DivX(cv);
if (y0 <= y && y <= y1) {
float pr = (y - y_orig)/delta_y; // Planar radial component.
float z2 = 1.0f - pr*pr; // Normal radial component.
if (z2 >= 0.0f) {
// Axial component.
float axial = atanf(u*cv/(1.0f - v*cv))/atanf(cv);
*out = translate_z + scale_z*sqrt(z2)*cos(half_pi*axial);
}
}
}
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
void DepthBuffer::DrawCircular(float clip_start_x, float clip_start_y,
float clip_end_x, float clip_end_y,
float* mx, float scale_z, float translate_z,
std::function<float(float)> radius_fn) {
auto depth_fn =
[scale_z, translate_z, radius_fn](float* out, float u, float v) -> void {
float r = radius_fn(u);
v /= r;
float z2 = 1.0f - v*v;
if (z2 >= 0.0f)
*out = translate_z + scale_z*r*sqrt(z2);
};
DrawDepth(this, clip_start_x, clip_start_y, clip_end_x, clip_end_y,
mx, depth_fn);
}
ARGBImageBuffer* DepthBuffer::ComputeNormals() {
auto normals = new ARGBImageBuffer(width_, width_, height_);
if (normals == nullptr || width_ < 3 || height_ < 3)
return normals;
int32_t* out_ptr = reinterpret_cast<int32_t*>(normals->GetPtr());
int nx = width_ - 2;
int ny = height_ - 2;
DepthType* begin_ptr = GetPtr();
DepthType* ptr = &begin_ptr[width_];
for (int iy = 1; iy < ny; iy++) {
DepthType lft = *ptr++;
DepthType* top_ptr = ptr - width_;
DepthType* bot_ptr = ptr + width_;
DepthType ctr = *ptr++;
DepthType rgt;
uint32_t x_mask = ((IsInfiniteDepth(lft) ? 1U : 0U) |
(IsInfiniteDepth(ctr) ? 2U : 0U));
DepthType* final_ptr = ptr + nx;
while (ptr < final_ptr) {
size_t offset = ptr - 1 - begin_ptr;
rgt = *ptr++;
x_mask |= (IsInfiniteDepth(rgt) ? 4U : 0U);
if ((x_mask & 2U) != 0) {
// Point with infinite depth: use default colors.
out_ptr[offset] = 0xff8080ff;
} else {
top_ptr = ptr - 2 - width_;
bot_ptr = ptr - 2 + width_;
DepthType top = *top_ptr;
DepthType bot = *bot_ptr;
bool top_absent = IsInfiniteDepth(top);
bool bot_absent = IsInfiniteDepth(bot);
float dy; // Compute -d/dy depth(x, y) in dy.
if (LIKELY(top_absent == bot_absent))
dy = UNLIKELY(top_absent) ? 0.0f : (bot - top)*0.5f;
else
dy = top_absent ? bot - ctr : ctr - top;
float dx; // Compute -d/dx depth(x, y) in dx.
if (LIKELY(x_mask == 0U))
dx = (rgt - lft)*0.5f;
else if (x_mask == 4U)
dx = ctr - lft;
else if (x_mask == 1U)
dx = rgt - ctr;
else
dx = 0.0f;
// Now compute the norm of the unnormalized normal vector.
float d = sqrtf(1.0f + dx*dx + dy*dy);
uint8_t red = 128 + static_cast<uint8_t>((dx*127.0f)/d);
uint8_t green = 128 + static_cast<uint8_t>((dy*127.0f)/d);
uint8_t blue = 128 + static_cast<uint8_t>(127.0/d);
out_ptr[offset] = ((static_cast<uint32_t>(blue)) |
(static_cast<uint32_t>(green) << 8) |
(static_cast<uint32_t>(red) << 16) |
(UINT32_C(0xff) << 24));
}
lft = ctr;
ctr = rgt;
x_mask >>= 1;
}
}
return normals;
}
|
Fix some precision issues in Crescent computations
|
Fix some precision issues in Crescent computations
|
C++
|
lgpl-2.1
|
mfnch/pyrtist,mfnch/pyrtist,mfnch/pyrtist,mfnch/pyrtist,mfnch/pyrtist,mfnch/pyrtist
|
7883a0551d55fe962092b94c9d72aa3354a15f8d
|
Source/core/css/PropertySetCSSStyleDeclaration.cpp
|
Source/core/css/PropertySetCSSStyleDeclaration.cpp
|
/*
* (C) 1999-2003 Lars Knoll ([email protected])
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2011 Research In Motion Limited. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/css/PropertySetCSSStyleDeclaration.h"
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionState.h"
#include "core/css/parser/BisonCSSParser.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/Element.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/inspector/InspectorInstrumentation.h"
using namespace std;
namespace WebCore {
namespace {
class StyleAttributeMutationScope {
WTF_MAKE_NONCOPYABLE(StyleAttributeMutationScope);
public:
StyleAttributeMutationScope(AbstractPropertySetCSSStyleDeclaration* decl)
{
InspectorInstrumentation::willMutateStyle(decl);
++s_scopeCount;
if (s_scopeCount != 1) {
ASSERT(s_currentDecl == decl);
return;
}
ASSERT(!s_currentDecl);
s_currentDecl = decl;
if (!s_currentDecl->parentElement())
return;
bool shouldReadOldValue = false;
m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(*s_currentDecl->parentElement(), HTMLNames::styleAttr);
if (m_mutationRecipients && m_mutationRecipients->isOldValueRequested())
shouldReadOldValue = true;
AtomicString oldValue;
if (shouldReadOldValue)
oldValue = s_currentDecl->parentElement()->getAttribute(HTMLNames::styleAttr);
if (m_mutationRecipients) {
AtomicString requestedOldValue = m_mutationRecipients->isOldValueRequested() ? oldValue : nullAtom;
m_mutation = MutationRecord::createAttributes(s_currentDecl->parentElement(), HTMLNames::styleAttr, requestedOldValue);
}
}
~StyleAttributeMutationScope()
{
--s_scopeCount;
if (s_scopeCount)
return;
if (m_mutation && s_shouldDeliver)
m_mutationRecipients->enqueueMutationRecord(m_mutation);
s_shouldDeliver = false;
// We have to clear internal state before calling Inspector's code.
AbstractPropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
s_currentDecl = 0;
InspectorInstrumentation::didMutateStyle(localCopyStyleDecl, localCopyStyleDecl->parentElement());
if (!s_shouldNotifyInspector)
return;
s_shouldNotifyInspector = false;
if (localCopyStyleDecl->parentElement())
InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement());
}
void enqueueMutationRecord()
{
s_shouldDeliver = true;
}
void didInvalidateStyleAttr()
{
s_shouldNotifyInspector = true;
}
private:
static unsigned s_scopeCount;
static AbstractPropertySetCSSStyleDeclaration* s_currentDecl;
static bool s_shouldNotifyInspector;
static bool s_shouldDeliver;
OwnPtr<MutationObserverInterestGroup> m_mutationRecipients;
RefPtr<MutationRecord> m_mutation;
};
unsigned StyleAttributeMutationScope::s_scopeCount = 0;
AbstractPropertySetCSSStyleDeclaration* StyleAttributeMutationScope::s_currentDecl = 0;
bool StyleAttributeMutationScope::s_shouldNotifyInspector = false;
bool StyleAttributeMutationScope::s_shouldDeliver = false;
} // namespace
void PropertySetCSSStyleDeclaration::ref()
{
m_propertySet->ref();
}
void PropertySetCSSStyleDeclaration::deref()
{
m_propertySet->deref();
}
unsigned AbstractPropertySetCSSStyleDeclaration::length() const
{
return propertySet().propertyCount();
}
String AbstractPropertySetCSSStyleDeclaration::item(unsigned i) const
{
if (i >= propertySet().propertyCount())
return "";
return propertySet().propertyAt(i).cssName();
}
String AbstractPropertySetCSSStyleDeclaration::cssText() const
{
return propertySet().asText();
}
void AbstractPropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
willMutate();
// FIXME: Detect syntax errors and set exceptionState.
propertySet().parseDeclaration(text, contextStyleSheet());
didMutate(PropertyChanged);
mutationScope.enqueueMutationRecord();
}
PassRefPtrWillBeRawPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValue(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return nullptr;
return cloneAndCacheForCSSOM(propertySet().getPropertyCSSValue(propertyID).get());
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyValue(const String &propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return propertySet().getPropertyValue(propertyID);
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyPriority(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return propertySet().propertyIsImportant(propertyID) ? "important" : "";
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyShorthand(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
CSSPropertyID shorthandID = propertySet().getPropertyShorthand(propertyID);
if (!shorthandID)
return String();
return getPropertyNameString(shorthandID);
}
bool AbstractPropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return false;
return propertySet().isPropertyImplicit(propertyID);
}
void AbstractPropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return;
bool important = equalIgnoringCase(priority, "important");
if (!important && !priority.isEmpty())
return;
willMutate();
bool changed = propertySet().setProperty(propertyID, value, important, contextStyleSheet());
didMutate(changed ? PropertyChanged : NoChanges);
if (changed) {
// CSS DOM requires raising SyntaxError of parsing failed, but this is too dangerous for compatibility,
// see <http://bugs.webkit.org/show_bug.cgi?id=7296>.
mutationScope.enqueueMutationRecord();
}
}
String AbstractPropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
willMutate();
String result;
bool changed = propertySet().removeProperty(propertyID, &result);
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
return result;
}
PassRefPtrWillBeRawPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
{
return propertySet().getPropertyCSSValue(propertyID);
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID)
{
return propertySet().getPropertyValue(propertyID);
}
void AbstractPropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState&)
{
StyleAttributeMutationScope mutationScope(this);
willMutate();
bool changed = propertySet().setProperty(propertyID, value, important, contextStyleSheet());
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
}
CSSValue* AbstractPropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
{
if (!internalValue)
return 0;
// The map is here to maintain the object identity of the CSSValues over multiple invocations.
// FIXME: It is likely that the identity is not important for web compatibility and this code should be removed.
if (!m_cssomCSSValueClones)
m_cssomCSSValueClones = adoptPtrWillBeNoop(new WillBeHeapHashMap<CSSValue*, RefPtrWillBeMember<CSSValue> >);
RefPtrWillBeMember<CSSValue>& clonedValue = m_cssomCSSValueClones->add(internalValue, RefPtrWillBeMember<CSSValue>()).storedValue->value;
if (!clonedValue)
clonedValue = internalValue->cloneForCSSOM();
return clonedValue.get();
}
StyleSheetContents* AbstractPropertySetCSSStyleDeclaration::contextStyleSheet() const
{
CSSStyleSheet* cssStyleSheet = parentStyleSheet();
return cssStyleSheet ? cssStyleSheet->contents() : 0;
}
PassRefPtrWillBeRawPtr<MutableStylePropertySet> AbstractPropertySetCSSStyleDeclaration::copyProperties() const
{
return propertySet().mutableCopy();
}
bool AbstractPropertySetCSSStyleDeclaration::cssPropertyMatches(CSSPropertyID propertyID, const CSSValue* propertyValue) const
{
return propertySet().propertyMatches(propertyID, propertyValue);
}
StyleRuleCSSStyleDeclaration::StyleRuleCSSStyleDeclaration(MutableStylePropertySet& propertySetArg, CSSRule* parentRule)
: PropertySetCSSStyleDeclaration(propertySetArg)
, m_refCount(1)
, m_parentRule(parentRule)
{
m_propertySet->ref();
}
StyleRuleCSSStyleDeclaration::~StyleRuleCSSStyleDeclaration()
{
m_propertySet->deref();
}
void StyleRuleCSSStyleDeclaration::ref()
{
++m_refCount;
}
void StyleRuleCSSStyleDeclaration::deref()
{
ASSERT(m_refCount);
if (!--m_refCount)
delete this;
}
void StyleRuleCSSStyleDeclaration::willMutate()
{
if (m_parentRule && m_parentRule->parentStyleSheet())
m_parentRule->parentStyleSheet()->willMutateRules();
}
void StyleRuleCSSStyleDeclaration::didMutate(MutationType type)
{
if (type == PropertyChanged)
m_cssomCSSValueClones.clear();
// Style sheet mutation needs to be signaled even if the change failed. willMutateRules/didMutateRules must pair.
if (m_parentRule && m_parentRule->parentStyleSheet())
m_parentRule->parentStyleSheet()->didMutateRules();
}
CSSStyleSheet* StyleRuleCSSStyleDeclaration::parentStyleSheet() const
{
return m_parentRule ? m_parentRule->parentStyleSheet() : 0;
}
void StyleRuleCSSStyleDeclaration::reattach(MutableStylePropertySet& propertySet)
{
m_propertySet->deref();
m_propertySet = &propertySet;
m_propertySet->ref();
}
MutableStylePropertySet& InlineCSSStyleDeclaration::propertySet() const
{
return m_parentElement->ensureMutableInlineStyle();
}
void InlineCSSStyleDeclaration::didMutate(MutationType type)
{
if (type == NoChanges)
return;
m_cssomCSSValueClones.clear();
if (!m_parentElement)
return;
m_parentElement->clearMutableInlineStyleIfEmpty();
m_parentElement->setNeedsStyleRecalc(LocalStyleChange);
m_parentElement->invalidateStyleAttribute();
StyleAttributeMutationScope(this).didInvalidateStyleAttr();
}
CSSStyleSheet* InlineCSSStyleDeclaration::parentStyleSheet() const
{
return m_parentElement ? &m_parentElement->document().elementSheet() : 0;
}
void InlineCSSStyleDeclaration::ref()
{
m_parentElement->ref();
}
void InlineCSSStyleDeclaration::deref()
{
m_parentElement->deref();
}
} // namespace WebCore
|
/*
* (C) 1999-2003 Lars Knoll ([email protected])
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2011 Research In Motion Limited. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/css/PropertySetCSSStyleDeclaration.h"
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionState.h"
#include "core/css/parser/BisonCSSParser.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/Element.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/inspector/InspectorInstrumentation.h"
using namespace std;
namespace WebCore {
namespace {
class StyleAttributeMutationScope {
WTF_MAKE_NONCOPYABLE(StyleAttributeMutationScope);
public:
StyleAttributeMutationScope(AbstractPropertySetCSSStyleDeclaration* decl)
{
InspectorInstrumentation::willMutateStyle(decl);
++s_scopeCount;
if (s_scopeCount != 1) {
ASSERT(s_currentDecl == decl);
return;
}
ASSERT(!s_currentDecl);
s_currentDecl = decl;
if (!s_currentDecl->parentElement())
return;
bool shouldReadOldValue = false;
m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(*s_currentDecl->parentElement(), HTMLNames::styleAttr);
if (m_mutationRecipients && m_mutationRecipients->isOldValueRequested())
shouldReadOldValue = true;
AtomicString oldValue;
if (shouldReadOldValue)
oldValue = s_currentDecl->parentElement()->getAttribute(HTMLNames::styleAttr);
if (m_mutationRecipients) {
AtomicString requestedOldValue = m_mutationRecipients->isOldValueRequested() ? oldValue : nullAtom;
m_mutation = MutationRecord::createAttributes(s_currentDecl->parentElement(), HTMLNames::styleAttr, requestedOldValue);
}
}
~StyleAttributeMutationScope()
{
--s_scopeCount;
if (s_scopeCount)
return;
if (m_mutation && s_shouldDeliver)
m_mutationRecipients->enqueueMutationRecord(m_mutation);
s_shouldDeliver = false;
// We have to clear internal state before calling Inspector's code.
AbstractPropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
s_currentDecl = 0;
InspectorInstrumentation::didMutateStyle(localCopyStyleDecl, localCopyStyleDecl->parentElement());
if (!s_shouldNotifyInspector)
return;
s_shouldNotifyInspector = false;
if (localCopyStyleDecl->parentElement())
InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement());
}
void enqueueMutationRecord()
{
s_shouldDeliver = true;
}
void didInvalidateStyleAttr()
{
s_shouldNotifyInspector = true;
}
private:
static unsigned s_scopeCount;
static AbstractPropertySetCSSStyleDeclaration* s_currentDecl;
static bool s_shouldNotifyInspector;
static bool s_shouldDeliver;
OwnPtr<MutationObserverInterestGroup> m_mutationRecipients;
RefPtr<MutationRecord> m_mutation;
};
unsigned StyleAttributeMutationScope::s_scopeCount = 0;
AbstractPropertySetCSSStyleDeclaration* StyleAttributeMutationScope::s_currentDecl = 0;
bool StyleAttributeMutationScope::s_shouldNotifyInspector = false;
bool StyleAttributeMutationScope::s_shouldDeliver = false;
} // namespace
void PropertySetCSSStyleDeclaration::ref()
{
m_propertySet->ref();
}
void PropertySetCSSStyleDeclaration::deref()
{
m_propertySet->deref();
}
unsigned AbstractPropertySetCSSStyleDeclaration::length() const
{
return propertySet().propertyCount();
}
String AbstractPropertySetCSSStyleDeclaration::item(unsigned i) const
{
if (i >= propertySet().propertyCount())
return "";
return propertySet().propertyAt(i).cssName();
}
String AbstractPropertySetCSSStyleDeclaration::cssText() const
{
return propertySet().asText();
}
void AbstractPropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
willMutate();
// FIXME: Detect syntax errors and set exceptionState.
propertySet().parseDeclaration(text, contextStyleSheet());
didMutate(PropertyChanged);
mutationScope.enqueueMutationRecord();
}
PassRefPtrWillBeRawPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValue(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return nullptr;
return cloneAndCacheForCSSOM(propertySet().getPropertyCSSValue(propertyID).get());
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyValue(const String &propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return propertySet().getPropertyValue(propertyID);
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyPriority(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
return propertySet().propertyIsImportant(propertyID) ? "important" : "";
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyShorthand(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
CSSPropertyID shorthandID = propertySet().getPropertyShorthand(propertyID);
if (!shorthandID)
return String();
return getPropertyNameString(shorthandID);
}
bool AbstractPropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyName)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return false;
return propertySet().isPropertyImplicit(propertyID);
}
void AbstractPropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& exceptionState)
{
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return;
bool important = equalIgnoringCase(priority, "important");
if (!important && !priority.isEmpty())
return;
setPropertyInternal(propertyID, value, important, exceptionState);
}
String AbstractPropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
if (!propertyID)
return String();
willMutate();
String result;
bool changed = propertySet().removeProperty(propertyID, &result);
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
return result;
}
PassRefPtrWillBeRawPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
{
return propertySet().getPropertyCSSValue(propertyID);
}
String AbstractPropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID propertyID)
{
return propertySet().getPropertyValue(propertyID);
}
void AbstractPropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState&)
{
StyleAttributeMutationScope mutationScope(this);
willMutate();
bool changed = propertySet().setProperty(propertyID, value, important, contextStyleSheet());
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
}
CSSValue* AbstractPropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
{
if (!internalValue)
return 0;
// The map is here to maintain the object identity of the CSSValues over multiple invocations.
// FIXME: It is likely that the identity is not important for web compatibility and this code should be removed.
if (!m_cssomCSSValueClones)
m_cssomCSSValueClones = adoptPtrWillBeNoop(new WillBeHeapHashMap<CSSValue*, RefPtrWillBeMember<CSSValue> >);
RefPtrWillBeMember<CSSValue>& clonedValue = m_cssomCSSValueClones->add(internalValue, RefPtrWillBeMember<CSSValue>()).storedValue->value;
if (!clonedValue)
clonedValue = internalValue->cloneForCSSOM();
return clonedValue.get();
}
StyleSheetContents* AbstractPropertySetCSSStyleDeclaration::contextStyleSheet() const
{
CSSStyleSheet* cssStyleSheet = parentStyleSheet();
return cssStyleSheet ? cssStyleSheet->contents() : 0;
}
PassRefPtrWillBeRawPtr<MutableStylePropertySet> AbstractPropertySetCSSStyleDeclaration::copyProperties() const
{
return propertySet().mutableCopy();
}
bool AbstractPropertySetCSSStyleDeclaration::cssPropertyMatches(CSSPropertyID propertyID, const CSSValue* propertyValue) const
{
return propertySet().propertyMatches(propertyID, propertyValue);
}
StyleRuleCSSStyleDeclaration::StyleRuleCSSStyleDeclaration(MutableStylePropertySet& propertySetArg, CSSRule* parentRule)
: PropertySetCSSStyleDeclaration(propertySetArg)
, m_refCount(1)
, m_parentRule(parentRule)
{
m_propertySet->ref();
}
StyleRuleCSSStyleDeclaration::~StyleRuleCSSStyleDeclaration()
{
m_propertySet->deref();
}
void StyleRuleCSSStyleDeclaration::ref()
{
++m_refCount;
}
void StyleRuleCSSStyleDeclaration::deref()
{
ASSERT(m_refCount);
if (!--m_refCount)
delete this;
}
void StyleRuleCSSStyleDeclaration::willMutate()
{
if (m_parentRule && m_parentRule->parentStyleSheet())
m_parentRule->parentStyleSheet()->willMutateRules();
}
void StyleRuleCSSStyleDeclaration::didMutate(MutationType type)
{
if (type == PropertyChanged)
m_cssomCSSValueClones.clear();
// Style sheet mutation needs to be signaled even if the change failed. willMutateRules/didMutateRules must pair.
if (m_parentRule && m_parentRule->parentStyleSheet())
m_parentRule->parentStyleSheet()->didMutateRules();
}
CSSStyleSheet* StyleRuleCSSStyleDeclaration::parentStyleSheet() const
{
return m_parentRule ? m_parentRule->parentStyleSheet() : 0;
}
void StyleRuleCSSStyleDeclaration::reattach(MutableStylePropertySet& propertySet)
{
m_propertySet->deref();
m_propertySet = &propertySet;
m_propertySet->ref();
}
MutableStylePropertySet& InlineCSSStyleDeclaration::propertySet() const
{
return m_parentElement->ensureMutableInlineStyle();
}
void InlineCSSStyleDeclaration::didMutate(MutationType type)
{
if (type == NoChanges)
return;
m_cssomCSSValueClones.clear();
if (!m_parentElement)
return;
m_parentElement->clearMutableInlineStyleIfEmpty();
m_parentElement->setNeedsStyleRecalc(LocalStyleChange);
m_parentElement->invalidateStyleAttribute();
StyleAttributeMutationScope(this).didInvalidateStyleAttr();
}
CSSStyleSheet* InlineCSSStyleDeclaration::parentStyleSheet() const
{
return m_parentElement ? &m_parentElement->document().elementSheet() : 0;
}
void InlineCSSStyleDeclaration::ref()
{
m_parentElement->ref();
}
void InlineCSSStyleDeclaration::deref()
{
m_parentElement->deref();
}
} // namespace WebCore
|
Remove code duplication in AbstractPropertySetCSSStyleDeclaration::setProperty
|
Remove code duplication in AbstractPropertySetCSSStyleDeclaration::setProperty
This code is duplicated between setPropertyInternal and setProperty. We
should de-dupe it so we can add specific optimizations to the property
setting code for things like transform and opacity.
Review URL: https://codereview.chromium.org/214333002
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@170160 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
|
6ef9ad5be55ac313550129b832beb569621f3613
|
common/Array.hpp
|
common/Array.hpp
|
#ifndef _ARRAY_HPP_
#define _ARRAY_HPP_
#include <cstdlib>
#include <algorithm>
template <typename T>
class Array
{
public:
Array() : data(nullptr) {}
Array(size_t size) : data(nullptr) { this->allocate(size); }
Array(const Array &array) : data(nullptr) { this->copy(array); }
Array(Array &&array) : data(nullptr) { this->swap(std::move(array)); }
~Array() { this->deallocate(); }
void allocate(size_t size)
{
this->deallocate();
this->size = size;
this->data = new T [size];
}
void deallocate()
{
if (this->data != nullptr)
{
delete [] this->data;
this->data = nullptr;
this->size = 0;
}
}
void copy(const Array &array)
{
this->allocate(array.size);
std::copy(array.begin(), array.end(), this->data);
}
void swap(Array &&array)
{
std::swap(this->data, array.data);
std::swap(this->size, array.size);
}
Array<T> clone() const
{
Array<T> array;
array.copy(*this);
return array;
}
size_t getSize() const { return this->size; }
T * begin() { return this->data; }
const T * begin() const { return this->begin(); }
T * end() { return this->data + this->size; }
const T * end() const { return this->end(); }
Array & operator = (const Array &array)
{ this->copy(array); return *this; }
Array & operator = (Array &&array)
{ this->swap(array); return *this; }
T & operator [] (size_t index) { return this->data[index]; }
const T & operator [] (size_t index) const { return this->data[index]; }
operator T * () { return this->begin(); }
operator const T * () const { return this->begin(); }
private:
T *data;
size_t size;
};
#endif
|
#ifndef _ARRAY_HPP_
#define _ARRAY_HPP_
#include <cstdlib>
#include <algorithm>
template <typename T>
class Array
{
public:
Array() : data(nullptr) {}
Array(size_t size) : data(nullptr) { this->allocate(size); }
Array(const Array &array) : data(nullptr) { this->copy(array); }
Array(Array &&array) : data(nullptr) { this->swap(std::move(array)); }
~Array() { this->deallocate(); }
void allocate(size_t size)
{
this->deallocate();
this->size = size;
this->data = new T [size];
}
void deallocate()
{
if (this->data != nullptr)
{
delete [] this->data;
this->data = nullptr;
this->size = 0;
}
}
void copy(const Array &array)
{
this->allocate(array.size);
std::copy(array.begin(), array.end(), this->data);
}
void swap(Array &&array)
{
std::swap(this->data, array.data);
std::swap(this->size, array.size);
}
Array<T> clone() const
{
Array<T> array;
array.copy(*this);
return array;
}
size_t getSize() const { return this->size; }
T * begin() { return this->data; }
const T * begin() const { return this->data; }
T * end() { return this->data + this->size; }
const T * end() const { return this->data + this->size; }
Array & operator = (const Array &array)
{ this->copy(array); return *this; }
Array & operator = (Array &&array)
{ this->swap(array); return *this; }
T & operator [] (size_t index) { return this->data[index]; }
const T & operator [] (size_t index) const { return this->data[index]; }
operator T * () { return this->begin(); }
operator const T * () const { return this->begin(); }
private:
T *data;
size_t size;
};
#endif
|
Fix wrong function call caused to recursion
|
Fix wrong function call caused to recursion
|
C++
|
mit
|
CltKitakami/MyLib,CltKitakami/MyLib,CltKitakami/MyLib
|
4de0c64a9ce16ebac5adedbd20a3c8a58d873d73
|
PWGLF/SPECTRA/PiKaPr/TPC/rTPC/AddTaskPPvsMult.C
|
PWGLF/SPECTRA/PiKaPr/TPC/rTPC/AddTaskPPvsMult.C
|
#if !defined (__CINT__) || defined (__CLING__)
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskPPvsMult.h"
#include "AliAnalysisFilter.h"
#include "TInterpreter.h"
#include "TChain.h"
#include <TString.h>
#include <TList.h>
#endif
AliAnalysisTaskPPvsMult* AddTaskPPvsMult(
Bool_t AnalysisMC = kFALSE,
//// Int_t system =1, // 0 for pp and 1 for Pb-Pb
Bool_t PostCalib = kFALSE,
//// Bool_t LowpT = kFALSE,
//// Bool_t MakePid = kFALSE,
const char* Period = "16g",
int TrkCutMode = 0
)
{
// get the manager via the static access member. since it's static, you don't need
// an instance of the class to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC");
AliESDtrackCuts* esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
trackFilterTPC->AddCuts(esdTrackCutsTPC);
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
//fileName += Form(":%.2f-%.2f",minCent,maxCent); // create a subfolder in the file
fileName += ":Output"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskPPvsMult* task = new AliAnalysisTaskPPvsMult("taskHighPtDeDxpp");
if(!task) return 0x0;
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// task->SelectCollisionCandidates(AliVEvent::kAnyINT);
task->SetAnalysisType(type);
task->SetAnalysisMC(AnalysisMC);
///// task->SetAddLowPt(LowpT);
task->SetPeriod(Period);
// if(system==1){
// task->SetAnalysisPbPb(kTRUE);
// task->SetMinCent(0.0);
// task->SetMaxCent(90.0);
// task->SetCentralityEstimator(centralityEstimator);
// }
// else
// task->SetAnalysisPbPb(kFALSE);
task->SetNcl(70);
task->SetDebugLevel(0);
task->SetEtaCut(0.8);
// task->SetVtxCut(10.0);
// task->SetTrigger(AliVEvent::kINT7);
// task->SetPileUpRej(ispileuprej);
//Set Filtesr
task->SetTrackFilterTPC(trackFilterTPC);
// task->SetStoreMcIn(AnalysisMC); // def: kFALSE
task->SetAnalysisTask(PostCalib);
/// task->SetAnalysisPID(MakePid);
task->SetTrackCutsSystVars(TrkCutMode);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer("MyOutputContainer", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
|
#if !defined (__CINT__) || defined (__CLING__)
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskPPvsMult.h"
#include "AliAnalysisFilter.h"
#include "TInterpreter.h"
#include "TChain.h"
#include <TString.h>
#include <TList.h>
#endif
AliAnalysisTaskPPvsMult* AddTaskPPvsMult(
Bool_t AnalysisMC = kFALSE,
//// Int_t system =1, // 0 for pp and 1 for Pb-Pb
Bool_t PostCalib = kFALSE,
//// Bool_t LowpT = kFALSE,
//// Bool_t MakePid = kFALSE,
const char* Period = "16g",
int Ncl = 70,
int TrkCutMode = 0
)
{
// get the manager via the static access member. since it's static, you don't need
// an instance of the class to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC");
AliESDtrackCuts* esdTrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
trackFilterTPC->AddCuts(esdTrackCutsTPC);
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
//fileName += Form(":%.2f-%.2f",minCent,maxCent); // create a subfolder in the file
fileName += ":Output"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskPPvsMult* task = new AliAnalysisTaskPPvsMult("taskHighPtDeDxpp");
if(!task) return 0x0;
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// task->SelectCollisionCandidates(AliVEvent::kAnyINT);
task->SetAnalysisType(type);
task->SetAnalysisMC(AnalysisMC);
///// task->SetAddLowPt(LowpT);
task->SetPeriod(Period);
// if(system==1){
// task->SetAnalysisPbPb(kTRUE);
// task->SetMinCent(0.0);
// task->SetMaxCent(90.0);
// task->SetCentralityEstimator(centralityEstimator);
// }
// else
// task->SetAnalysisPbPb(kFALSE);
task->SetNcl(Ncl);
task->SetDebugLevel(0);
task->SetEtaCut(0.8);
// task->SetVtxCut(10.0);
// task->SetTrigger(AliVEvent::kINT7);
// task->SetPileUpRej(ispileuprej);
//Set Filtesr
task->SetTrackFilterTPC(trackFilterTPC);
// task->SetStoreMcIn(AnalysisMC); // def: kFALSE
task->SetAnalysisTask(PostCalib);
/// task->SetAnalysisPID(MakePid);
task->SetTrackCutsSystVars(TrkCutMode);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer("MyOutputContainer", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
|
Add variable to change Ncl
|
Add variable to change Ncl
|
C++
|
bsd-3-clause
|
pchrista/AliPhysics,fcolamar/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,amaringarcia/AliPhysics,fbellini/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,fbellini/AliPhysics,lcunquei/AliPhysics,fcolamar/AliPhysics,fbellini/AliPhysics,nschmidtALICE/AliPhysics,hzanoli/AliPhysics,AMechler/AliPhysics,AMechler/AliPhysics,amaringarcia/AliPhysics,rbailhac/AliPhysics,hzanoli/AliPhysics,fcolamar/AliPhysics,lcunquei/AliPhysics,alisw/AliPhysics,nschmidtALICE/AliPhysics,pchrista/AliPhysics,hzanoli/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,mpuccio/AliPhysics,fcolamar/AliPhysics,fbellini/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,fcolamar/AliPhysics,AMechler/AliPhysics,victor-gonzalez/AliPhysics,lcunquei/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,alisw/AliPhysics,lcunquei/AliPhysics,victor-gonzalez/AliPhysics,fbellini/AliPhysics,alisw/AliPhysics,rihanphys/AliPhysics,mpuccio/AliPhysics,rihanphys/AliPhysics,amaringarcia/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,hzanoli/AliPhysics,rihanphys/AliPhysics,hzanoli/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,rbailhac/AliPhysics,fbellini/AliPhysics,AMechler/AliPhysics,mpuccio/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,hzanoli/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,fcolamar/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,pchrista/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,mpuccio/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,lcunquei/AliPhysics,fbellini/AliPhysics,rbailhac/AliPhysics,rbailhac/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,victor-gonzalez/AliPhysics,adriansev/AliPhysics,nschmidtALICE/AliPhysics,adriansev/AliPhysics,fcolamar/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics
|
187f9f2de7765f29dafdfef05f6848a218892c99
|
hts_AdapterTrimmer/src/hts_AdapterTrimmer.cpp
|
hts_AdapterTrimmer/src/hts_AdapterTrimmer.cpp
|
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include <fstream>
#include "ioHandler.h"
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
#include <map>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include "hts_AdapterTrimmer.h"
namespace
{
const size_t SUCCESS = 0;
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
namespace bi = boost::iostreams;
int main(int argc, char** argv)
{
const std::string program_name = "adapter-trimmer";
std::string app_description =
"Adapter Trimmer, trims off adapters by first overlapping paired-end reads and\n";
app_description += " trimming off overhangs which by definition are adapter sequence in standard\n";
app_description += " libraries. [SE Reads are currently not supported for adapter trimming].";
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description standard = setStandardOptions();
// version|v ; help|h ; notes|N ; stats-file|L ; append-stats-file|A
po::options_description input = setInputOptions();
// read1-input|1 ; read2-input|2 ; singleend-input|U
// tab-input|T ; interleaved-input|I ; from-stdin|S
po::options_description output = setOutputOptions(program_name);
// force|F ; prefix|p ; gzip-output,g ; fastq-output|f
// tab-output|t ; interleaved-output|i ; unmapped-output|u ; to-stdout,O
po::options_description desc("Application Specific Options");
setDefaultParamsCutting(desc);
// no-orphans|n ; stranded|s ; min-length|m
setDefaultParamsOverlapping(desc);
// kmer|k ; kmer-offset|r ; max-mismatch-errorDensity|x
// check-lengths|c ; min-overlap|o
desc.add_options()
("no-fixbases,X", po::bool_switch()->default_value(false), "after trimming adapter, DO NOT use consensus sequence of paired reads, only trims adapter sequence");
desc.add_options()
("adapter-sequence,a", po::value<std::string>()->default_value("AGATCGGAAGAGCACACGTCTGAACTCCAGTCA"), "Primer sequence to trim in SE adapter trimming, default is truseq ht primer sequence");
po::options_description cmdline_options;
cmdline_options.add(standard).add(input).add(output).add(desc);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, cmdline_options), vm); // can throw
version_or_help(program_name, app_description, cmdline_options, vm);
po::notify(vm); // throws on error, so do after help in case
std::string statsFile(vm["stats-file"].as<std::string>());
std::string prefix(vm["prefix"].as<std::string>());
std::shared_ptr<OutputWriter> pe = nullptr;
std::shared_ptr<OutputWriter> se = nullptr;
AdapterCounters counters(statsFile, vm["append-stats-file"].as<bool>(), program_name, vm["notes"].as<std::string>());
outputWriters(pe, se, vm["fastq-output"].as<bool>(), vm["tab-output"].as<bool>(), vm["interleaved-output"].as<bool>(), vm["unmapped-output"].as<bool>(), vm["force"].as<bool>(), vm["gzip-output"].as<bool>(), vm["to-stdout"].as<bool>(), prefix );
if(vm.count("read1-input")) {
if (!vm.count("read2-input")) {
throw std::runtime_error("must specify both read1 and read2 input files.");
}
auto read1_files = vm["read1-input"].as<std::vector<std::string> >();
auto read2_files = vm["read2-input"].as<std::vector<std::string> >();
if (read1_files.size() != read2_files.size()) {
throw std::runtime_error("must have same number of input files for read1 and read2");
}
for(size_t i = 0; i < read1_files.size(); ++i) {
bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle};
bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle};
InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2);
helper_adapterTrimmer(ifp, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if(vm.count("singleend-input")) {
auto read_files = vm["singleend-input"].as<std::vector<std::string> >();
for (auto file : read_files) {
bi::stream<bi::file_descriptor_source> sef{ check_open_r(file), bi::close_handle};
InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(sef);
//JUST WRITE se read out - no way to overlap
helper_adapterTrimmer(ifs, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if(vm.count("tab-input")) {
auto read_files = vm["tab-input"].as<std::vector<std::string> > ();
for (auto file : read_files) {
bi::stream<bi::file_descriptor_source> tabin{ check_open_r(file), bi::close_handle};
InputReader<ReadBase, TabReadImpl> ift(tabin);
helper_adapterTrimmer(ift, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if (vm.count("interleaved-input")) {
auto read_files = vm["interleaved-input"].as<std::vector<std::string > >();
for (auto file : read_files) {
bi::stream<bi::file_descriptor_source> inter{ check_open_r(file), bi::close_handle};
InputReader<PairedEndRead, InterReadImpl> ifp(inter);
helper_adapterTrimmer(ifp, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if (vm.count("from-stdin")) {
bi::stream<bi::file_descriptor_source> tabin {fileno(stdin), bi::close_handle};
InputReader<ReadBase, TabReadImpl> ift(tabin);
helper_adapterTrimmer(ift, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
counters.write_out();
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
version_or_help(program_name, app_description, cmdline_options, vm, true);
return ERROR_IN_COMMAND_LINE;
}
}
catch(std::exception& e)
{
std::cerr << "\n\tUnhandled Exception: "
<< e.what() << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return SUCCESS;
}
|
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <vector>
#include <fstream>
#include "ioHandler.h"
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
#include <map>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include "hts_AdapterTrimmer.h"
namespace
{
const size_t SUCCESS = 0;
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;
} // namespace
namespace bi = boost::iostreams;
int main(int argc, char** argv)
{
const std::string program_name = "adapter-trimmer";
std::string app_description =
"Adapter Trimmer, trims off adapters by first overlapping paired-end reads and\n";
app_description += " trimming off overhangs which by definition are adapter sequence in standard\n";
app_description += " libraries. SE Reads are trimmed by overlapping the adapter-sequence and trimming off the overlap.";
try
{
/** Define and parse the program options
*/
namespace po = boost::program_options;
po::options_description standard = setStandardOptions();
// version|v ; help|h ; notes|N ; stats-file|L ; append-stats-file|A
po::options_description input = setInputOptions();
// read1-input|1 ; read2-input|2 ; singleend-input|U
// tab-input|T ; interleaved-input|I ; from-stdin|S
po::options_description output = setOutputOptions(program_name);
// force|F ; prefix|p ; gzip-output,g ; fastq-output|f
// tab-output|t ; interleaved-output|i ; unmapped-output|u ; to-stdout,O
po::options_description desc("Application Specific Options");
setDefaultParamsCutting(desc);
// no-orphans|n ; stranded|s ; min-length|m
setDefaultParamsOverlapping(desc);
// kmer|k ; kmer-offset|r ; max-mismatch-errorDensity|x
// check-lengths|c ; min-overlap|o
desc.add_options()
("no-fixbases,X", po::bool_switch()->default_value(false), "after trimming adapter, DO NOT use consensus sequence of paired reads, only trims adapter sequence");
desc.add_options()
("adapter-sequence,a", po::value<std::string>()->default_value("AGATCGGAAGAGCACACGTCTGAACTCCAGTCA"), "Primer sequence to trim in SE adapter trimming, default is truseq ht primer sequence");
po::options_description cmdline_options;
cmdline_options.add(standard).add(input).add(output).add(desc);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, cmdline_options), vm); // can throw
version_or_help(program_name, app_description, cmdline_options, vm);
po::notify(vm); // throws on error, so do after help in case
std::string statsFile(vm["stats-file"].as<std::string>());
std::string prefix(vm["prefix"].as<std::string>());
std::shared_ptr<OutputWriter> pe = nullptr;
std::shared_ptr<OutputWriter> se = nullptr;
AdapterCounters counters(statsFile, vm["append-stats-file"].as<bool>(), program_name, vm["notes"].as<std::string>());
outputWriters(pe, se, vm["fastq-output"].as<bool>(), vm["tab-output"].as<bool>(), vm["interleaved-output"].as<bool>(), vm["unmapped-output"].as<bool>(), vm["force"].as<bool>(), vm["gzip-output"].as<bool>(), vm["to-stdout"].as<bool>(), prefix );
if(vm.count("read1-input")) {
if (!vm.count("read2-input")) {
throw std::runtime_error("must specify both read1 and read2 input files.");
}
auto read1_files = vm["read1-input"].as<std::vector<std::string> >();
auto read2_files = vm["read2-input"].as<std::vector<std::string> >();
if (read1_files.size() != read2_files.size()) {
throw std::runtime_error("must have same number of input files for read1 and read2");
}
for(size_t i = 0; i < read1_files.size(); ++i) {
bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle};
bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle};
InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2);
helper_adapterTrimmer(ifp, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if(vm.count("singleend-input")) {
auto read_files = vm["singleend-input"].as<std::vector<std::string> >();
for (auto file : read_files) {
bi::stream<bi::file_descriptor_source> sef{ check_open_r(file), bi::close_handle};
InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(sef);
//JUST WRITE se read out - no way to overlap
helper_adapterTrimmer(ifs, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if(vm.count("tab-input")) {
auto read_files = vm["tab-input"].as<std::vector<std::string> > ();
for (auto file : read_files) {
bi::stream<bi::file_descriptor_source> tabin{ check_open_r(file), bi::close_handle};
InputReader<ReadBase, TabReadImpl> ift(tabin);
helper_adapterTrimmer(ift, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if (vm.count("interleaved-input")) {
auto read_files = vm["interleaved-input"].as<std::vector<std::string > >();
for (auto file : read_files) {
bi::stream<bi::file_descriptor_source> inter{ check_open_r(file), bi::close_handle};
InputReader<PairedEndRead, InterReadImpl> ifp(inter);
helper_adapterTrimmer(ifp, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
}
if (vm.count("from-stdin")) {
bi::stream<bi::file_descriptor_source> tabin {fileno(stdin), bi::close_handle};
InputReader<ReadBase, TabReadImpl> ift(tabin);
helper_adapterTrimmer(ift, pe, se, counters, vm["max-mismatch-errorDensity"].as<double>(), vm["max-mismatch"].as<size_t>(), vm["min-overlap"].as<size_t>(), vm["stranded"].as<bool>(), vm["min-length"].as<size_t>(), vm["check-lengths"].as<size_t>(), vm["kmer"].as<size_t>(), vm["kmer-offset"].as<size_t>(), vm["no-orphans"].as<bool>(), vm["no-fixbases"].as<bool>(), vm["adapter-sequence"].as<std::string>() );
}
counters.write_out();
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
version_or_help(program_name, app_description, cmdline_options, vm, true);
return ERROR_IN_COMMAND_LINE;
}
}
catch(std::exception& e)
{
std::cerr << "\n\tUnhandled Exception: "
<< e.what() << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
return SUCCESS;
}
|
change adapter trimmer help message
|
change adapter trimmer help message
|
C++
|
apache-2.0
|
ibest/HTStream,ibest/HTStream
|
9ce5177644d10c1c2a4e453bc60fb9232740c405
|
igvc_gazebo/nodes/sim_color_detector/main.cpp
|
igvc_gazebo/nodes/sim_color_detector/main.cpp
|
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/mat.hpp>
#include <fstream>
#include <iostream>
#include <igvc_utils/NodeUtils.hpp>
ros::Publisher img_pub;
void handle_image(const sensor_msgs::ImageConstPtr& msg) {
cv_bridge::CvImagePtr cv_ptr;
cv::Mat frame;
try {
cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("CV-Bridge error: %s", e.what());
return;
}
frame = cv_ptr->image;
cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0));
const int min_b_line = 120;
const int max_b_line = 140;
const int min_g_line = 0;
const int max_g_line = 20;
const int min_r_line = 70;
const int max_r_line = 85;
const int max_b_obstacle_black = 45;
const int max_g_obstacle_black = 45;
const int max_r_obstacle_black = 45;
const int max_g_obstacle_orange = 160;
const int min_r_obstacle_orange = 240;
const int min_b_obstacle_white = 230;
const int min_g_obstacle_white = 230;
const int min_r_obstacle_white = 230;
const int white_color = 255;
const int black_color = 0;
for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
for(int columnCount=0; columnCount<frame.cols; ++columnCount) {
cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));
if (int(color.val[0]) > min_b_line && int(color.val[0]) < max_b_line && int(color.val[1]) >= min_g_line && int(color.val[1]) < max_g_line && int(color.val[2]) > min_r_line && int(color.val[2]) < max_r_line) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else if (int(color.val[0]) < max_b_obstacle_black && int(color.val[1]) < max_g_obstacle_black && int(color.val[2]) < max_r_obstacle_black) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else if (int(color.val[1]) < max_g_obstacle_orange && int(color.val[2]) > min_r_obstacle_orange) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else if (int(color.val[0]) > min_b_obstacle_white && int(color.val[1]) > min_g_obstacle_white && int(color.val[2]) > min_r_obstacle_white) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else {
output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
}
}
}
sensor_msgs::Image outmsg;
outmsg.header = msg->header;
cv_ptr->image = output;
cv_ptr->encoding = "mono8";
cv_ptr->toImageMsg(outmsg);
img_pub.publish(outmsg);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "sim_color_detector");
ros::NodeHandle nh;
ros::NodeHandle pNh("~");
std::string topic_name;
//pNh.param("image_topic", topic_name, std::string("/center_cam/image_raw"));
igvc::param(pNh, "image_topic", topic_name, std::string("/center_cam/image_raw"));
img_pub = nh.advertise<sensor_msgs::Image>("/usb_cam_center/detected", 1);
ros::Subscriber img_sub = nh.subscribe(topic_name, 1, handle_image);
ros::spin();
return 0;
}
|
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/mat.hpp>
#include <fstream>
#include <iostream>
#include <igvc_utils/NodeUtils.hpp>
ros::Publisher img_pub_lines;
ros::Publisher img_pub_barrels;
sensor_msgs::Image outmsg_lines;
sensor_msgs::Image outmsg_barrels;
/*
* Responsible for detecting the lines (currently set to a purple color) and
* illuminating them as white (and setting all other pixels to black).
*/
void handle_image_lines(const sensor_msgs::ImageConstPtr& msg) {
cv_bridge::CvImagePtr cv_ptr;
cv::Mat frame;
try {
cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("CV-Bridge error: %s", e.what());
return;
}
frame = cv_ptr->image;
cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0));
// Set color ranges (8 bit BGR) for line detection
const int min_b = 120;
const int max_b = 140;
const int min_g = 0;
const int max_g = 20;
const int min_r = 70;
const int max_r = 85;
const int white_color = 255;
const int black_color = 0;
for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
for(int columnCount=0; columnCount<frame.cols; ++columnCount) {
cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));
if (int(color.val[0]) > min_b && int(color.val[0]) < max_b && int(color.val[1]) >= min_g && int(color.val[1]) < max_g && int(color.val[2]) > min_r && int(color.val[2]) < max_r) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else {
output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
}
}
}
sensor_msgs::Image outmsg;
outmsg.header = msg->header;
cv_ptr->image = output;
cv_ptr->encoding = "mono8";
cv_ptr->toImageMsg(outmsg);
outmsg_lines = outmsg;
}
/*
* Responsible for detecting the barrels (white and orange components) and
* illuminating them as white (and setting all other pixels to black).
*/
void handle_image_barrels(const sensor_msgs::ImageConstPtr& msg) {
cv_bridge::CvImagePtr cv_ptr;
cv::Mat frame;
try {
cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
} catch (cv_bridge::Exception& e) {
ROS_ERROR("CV-Bridge error: %s", e.what());
return;
}
frame = cv_ptr->image;
cv::Mat output(frame.rows, frame.cols, CV_8UC1, cv::Scalar::all(0));
// Set color ranges (8 bit BGR) for barrel detection
// Detects the black base of the barrel
const int max_b_obstacle_black = 45;
const int max_g_obstacle_black = 45;
const int max_r_obstacle_black = 45;
// Detects the orange parts of the barrel
const int max_g_obstacle_orange = 160;
const int min_r_obstacle_orange = 240;
// Detects the white parts of the barrel
const int min_b_obstacle_white = 230;
const int min_g_obstacle_white = 230;
const int min_r_obstacle_white = 230;
const int white_color = 255;
const int black_color = 0;
for(int rowCount=0; rowCount<frame.rows; ++rowCount) {
for(int columnCount=0; columnCount<frame.cols; ++columnCount) {
cv::Vec3b color = frame.at<cv::Vec3b>(cv::Point(columnCount,rowCount));
if (int(color.val[0]) < max_b_obstacle_black && int(color.val[1]) < max_g_obstacle_black && int(color.val[2]) < max_r_obstacle_black) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else if (int(color.val[1]) < max_g_obstacle_orange && int(color.val[2]) > min_r_obstacle_orange) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else if (int(color.val[0]) > min_b_obstacle_white && int(color.val[1]) > min_g_obstacle_white && int(color.val[2]) > min_r_obstacle_white) {
output.at<uchar>(cv::Point(columnCount, rowCount)) = white_color;
} else {
output.at<uchar>(cv::Point(columnCount, rowCount)) = black_color;
}
}
}
sensor_msgs::Image outmsg;
outmsg.header = msg->header;
cv_ptr->image = output;
cv_ptr->encoding = "mono8";
cv_ptr->toImageMsg(outmsg);
outmsg_barrels = outmsg;
}
/*
* Takes the most recent messages from the handle_image_lines and
* handle_image_barrels functions and publishes them once triggered
* by a a ros::Timer
*/
void publish(const ros::TimerEvent&)
{
img_pub_barrels.publish(outmsg_barrels);
img_pub_lines.publish(outmsg_lines);
}
/*
* Responsible for setting up the publishers and triggering the functions to
* update the detected black-and-white images
*/
int main(int argc, char** argv) {
ros::init(argc, argv, "sim_color_detector");
// LINES
ros::NodeHandle nh_lines;
ros::NodeHandle pNh_lines("~");
std::string topic_name_lines;
igvc::param(pNh_lines, "image_topic", topic_name_lines, std::string("/center_cam/image_raw"));
img_pub_lines = nh_lines.advertise<sensor_msgs::Image>("/usb_cam_center/detected_lines", 1);
ros::Subscriber img_sub_lines = nh_lines.subscribe(topic_name_lines, 1, handle_image_lines);
// BARRELS
ros::NodeHandle nh_barrels;
ros::NodeHandle pNh_barrels("~");
std::string topic_name_barrels;
igvc::param(pNh_barrels, "image_topic", topic_name_barrels, std::string("/center_cam/image_raw"));
img_pub_barrels = nh_barrels.advertise<sensor_msgs::Image>("/usb_cam_center/detected_barrels", 1);
ros::Subscriber img_sub_barrels = nh_barrels.subscribe(topic_name_barrels, 1, handle_image_barrels);
ros::NodeHandle nh;
// Will call publish to update the published topics -> Set the publishing rate here
ros::Timer timer = nh.createTimer(ros::Duration(1.0/30), publish);
ros::spin();
return 0;
}
|
Split the output into two different nodes (one for the line detection, one for the barrel detection). Implemented a ROS Timer that dictates the frequency of publishing for the two nodes. Added some documentation.
|
Split the output into two different nodes (one for the line detection, one for the barrel detection). Implemented a ROS Timer that dictates the frequency of publishing for the two nodes. Added some documentation.
|
C++
|
mit
|
RoboJackets/igvc-software,RoboJackets/igvc-software,RoboJackets/igvc-software,RoboJackets/igvc-software
|
3fc2c5f26eb022f06c863fcb7d2473ad1af1470f
|
Rendering/Testing/Cxx/TestPriorityStreaming.cxx
|
Rendering/Testing/Cxx/TestPriorityStreaming.cxx
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestPriorityStreaming.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Test of the priority streaming support in VTK
#include "vtkContourFilter.h"
#include "vtkImageMandelbrotSource.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTesting.h"
#include "vtkXMLImageDataReader.h"
#include "vtkXMLImageDataWriter.h"
#include "vtkXMLPImageDataWriter.h"
#include "vtksys/SystemTools.hxx"
//---------------------------------------------------------------------------
int TestPriorityStreaming(int argc, char *argv[])
{
// parse the arguments
vtkSmartPointer<vtkTesting> test =
vtkSmartPointer<vtkTesting>::New();
int cc;
for ( cc = 1; cc < argc; cc ++ )
{
test->AddArgument(argv[cc]);
}
// first create a data file containing many pieces
// first we want to create some data, a 256 cubed Mandelbrot src
vtkSmartPointer<vtkImageMandelbrotSource> Mandelbrot =
vtkSmartPointer<vtkImageMandelbrotSource>::New();
Mandelbrot->SetWholeExtent(0,127,0,127,0,127);
Mandelbrot->SetOriginCX(-1.75,-1.25,-1,0);
Mandelbrot->Update();
// write out the image data file into many pieces
vtkSmartPointer<vtkXMLImageDataWriter> iw =
vtkSmartPointer<vtkXMLImageDataWriter>::New();
iw->SetInputConnection(Mandelbrot->GetOutputPort());
vtkstd::string fname = test->GetTempDirectory();
fname += "/StreamTestFile.vti";
iw->SetFileName(fname.c_str());
iw->SetNumberOfPieces(64);
iw->Write();
// create a reader
vtkSmartPointer<vtkXMLImageDataReader> ir =
vtkSmartPointer<vtkXMLImageDataReader>::New();
ir->SetFileName(fname.c_str());
vtkSmartPointer<vtkContourFilter> contour =
vtkSmartPointer<vtkContourFilter>::New();
contour->SetInputConnection(ir->GetOutputPort());
contour->SetValue(0,50);
// lets get some priorities :-)
vtkInformationVector *outVec =
contour->GetExecutive()->GetOutputInformation();
vtkInformation *outInfo = outVec->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
iw->GetNumberOfPieces());
// build the UE request
vtkSmartPointer<vtkInformation> UpdateExtentRequest =
vtkSmartPointer<vtkInformation>::New();
UpdateExtentRequest->Set
(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT());
UpdateExtentRequest->Set(vtkExecutive::FORWARD_DIRECTION(),
vtkExecutive::RequestUpstream);
UpdateExtentRequest->Set(vtkExecutive::ALGORITHM_BEFORE_FORWARD(), 1);
UpdateExtentRequest->Set(vtkExecutive::FROM_OUTPUT_PORT(), 0);
// build the UEInfo request
vtkSmartPointer<vtkInformation> UEInfoRequest =
vtkSmartPointer<vtkInformation>::New();
UEInfoRequest->Set
(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT_INFORMATION());
UEInfoRequest->Set(vtkExecutive::FORWARD_DIRECTION(),
vtkExecutive::RequestUpstream);
UEInfoRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
UEInfoRequest->Set(vtkExecutive::FROM_OUTPUT_PORT(), 0);
// store the in and out info
vtkStreamingDemandDrivenPipeline *sdd =
vtkStreamingDemandDrivenPipeline::SafeDownCast(contour->GetExecutive());
sdd->UpdateInformation();
vtkInformationVector **inVec =
contour->GetExecutive()->GetInputInformation();
int piece;
double *priority = new double [iw->GetNumberOfPieces()];
for (piece = 0; piece < iw->GetNumberOfPieces(); piece++)
{
outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
piece);
contour->GetExecutive()->
ProcessRequest(UpdateExtentRequest, inVec, outVec);
// get the ue info
contour->GetExecutive()->
ProcessRequest(UEInfoRequest, inVec, outVec);
// get the priority
double p = outVec->GetInformationObject(0)->
Get(vtkStreamingDemandDrivenPipeline::PRIORITY());
//cerr << piece << " " << p << endl;
priority[piece] = p;
}
if (iw->GetNumberOfPieces() != 64 ||
priority[36] != 0.0 ||
priority[37] != 1.0)
{
delete [] priority;
// Leave file around in case somebody wants to look at it
// after the failed test...
cerr << "Bad results for priority streaming test\n";
return 1;
}
delete [] priority;
// Delete the file since the test passed:
vtksys::SystemTools::RemoveFile(fname.c_str());
return 0;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestPriorityStreaming.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME Test the priority streaming support in VTK well.
#include "vtkActor.h"
#include "vtkArrayCalculator.h"
#include "vtkCamera.h"
#include "vtkClipDataSet.h"
#include "vtkContourFilter.h"
#include "vtkDataSetMapper.h"
#include "vtkIdentityTransform.h"
#include "vtkImageMandelbrotSource.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkPlane.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTesting.h"
#include "vtkXMLImageDataReader.h"
#include "vtkXMLImageDataWriter.h"
#include "vtkXMLPImageDataWriter.h"
#include "vtksys/SystemTools.hxx"
//---------------------------------------------------------------------------
int TestPriorityStreaming(int argc, char *argv[])
{
// parse the arguments
vtkSmartPointer<vtkTesting> test =
vtkSmartPointer<vtkTesting>::New();
int cc;
for ( cc = 1; cc < argc; cc ++ )
{
test->AddArgument(argv[cc]);
}
// first create a data file containing many pieces
// first we want to create some data, a 256 cubed Mandelbrot src
vtkSmartPointer<vtkImageMandelbrotSource> Mandelbrot =
vtkSmartPointer<vtkImageMandelbrotSource>::New();
Mandelbrot->SetWholeExtent(0,127,0,127,0,127);
Mandelbrot->SetOriginCX(-1.75,-1.25,-1,0);
Mandelbrot->Update();
// write out the image data file into many pieces
vtkSmartPointer<vtkXMLImageDataWriter> iw =
vtkSmartPointer<vtkXMLImageDataWriter>::New();
iw->SetInputConnection(Mandelbrot->GetOutputPort());
vtkstd::string fname = test->GetTempDirectory();
fname += "/StreamTestFile.vti";
iw->SetFileName(fname.c_str());
iw->SetNumberOfPieces(64);
iw->Write();
// create a reader
vtkSmartPointer<vtkXMLImageDataReader> ir =
vtkSmartPointer<vtkXMLImageDataReader>::New();
ir->SetFileName(fname.c_str());
vtkSmartPointer<vtkContourFilter> contour =
vtkSmartPointer<vtkContourFilter>::New();
contour->SetInputConnection(ir->GetOutputPort());
contour->SetValue(0,50);
// lets get some priorities :-)
vtkInformationVector *outVec =
contour->GetExecutive()->GetOutputInformation();
vtkInformation *outInfo = outVec->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
iw->GetNumberOfPieces());
// build the UE request
vtkSmartPointer<vtkInformation> UpdateExtentRequest =
vtkSmartPointer<vtkInformation>::New();
UpdateExtentRequest->Set
(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT());
UpdateExtentRequest->Set(vtkExecutive::FORWARD_DIRECTION(),
vtkExecutive::RequestUpstream);
UpdateExtentRequest->Set(vtkExecutive::ALGORITHM_BEFORE_FORWARD(), 1);
UpdateExtentRequest->Set(vtkExecutive::FROM_OUTPUT_PORT(), 0);
// build the UEInfo request
vtkSmartPointer<vtkInformation> UEInfoRequest =
vtkSmartPointer<vtkInformation>::New();
UEInfoRequest->Set
(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT_INFORMATION());
UEInfoRequest->Set(vtkExecutive::FORWARD_DIRECTION(),
vtkExecutive::RequestUpstream);
UEInfoRequest->Set(vtkExecutive::ALGORITHM_AFTER_FORWARD(), 1);
UEInfoRequest->Set(vtkExecutive::FROM_OUTPUT_PORT(), 0);
// store the in and out info
vtkStreamingDemandDrivenPipeline *sdd =
vtkStreamingDemandDrivenPipeline::SafeDownCast(contour->GetExecutive());
sdd->UpdateInformation();
vtkInformationVector **inVec =
contour->GetExecutive()->GetInputInformation();
int piece;
double *priority = new double [iw->GetNumberOfPieces()];
for (piece = 0; piece < iw->GetNumberOfPieces(); piece++)
{
outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
piece);
contour->GetExecutive()->
ProcessRequest(UpdateExtentRequest, inVec, outVec);
// get the ue info
contour->GetExecutive()->
ProcessRequest(UEInfoRequest, inVec, outVec);
// get the priority
double p = outVec->GetInformationObject(0)->
Get(vtkStreamingDemandDrivenPipeline::PRIORITY());
//cerr << piece << " " << p << endl;
priority[piece] = p;
}
if (iw->GetNumberOfPieces() != 64 ||
priority[36] != 0.0 ||
priority[37] != 1.0)
{
delete [] priority;
// Leave file around in case somebody wants to look at it
// after the failed test...
cerr << "Bad results for priority streaming test. "
<< "Contour didn't reject/accept pieces correctly.\n";
return 1;
}
delete [] priority;
//--------------------------------------------------------------------------
// Now test meta-information persistance.
// Meta information is either about the geometry (GI), or about
// the attribute ranges (AI).
//
// Filters reject pieces based on valid meta-information.
// Filters only pass through meta-information, when they are
// known not to modify it. Calc filter can modify either.
//
// Downstream of a filter that stops information, downstream filters can not
// reject any new pieces.
//
//READER -> CALC -> CONTOUR
//SETSGI STOPGI Can not reject(noR)
vtkSmartPointer<vtkArrayCalculator> calc_A =
vtkSmartPointer<vtkArrayCalculator>::New();
calc_A->SetInputConnection(ir->GetOutputPort());
calc_A->SetFunction("1");
vtkSmartPointer<vtkContourFilter> contour_A =
vtkSmartPointer<vtkContourFilter>::New();
contour_A->SetInputConnection(calc_A->GetOutputPort());
contour_A->SetValue(0,50);
vtkStreamingDemandDrivenPipeline* sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(contour_A->GetExecutive());
for (int i = 0; i < 64; i++)
{
double lpriority = 1.0;
sddp->SetUpdateExtent(0, i, 64, 0);
lpriority = sddp->ComputePriority();
if (lpriority != 1.0)
{
cerr << "Bad results for priority streaming test. "
<< "Should not be able to reject based on attribute ranges." << endl;
return 1;
}
}
//READER -> CALC -> CLIP
//SETSAI STOPAI Can not reject(noR)
vtkSmartPointer<vtkArrayCalculator> calc_B =
vtkSmartPointer<vtkArrayCalculator>::New();
calc_B->SetInputConnection(ir->GetOutputPort());
calc_B->SetFunction("1");
vtkSmartPointer<vtkClipDataSet> clip_B =
vtkSmartPointer<vtkClipDataSet>::New();
clip_B->SetInputConnection(calc_B->GetOutputPort());
vtkSmartPointer<vtkPlane> plane_B =
vtkSmartPointer<vtkPlane>::New();
plane_B->SetNormal(0,1,0);
plane_B->SetOrigin(0,0,0);
clip_B->SetClipFunction(plane_B);
sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(clip_B->GetExecutive());
for (int i = 0; i < 64; i++)
{
double lpriority = 1.0;
sddp->SetUpdateExtent(0, i, 64, 0);
lpriority = sddp->ComputePriority();
if (lpriority != 1.0)
{
cerr << "Bad results for priority streaming test. "
<< "Should not be able to reject based on geometric bounds ranges." << endl;
return 1;
}
}
// Pieces rejected are union of upstream rejections.
// Downstream removal of meta info does not "unreject" pieces.
//READER -> CONTOUR -> CLIP1 -> CALC
//SETSGI PASSGI PASSGI+R STOPGI
//SETSAI PASSAI+R PASSAI STOPAI
vtkSmartPointer<vtkContourFilter> contour_C =
vtkSmartPointer<vtkContourFilter>::New();
contour_C->SetInputConnection(ir->GetOutputPort());
contour_C->SetValue(0,50);
vtkSmartPointer<vtkClipDataSet> clip_C1=
vtkSmartPointer<vtkClipDataSet>::New();
clip_C1->SetInputConnection(ir->GetOutputPort());
vtkSmartPointer<vtkPlane> plane_C1 =
vtkSmartPointer<vtkPlane>::New();
plane_C1->SetNormal(1,0,0);
plane_C1->SetOrigin(0,0,0);
clip_C1->SetClipFunction(plane_C1);
vtkSmartPointer<vtkClipDataSet> clip_C2 =
vtkSmartPointer<vtkClipDataSet>::New();
clip_C2->SetInputConnection(ir->GetOutputPort());
vtkSmartPointer<vtkPlane> plane_C2 =
vtkSmartPointer<vtkPlane>::New();
plane_C2->SetNormal(0,1,0);
plane_C2->SetOrigin(0,0,0);
clip_C2->SetClipFunction(plane_C2);
double *priority1 = new double [64];
double *priority2 = new double [64];
double *priority3 = new double [64];
sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(contour_C->GetExecutive());
for (int i = 0; i < 64; i++)
{
sddp->SetUpdateExtent(0, i, 64, 0);
priority1[i] = sddp->ComputePriority();
}
sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(clip_C1->GetExecutive());
for (int i = 0; i < 64; i++)
{
sddp->SetUpdateExtent(0, i, 64, 0);
priority2[i] = sddp->ComputePriority();
}
sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(clip_C2->GetExecutive());
for (int i = 0; i < 64; i++)
{
sddp->SetUpdateExtent(0, i, 64, 0);
priority3[i] = sddp->ComputePriority();
}
clip_C1->SetInputConnection(contour_C->GetOutputPort());
clip_C2->SetInputConnection(clip_C1->GetOutputPort());
vtkSmartPointer<vtkArrayCalculator> calc_C =
vtkSmartPointer<vtkArrayCalculator>::New();
calc_C->SetInputConnection(clip_C2->GetOutputPort());
calc_C->SetFunction("1");
vtkSmartPointer<vtkClipDataSet> clip_C3 =
vtkSmartPointer<vtkClipDataSet>::New();
clip_C3->SetInputConnection(calc_C->GetOutputPort());
vtkSmartPointer<vtkPlane> plane_C3 =
vtkSmartPointer<vtkPlane>::New();
plane_C3->SetNormal(0,0,1);
plane_C2->SetOrigin(0,0,0);
clip_C3->SetClipFunction(plane_C3);
sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(calc_C->GetExecutive());
for (int i = 0; i < 64; i++)
{
bool fail = false;
sddp->SetUpdateExtent(0, i, 64, 0);
double val = priority1[i] * priority2[i] * priority3[i];
double lpriority = sddp->ComputePriority();
if (lpriority != val)
{
cerr << "Chained priority " << i << " is wrong "
<< priority1[i] << "*" << priority2[i] << "*" << priority3[i] << "!=" << lpriority << endl;
fail = true;
}
if (i == 62 && lpriority != 1.0)
{
cerr << "Chained priority " << i << " should be 1.0" << endl;
fail = true;
}
if (i == 63 && lpriority != 0.0)
{
cerr << "Chained priority " << i << " should be 0.0" << endl;
fail = true;
}
if (fail)
{
delete[] priority1;
delete[] priority2;
delete[] priority3;
return 1;
}
}
delete[] priority1;
delete[] priority2;
delete[] priority3;
#if 0
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(renderer);
renderer->GetActiveCamera()->SetPosition( 0, 0, 10);
renderer->GetActiveCamera()->SetFocalPoint(0, 0, 0);
renderer->GetActiveCamera()->SetViewUp( 0, 1, 0);
renderer->SetBackground(0.0,0.0,0.0);
renWin->SetSize(300,300);
vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
vtkSmartPointer<vtkDataSetMapper> map1 = vtkSmartPointer<vtkDataSetMapper>::New();
map1->SetInputConnection(clip_C3->GetOutputPort());
vtkSmartPointer<vtkActor> act1 = vtkSmartPointer<vtkActor>::New();
act1->SetMapper(map1);
renderer->AddActor(act1);
renWin->Render();
iren->Start();
#endif
// Delete the file since the test passed:
vtksys::SystemTools::RemoveFile(fname.c_str());
return 0;
}
|
Add test coverage for meta information propagation. vtkStreamingDemandDrivenPipeline attempts to preserve meta information across filters. This test has been expanded to demonstrate that.
|
ENH: Add test coverage for meta information propagation. vtkStreamingDemandDrivenPipeline attempts to preserve meta information across filters. This test has been expanded to demonstrate that.
|
C++
|
bsd-3-clause
|
spthaolt/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,gram526/VTK,hendradarwin/VTK,keithroe/vtkoptix,keithroe/vtkoptix,collects/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,cjh1/VTK,aashish24/VTK-old,Wuteyan/VTK,sumedhasingla/VTK,mspark93/VTK,biddisco/VTK,ashray/VTK-EVM,mspark93/VTK,johnkit/vtk-dev,ashray/VTK-EVM,ashray/VTK-EVM,sankhesh/VTK,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,sankhesh/VTK,sumedhasingla/VTK,jmerkow/VTK,gram526/VTK,jmerkow/VTK,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,mspark93/VTK,msmolens/VTK,arnaudgelas/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,candy7393/VTK,collects/VTK,biddisco/VTK,collects/VTK,spthaolt/VTK,cjh1/VTK,msmolens/VTK,sumedhasingla/VTK,ashray/VTK-EVM,SimVascular/VTK,biddisco/VTK,aashish24/VTK-old,collects/VTK,Wuteyan/VTK,SimVascular/VTK,ashray/VTK-EVM,aashish24/VTK-old,hendradarwin/VTK,SimVascular/VTK,spthaolt/VTK,arnaudgelas/VTK,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,cjh1/VTK,sumedhasingla/VTK,demarle/VTK,biddisco/VTK,candy7393/VTK,jmerkow/VTK,hendradarwin/VTK,keithroe/vtkoptix,jmerkow/VTK,keithroe/vtkoptix,arnaudgelas/VTK,arnaudgelas/VTK,gram526/VTK,candy7393/VTK,mspark93/VTK,johnkit/vtk-dev,ashray/VTK-EVM,biddisco/VTK,johnkit/vtk-dev,sankhesh/VTK,candy7393/VTK,candy7393/VTK,jmerkow/VTK,msmolens/VTK,Wuteyan/VTK,jmerkow/VTK,naucoin/VTKSlicerWidgets,daviddoria/PointGraphsPhase1,Wuteyan/VTK,demarle/VTK,SimVascular/VTK,daviddoria/PointGraphsPhase1,cjh1/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,jmerkow/VTK,aashish24/VTK-old,jeffbaumes/jeffbaumes-vtk,demarle/VTK,daviddoria/PointGraphsPhase1,cjh1/VTK,keithroe/vtkoptix,msmolens/VTK,hendradarwin/VTK,hendradarwin/VTK,jeffbaumes/jeffbaumes-vtk,candy7393/VTK,collects/VTK,mspark93/VTK,hendradarwin/VTK,johnkit/vtk-dev,daviddoria/PointGraphsPhase1,cjh1/VTK,spthaolt/VTK,demarle/VTK,ashray/VTK-EVM,sankhesh/VTK,mspark93/VTK,johnkit/vtk-dev,johnkit/vtk-dev,keithroe/vtkoptix,gram526/VTK,spthaolt/VTK,collects/VTK,candy7393/VTK,demarle/VTK,msmolens/VTK,demarle/VTK,gram526/VTK,msmolens/VTK,daviddoria/PointGraphsPhase1,ashray/VTK-EVM,biddisco/VTK,naucoin/VTKSlicerWidgets,SimVascular/VTK,keithroe/vtkoptix,aashish24/VTK-old,berendkleinhaneveld/VTK,johnkit/vtk-dev,sumedhasingla/VTK,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,sumedhasingla/VTK,arnaudgelas/VTK,candy7393/VTK,naucoin/VTKSlicerWidgets,gram526/VTK,spthaolt/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,biddisco/VTK,sankhesh/VTK,aashish24/VTK-old,spthaolt/VTK,msmolens/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,mspark93/VTK,demarle/VTK,sankhesh/VTK,daviddoria/PointGraphsPhase1,arnaudgelas/VTK,msmolens/VTK,hendradarwin/VTK,sumedhasingla/VTK,sumedhasingla/VTK,Wuteyan/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,keithroe/vtkoptix,mspark93/VTK,demarle/VTK,Wuteyan/VTK
|
027af6e2d1a9a6f0f5adcf4179f1544c14a26d63
|
DungeonsOfNoudar486/DOSVersion/CDOSRenderer.cpp
|
DungeonsOfNoudar486/DOSVersion/CDOSRenderer.cpp
|
#include <conio.h>
#include <iterator>
#include <dpmi.h>
#include <go32.h>
#include <pc.h>
#include <bios.h>
#include <sys/movedata.h>
#include <sys/farptr.h>
#include <sys/nearptr.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
using sg14::fixed_point;
#include "RasterizerCommon.h"
#include "RaycastCommon.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "NativeBitmap.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
namespace odb {
long frame = 0;
void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) {
if (x < 0 || x >= 320 || y < 0 || y >= 128) {
return;
}
mBuffer[(320 * y) + x] = pixel;
}
CRenderer::~CRenderer() {
textmode(C80);
clrscr();
#ifdef PROFILEBUILD
printf("Total time spent rendering: %d\nTotal time spent processing visibility: %d\nFrames rendered: %d\n", mAccMs, mProcVisTime, mUsefulFrames );
#endif
}
CRenderer::CRenderer() {
__dpmi_regs reg;
reg.x.ax = 0x13;
__dpmi_int(0x10, ®);
outp(0x03c8, 0);
for (int r = 0; r < 4; ++r) {
for (int g = 0; g < 8; ++g) {
for (int b = 0; b < 8; ++b) {
outp(0x03c9, (r * (16)));
outp(0x03c9, (g * (8)));
outp(0x03c9, (b * (8)));
}
}
}
}
void CRenderer::sleep(long ms) {
}
void CRenderer::handleSystemEvents() {
#ifdef PROFILEBUILD
gotoxy(1,1);
printf("%d", ++mFrame);
#endif
const static FixP delta{2};
int lastKey = 0;
if (kbhit()) {
auto getched = getch();
switch(getched) {
case 27:
mBufferedCommand = Knights::kQuitGameCommand;
break;
case 'w':
mBufferedCommand = Knights::kPickItemCommand;
mCached = false;
break;
case 's':
mBufferedCommand = Knights::kDropItemCommand;
mCached = false;
break;
case 'q':
mBufferedCommand = Knights::kCycleLeftInventoryCommand;
mCached = false;
break;
case 'e':
mBufferedCommand = Knights::kCycleRightInventoryCommand;
mCached = false;
break;
case 'z':
mBufferedCommand = Knights::kStrafeLeftCommand;
mCached = false;
break;
case 'x':
mBufferedCommand = Knights::kStrafeRightCommand;
mCached = false;
break;
case ' ':
mBufferedCommand = Knights::kUseCurrentItemInInventoryCommand;
mCached = false;
break;
case 224:
case 0:
auto arrow = getch();
switch(arrow) {
case 75:
mBufferedCommand = Knights::kTurnPlayerLeftCommand;
mCached = false;
break;
case 72:
mBufferedCommand = Knights::kMovePlayerForwardCommand;
mCached = false;
break;
case 77:
mBufferedCommand = Knights::kTurnPlayerRightCommand;
mCached = false;
break;
case 80:
mBufferedCommand = Knights::kMovePlayerBackwardCommand;
mCached = false;
break;
}
break;
}
}
}
void CRenderer::drawTextAt( int x, int y, const char* text ) {
gotoxy(x, y );
printf("%s", text);
}
void CRenderer::flip() {
dosmemput(&mBuffer[0], 320 * 200, 0xa0000);
}
void CRenderer::clear() {
}
}
|
#include <conio.h>
#include <iterator>
#include <dpmi.h>
#include <go32.h>
#include <pc.h>
#include <bios.h>
#include <sys/movedata.h>
#include <sys/farptr.h>
#include <sys/nearptr.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using eastl::vector;
using eastl::array;
using namespace std::chrono;
using sg14::fixed_point;
#include "RasterizerCommon.h"
#include "RaycastCommon.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "NativeBitmap.h"
#include "RasterizerCommon.h"
#include "CRenderer.h"
namespace odb {
long frame = 0;
void CRenderer::putRaw(int16_t x, int16_t y, uint32_t pixel) {
if (x < 0 || x >= 320 || y < 0 || y >= 128) {
return;
}
mBuffer[(320 * y) + x] = pixel;
}
CRenderer::~CRenderer() {
textmode(C80);
clrscr();
printf("Thanks for playing!\nI would like to thank Ivan Odintsoff for the help,\nmy coworkers in the Lisobn office,\nmy family and most of all, my wife for keeping me human.\n\n" );
#ifdef PROFILEBUILD
printf("Total time spent rendering: %d\nTotal time spent processing visibility: %d\nFrames rendered: %d\n", mAccMs, mProcVisTime, mUsefulFrames );
#endif
}
CRenderer::CRenderer() {
__dpmi_regs reg;
reg.x.ax = 0x13;
__dpmi_int(0x10, ®);
outp(0x03c8, 0);
for (int r = 0; r < 4; ++r) {
for (int g = 0; g < 8; ++g) {
for (int b = 0; b < 8; ++b) {
outp(0x03c9, (r * (16)));
outp(0x03c9, (g * (8)));
outp(0x03c9, (b * (8)));
}
}
}
}
void CRenderer::sleep(long ms) {
}
void CRenderer::handleSystemEvents() {
#ifdef PROFILEBUILD
gotoxy(1,1);
printf("%d", ++mFrame);
#endif
const static FixP delta{2};
int lastKey = 0;
if (kbhit()) {
auto getched = getch();
switch(getched) {
case 27:
mBufferedCommand = Knights::kQuitGameCommand;
break;
case 'w':
mBufferedCommand = Knights::kPickItemCommand;
mCached = false;
break;
case 's':
mBufferedCommand = Knights::kDropItemCommand;
mCached = false;
break;
case 'q':
mBufferedCommand = Knights::kCycleLeftInventoryCommand;
mCached = false;
break;
case 'e':
mBufferedCommand = Knights::kCycleRightInventoryCommand;
mCached = false;
break;
case 'z':
mBufferedCommand = Knights::kStrafeLeftCommand;
mCached = false;
break;
case 'x':
mBufferedCommand = Knights::kStrafeRightCommand;
mCached = false;
break;
case ' ':
mBufferedCommand = Knights::kUseCurrentItemInInventoryCommand;
mCached = false;
break;
case 224:
case 0:
auto arrow = getch();
switch(arrow) {
case 75:
mBufferedCommand = Knights::kTurnPlayerLeftCommand;
mCached = false;
break;
case 72:
mBufferedCommand = Knights::kMovePlayerForwardCommand;
mCached = false;
break;
case 77:
mBufferedCommand = Knights::kTurnPlayerRightCommand;
mCached = false;
break;
case 80:
mBufferedCommand = Knights::kMovePlayerBackwardCommand;
mCached = false;
break;
}
break;
}
}
}
void CRenderer::drawTextAt( int x, int y, const char* text ) {
gotoxy(x, y );
printf("%s", text);
}
void CRenderer::flip() {
dosmemput(&mBuffer[0], 320 * 200, 0xa0000);
}
void CRenderer::clear() {
}
}
|
Add extended thanks
|
Add extended thanks
|
C++
|
bsd-2-clause
|
TheFakeMontyOnTheRun/dungeons-of-noudar,TheFakeMontyOnTheRun/dungeons-of-noudar
|
01443b82c023801fbda9b615428a1891ab9b1a9c
|
EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
|
EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
|
///
/// \file TestEMCALSimulation.C
/// \ingroup EMCAL_TestSimRec
/// \brief Simple macro to test EMCAL simulation
///
/// Simple macro to test EMCAL simulation
///
/// \author Jenn Klay, LLNL
///
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStopwatch.h>
#include <TSystem.h>
#include "AliSimulation.h"
#include "AliLog.h"
#endif
///
/// Main execution method
///
/// \param nev: number of events to be generated
/// \param raw: generate also raw data from digits?
///
void TestEMCALSimulation(Int_t nev =10, Bool_t raw = kFALSE)
{
AliSimulation simulator;
simulator.SetConfigFile("Config.C");
simulator.SetMakeSDigits("EMCAL");
simulator.SetMakeDigits ("EMCAL");
//simulator.SetRunGeneration(kFALSE); // Generate or not particles
//simulator.SetRunSimulation(kFALSE); // Generate or not HITS (detector response) or not, start from SDigits
if(raw) simulator.SetWriteRawData("EMCAL","raw.root",kTRUE);
//OCDB settings
simulator.SetDefaultStorage("local://$ALICE_ROOT/OCDB");
simulator.SetSpecificStorage("GRP/GRP/Data",
Form("local://%s",gSystem->pwd()));
// In case of anchoring MC, comment previous OCDB lines
// select the appropriate year
//simulator.SetDefaultStorage("alien://Folder=/alice/data/2011/OCDB");
//simulator.UseVertexFromCDB();
//simulator.UseMagFieldFromGRP();
//Avoid the HLT to run
simulator.SetRunHLT("");
//Avoid QA
simulator.SetRunQA(":");
TStopwatch timer;
timer.Start();
// simulator.SetRunNumber(159582); // LHC11d run
simulator.Run(nev);
timer.Stop();
timer.Print();
}
|
///
/// \file TestEMCALSimulation.C
/// \ingroup EMCAL_TestSimRec
/// \brief Simple macro to test EMCAL simulation
///
/// Simple macro to test EMCAL simulation.
/// It will take the Config.C macro that is sitting in the same place as the execution is performed.
/// In order to execute this you can do
/// * Root5: aliroot -q -b -l $ALICE_ROOT/EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
/// * Root6: aliroot -q -b -l $ALICE_ROOT/EMCAL/macros/TestSimuReco/LoadLibForConfig.C $ALICE_ROOT/EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
///
/// Or directly in the root prompt
/// root [1] .x LoadLibForConfig.C //Root6
/// root [2] .x TestEMCALSimulation.C
///
/// In order to find all the included classes in the Config.C one should add to the rootlogon.C file some paths
/// gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/ -I$ALICE_ROOT/include -I$ALICE_ROOT/ANALYSIS/macros -I$ALICE_ROOT/STEER -I$ALICE_ROOT/STEER/STEER -I$GEANT3DIR/include -I$GEANT3DIR/include/TGeant3");
/// or do it in the root prompt before execution.
///
/// \author : Jenn Klay, LLNL.
/// \author : Gustavo Conesa Balbastre <[email protected]>, (LPSC-CNRS).
///
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStopwatch.h>
#include <TSystem.h>
#include "AliSimulation.h"
#include "AliLog.h"
#endif
///
/// Main execution method
///
/// \param nev: number of events to be generated
/// \param raw: generate also raw data from digits?
///
void TestEMCALSimulation(Int_t nev =10, Bool_t raw = kFALSE)
{
AliSimulation simulator;
simulator.SetConfigFile("Config.C");
simulator.SetMakeSDigits("EMCAL");
simulator.SetMakeDigits ("EMCAL");
//simulator.SetRunGeneration(kFALSE); // Generate or not particles
//simulator.SetRunSimulation(kFALSE); // Generate or not HITS (detector response) or not, start from SDigits
if(raw) simulator.SetWriteRawData("EMCAL","raw.root",kTRUE);
//OCDB settings
simulator.SetDefaultStorage("local://$ALICE_ROOT/OCDB");
simulator.SetSpecificStorage("GRP/GRP/Data",
Form("local://%s",gSystem->pwd()));
// In case of anchoring MC, comment previous OCDB lines
// select the appropriate year
//simulator.SetDefaultStorage("alien://Folder=/alice/data/2011/OCDB");
//simulator.UseVertexFromCDB();
//simulator.UseMagFieldFromGRP();
//Avoid the HLT to run
simulator.SetRunHLT("");
//Avoid QA
simulator.SetRunQA(":");
TStopwatch timer;
timer.Start();
// simulator.SetRunNumber(159582); // LHC11d run
simulator.Run(nev);
timer.Stop();
timer.Print();
}
|
update doygen doc, specially on how to execute the macro for Root6
|
update doygen doc, specially on how to execute the macro for Root6
|
C++
|
bsd-3-clause
|
alisw/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,miranov25/AliRoot,miranov25/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,shahor02/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,coppedis/AliRoot,alisw/AliRoot,shahor02/AliRoot,alisw/AliRoot,alisw/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,coppedis/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,coppedis/AliRoot,alisw/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,alisw/AliRoot,coppedis/AliRoot
|
26920307f0b481809d0179bdc007d1336794690c
|
src/libs/ssh/sshchannel.cpp
|
src/libs/ssh/sshchannel.cpp
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** 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.
**
****************************************************************************/
#include "sshchannel_p.h"
#include "sshincomingpacket_p.h"
#include "sshsendfacility_p.h"
#include <botan/botan.h>
#include <QTimer>
namespace QSsh {
namespace Internal {
// "Payload length" (RFC 4253, 6.1), i.e. minus packet type, channel number
// and length field for string.
const quint32 MinMaxPacketSize = 32768 - sizeof(quint32) - sizeof(quint32) - 1;
const quint32 NoChannel = 0xffffffffu;
AbstractSshChannel::AbstractSshChannel(quint32 channelId,
SshSendFacility &sendFacility)
: m_sendFacility(sendFacility), m_timeoutTimer(new QTimer(this)),
m_localChannel(channelId), m_remoteChannel(NoChannel),
m_localWindowSize(initialWindowSize()), m_remoteWindowSize(0),
m_state(Inactive)
{
m_timeoutTimer->setSingleShot(true);
connect(m_timeoutTimer, SIGNAL(timeout()), this, SIGNAL(timeout()));
}
AbstractSshChannel::~AbstractSshChannel()
{
}
void AbstractSshChannel::setChannelState(ChannelState state)
{
m_state = state;
if (state == Closed)
closeHook();
}
void AbstractSshChannel::requestSessionStart()
{
// Note: We are just being paranoid here about the Botan exceptions,
// which are extremely unlikely to happen, because if there was a problem
// with our cryptography stuff, it would have hit us before, on
// establishing the connection.
try {
m_sendFacility.sendSessionPacket(m_localChannel, initialWindowSize(), maxPacketSize());
setChannelState(SessionRequested);
m_timeoutTimer->start(ReplyTimeout);
} catch (Botan::Exception &e) {
qDebug("Botan error: %s", e.what());
closeChannel();
}
}
void AbstractSshChannel::sendData(const QByteArray &data)
{
try {
m_sendBuffer += data;
flushSendBuffer();
} catch (Botan::Exception &e) {
qDebug("Botan error: %s", e.what());
closeChannel();
}
}
quint32 AbstractSshChannel::initialWindowSize()
{
return maxPacketSize();
}
quint32 AbstractSshChannel::maxPacketSize()
{
return 16 * 1024 * 1024;
}
void AbstractSshChannel::handleWindowAdjust(quint32 bytesToAdd)
{
checkChannelActive();
const quint64 newValue = m_remoteWindowSize + bytesToAdd;
if (newValue > 0xffffffffu) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Illegal window size requested.");
}
m_remoteWindowSize = newValue;
flushSendBuffer();
}
void AbstractSshChannel::flushSendBuffer()
{
while (true) {
const quint32 bytesToSend = qMin(m_remoteMaxPacketSize,
qMin<quint32>(m_remoteWindowSize, m_sendBuffer.size()));
if (bytesToSend == 0)
break;
const QByteArray &data = m_sendBuffer.left(bytesToSend);
m_sendFacility.sendChannelDataPacket(m_remoteChannel, data);
m_sendBuffer.remove(0, bytesToSend);
m_remoteWindowSize -= bytesToSend;
}
}
void AbstractSshChannel::handleOpenSuccess(quint32 remoteChannelId,
quint32 remoteWindowSize, quint32 remoteMaxPacketSize)
{
if (m_state != SessionRequested) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet.");
}
m_timeoutTimer->stop();
if (remoteMaxPacketSize < MinMaxPacketSize) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Maximum packet size too low.");
}
#ifdef CREATOR_SSH_DEBUG
qDebug("Channel opened. remote channel id: %u, remote window size: %u, "
"remote max packet size: %u",
remoteChannelId, remoteWindowSize, remoteMaxPacketSize);
#endif
m_remoteChannel = remoteChannelId;
m_remoteWindowSize = remoteWindowSize;
m_remoteMaxPacketSize = remoteMaxPacketSize;
setChannelState(SessionEstablished);
handleOpenSuccessInternal();
}
void AbstractSshChannel::handleOpenFailure(const QString &reason)
{
if (m_state != SessionRequested) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_CHANNEL_OPEN_FAILURE packet.");
}
m_timeoutTimer->stop();
#ifdef CREATOR_SSH_DEBUG
qDebug("Channel open request failed for channel %u", m_localChannel);
#endif
handleOpenFailureInternal(reason);
}
void AbstractSshChannel::handleChannelEof()
{
if (m_state == Inactive || m_state == Closed) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_EOF message.");
}
m_localWindowSize = 0;
emit eof();
}
void AbstractSshChannel::handleChannelClose()
{
#ifdef CREATOR_SSH_DEBUG
qDebug("Receiving CLOSE for channel %u", m_localChannel);
#endif
if (channelState() == Inactive || channelState() == Closed) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_CLOSE message.");
}
closeChannel();
setChannelState(Closed);
}
void AbstractSshChannel::handleChannelData(const QByteArray &data)
{
const int bytesToDeliver = handleChannelOrExtendedChannelData(data);
handleChannelDataInternal(bytesToDeliver == data.size()
? data : data.left(bytesToDeliver));
}
void AbstractSshChannel::handleChannelExtendedData(quint32 type, const QByteArray &data)
{
const int bytesToDeliver = handleChannelOrExtendedChannelData(data);
handleChannelExtendedDataInternal(type, bytesToDeliver == data.size()
? data : data.left(bytesToDeliver));
}
void AbstractSshChannel::handleChannelRequest(const SshIncomingPacket &packet)
{
checkChannelActive();
const QByteArray &requestType = packet.extractChannelRequestType();
if (requestType == SshIncomingPacket::ExitStatusType)
handleExitStatus(packet.extractChannelExitStatus());
else if (requestType == SshIncomingPacket::ExitSignalType)
handleExitSignal(packet.extractChannelExitSignal());
else if (requestType != "[email protected]") // Suppress warning for this one, as it's sent all the time.
qWarning("Ignoring unknown request type '%s'", requestType.data());
}
int AbstractSshChannel::handleChannelOrExtendedChannelData(const QByteArray &data)
{
checkChannelActive();
const int bytesToDeliver = qMin<quint32>(data.size(), maxDataSize());
if (bytesToDeliver != data.size())
qWarning("Misbehaving server does not respect local window, clipping.");
m_localWindowSize -= bytesToDeliver;
if (m_localWindowSize < maxPacketSize()) {
m_localWindowSize += maxPacketSize();
m_sendFacility.sendWindowAdjustPacket(m_remoteChannel, maxPacketSize());
}
return bytesToDeliver;
}
void AbstractSshChannel::closeChannel()
{
if (m_state == CloseRequested) {
m_timeoutTimer->stop();
} else if (m_state != Closed) {
if (m_state == Inactive) {
setChannelState(Closed);
} else {
setChannelState(CloseRequested);
m_sendFacility.sendChannelEofPacket(m_remoteChannel);
m_sendFacility.sendChannelClosePacket(m_remoteChannel);
}
}
}
void AbstractSshChannel::checkChannelActive()
{
if (channelState() == Inactive || channelState() == Closed)
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Channel not open.");
}
quint32 AbstractSshChannel::maxDataSize() const
{
return qMin(m_localWindowSize, maxPacketSize());
}
} // namespace Internal
} // namespace QSsh
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** 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.
**
****************************************************************************/
#include "sshchannel_p.h"
#include "sshincomingpacket_p.h"
#include "sshsendfacility_p.h"
#include <botan/botan.h>
#include <QTimer>
namespace QSsh {
namespace Internal {
// "Payload length" (RFC 4253, 6.1), i.e. minus packet type, channel number
// and length field for string.
const quint32 MinMaxPacketSize = 32768 - sizeof(quint32) - sizeof(quint32) - 1;
const quint32 NoChannel = 0xffffffffu;
AbstractSshChannel::AbstractSshChannel(quint32 channelId,
SshSendFacility &sendFacility)
: m_sendFacility(sendFacility), m_timeoutTimer(new QTimer(this)),
m_localChannel(channelId), m_remoteChannel(NoChannel),
m_localWindowSize(initialWindowSize()), m_remoteWindowSize(0),
m_state(Inactive)
{
m_timeoutTimer->setSingleShot(true);
connect(m_timeoutTimer, SIGNAL(timeout()), this, SIGNAL(timeout()));
}
AbstractSshChannel::~AbstractSshChannel()
{
}
void AbstractSshChannel::setChannelState(ChannelState state)
{
m_state = state;
if (state == Closed)
closeHook();
}
void AbstractSshChannel::requestSessionStart()
{
// Note: We are just being paranoid here about the Botan exceptions,
// which are extremely unlikely to happen, because if there was a problem
// with our cryptography stuff, it would have hit us before, on
// establishing the connection.
try {
m_sendFacility.sendSessionPacket(m_localChannel, initialWindowSize(), maxPacketSize());
setChannelState(SessionRequested);
m_timeoutTimer->start(ReplyTimeout);
} catch (Botan::Exception &e) {
qDebug("Botan error: %s", e.what());
closeChannel();
}
}
void AbstractSshChannel::sendData(const QByteArray &data)
{
try {
m_sendBuffer += data;
flushSendBuffer();
} catch (Botan::Exception &e) {
qDebug("Botan error: %s", e.what());
closeChannel();
}
}
quint32 AbstractSshChannel::initialWindowSize()
{
return maxPacketSize();
}
quint32 AbstractSshChannel::maxPacketSize()
{
return 16 * 1024 * 1024;
}
void AbstractSshChannel::handleWindowAdjust(quint32 bytesToAdd)
{
checkChannelActive();
const quint64 newValue = m_remoteWindowSize + bytesToAdd;
if (newValue > 0xffffffffu) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Illegal window size requested.");
}
m_remoteWindowSize = newValue;
flushSendBuffer();
}
void AbstractSshChannel::flushSendBuffer()
{
while (true) {
const quint32 bytesToSend = qMin(m_remoteMaxPacketSize,
qMin<quint32>(m_remoteWindowSize, m_sendBuffer.size()));
if (bytesToSend == 0)
break;
const QByteArray &data = m_sendBuffer.left(bytesToSend);
m_sendFacility.sendChannelDataPacket(m_remoteChannel, data);
m_sendBuffer.remove(0, bytesToSend);
m_remoteWindowSize -= bytesToSend;
}
}
void AbstractSshChannel::handleOpenSuccess(quint32 remoteChannelId,
quint32 remoteWindowSize, quint32 remoteMaxPacketSize)
{
switch (m_state) {
case SessionRequested:
break; // Ok, continue.
case CloseRequested:
return; // Late server reply; we requested a channel close in the meantime.
default:
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet.");
}
m_timeoutTimer->stop();
if (remoteMaxPacketSize < MinMaxPacketSize) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Maximum packet size too low.");
}
#ifdef CREATOR_SSH_DEBUG
qDebug("Channel opened. remote channel id: %u, remote window size: %u, "
"remote max packet size: %u",
remoteChannelId, remoteWindowSize, remoteMaxPacketSize);
#endif
m_remoteChannel = remoteChannelId;
m_remoteWindowSize = remoteWindowSize;
m_remoteMaxPacketSize = remoteMaxPacketSize;
setChannelState(SessionEstablished);
handleOpenSuccessInternal();
}
void AbstractSshChannel::handleOpenFailure(const QString &reason)
{
switch (m_state) {
case SessionRequested:
break; // Ok, continue.
case CloseRequested:
return; // Late server reply; we requested a channel close in the meantime.
default:
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet.");
}
m_timeoutTimer->stop();
#ifdef CREATOR_SSH_DEBUG
qDebug("Channel open request failed for channel %u", m_localChannel);
#endif
handleOpenFailureInternal(reason);
}
void AbstractSshChannel::handleChannelEof()
{
if (m_state == Inactive || m_state == Closed) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_EOF message.");
}
m_localWindowSize = 0;
emit eof();
}
void AbstractSshChannel::handleChannelClose()
{
#ifdef CREATOR_SSH_DEBUG
qDebug("Receiving CLOSE for channel %u", m_localChannel);
#endif
if (channelState() == Inactive || channelState() == Closed) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_CLOSE message.");
}
closeChannel();
setChannelState(Closed);
}
void AbstractSshChannel::handleChannelData(const QByteArray &data)
{
const int bytesToDeliver = handleChannelOrExtendedChannelData(data);
handleChannelDataInternal(bytesToDeliver == data.size()
? data : data.left(bytesToDeliver));
}
void AbstractSshChannel::handleChannelExtendedData(quint32 type, const QByteArray &data)
{
const int bytesToDeliver = handleChannelOrExtendedChannelData(data);
handleChannelExtendedDataInternal(type, bytesToDeliver == data.size()
? data : data.left(bytesToDeliver));
}
void AbstractSshChannel::handleChannelRequest(const SshIncomingPacket &packet)
{
checkChannelActive();
const QByteArray &requestType = packet.extractChannelRequestType();
if (requestType == SshIncomingPacket::ExitStatusType)
handleExitStatus(packet.extractChannelExitStatus());
else if (requestType == SshIncomingPacket::ExitSignalType)
handleExitSignal(packet.extractChannelExitSignal());
else if (requestType != "[email protected]") // Suppress warning for this one, as it's sent all the time.
qWarning("Ignoring unknown request type '%s'", requestType.data());
}
int AbstractSshChannel::handleChannelOrExtendedChannelData(const QByteArray &data)
{
checkChannelActive();
const int bytesToDeliver = qMin<quint32>(data.size(), maxDataSize());
if (bytesToDeliver != data.size())
qWarning("Misbehaving server does not respect local window, clipping.");
m_localWindowSize -= bytesToDeliver;
if (m_localWindowSize < maxPacketSize()) {
m_localWindowSize += maxPacketSize();
m_sendFacility.sendWindowAdjustPacket(m_remoteChannel, maxPacketSize());
}
return bytesToDeliver;
}
void AbstractSshChannel::closeChannel()
{
if (m_state == CloseRequested) {
m_timeoutTimer->stop();
} else if (m_state != Closed) {
if (m_state == Inactive) {
setChannelState(Closed);
} else {
setChannelState(CloseRequested);
m_sendFacility.sendChannelEofPacket(m_remoteChannel);
m_sendFacility.sendChannelClosePacket(m_remoteChannel);
}
}
}
void AbstractSshChannel::checkChannelActive()
{
if (channelState() == Inactive || channelState() == Closed)
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Channel not open.");
}
quint32 AbstractSshChannel::maxDataSize() const
{
return qMin(m_localWindowSize, maxPacketSize());
}
} // namespace Internal
} // namespace QSsh
|
Fix misleading error message.
|
SSH: Fix misleading error message.
- It is not an error if the server replies to one of our earlier
requests while we are in closing state. This can happen if we
close the channel shortly after sending the other request.
- Also change the message itself, which could be interpreted as
"packet corrupt" when we actually meant "packet unexpected".
Change-Id: I735c67b2a9b41af0c5e0b8d229369d94ec37277c
Reviewed-by: hjk <[email protected]>
|
C++
|
lgpl-2.1
|
xianian/qt-creator,Distrotech/qtcreator,danimo/qt-creator,kuba1/qtcreator,amyvmiwei/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,farseerri/git_code,xianian/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,farseerri/git_code,danimo/qt-creator,farseerri/git_code,xianian/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,farseerri/git_code,Distrotech/qtcreator,danimo/qt-creator,farseerri/git_code,martyone/sailfish-qtcreator,danimo/qt-creator,martyone/sailfish-qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,danimo/qt-creator,Distrotech/qtcreator,farseerri/git_code,kuba1/qtcreator,xianian/qt-creator,xianian/qt-creator,danimo/qt-creator,Distrotech/qtcreator,kuba1/qtcreator,kuba1/qtcreator,danimo/qt-creator,martyone/sailfish-qtcreator
|
4fa5c5160b93d0c2c825a186f3e504bd86e1a600
|
build/tsan_suppressions.cc
|
build/tsan_suppressions.cc
|
/*
* Copyright (c) 2014 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.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// False positive in system wrappers.
// https://code.google.com/p/webrtc/issues/detail?id=300
"race:webrtc/system_wrappers/source/thread_posix.cc\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/messagequeue.cc\n"
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/base/messagequeue.cc\n"
"race:talk/base/testclient.cc\n"
"race:talk/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// libjingle_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
"race:webrtc/base/thread.cc\n"
"race:talk/base/logging.cc\n"
"race:talk/base/sharedexclusivelock_unittest.cc\n"
"race:talk/base/signalthread_unittest.cc\n"
"race:talk/base/thread.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:third_party/usrsctp/usrsctplib/user_sctp_timer_iterate.c\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:talk/base/criticalsection.h\n"
"deadlock:talk/base/sigslot.h\n"
"deadlock:webrtc/system_wrappers/source/critical_section_posix.cc\n"
"deadlock:webrtc/system_wrappers/source/rw_lock_posix.cc\n"
"deadlock:webrtc/system_wrappers/source/thread_posix.cc\n"
// From Chromium's tsan_suppressions.cc file.
// False positives in libglib.so. Since we don't instrument them, we cannot
// reason about the synchronization in them.
"race:libglib*.so\n"
// Races in libevent, http://crbug.com/23244.
"race:libevent/event.c\n"
// http://crbug.com/84094.
"race:sqlite3StatusSet\n"
"race:pcache1EnforceMaxPage\n"
"race:pcache1AllocPage\n"
// http://crbug.com/157586
"race:third_party/libvpx/source/libvpx/vp8/decoder/threading.c\n"
// http://crbug.com/158922
"race:third_party/libvpx/source/libvpx/vp8/encoder/*\n"
// http://crbug.com/223352
"race:uprv_malloc_46\n"
"race:uprv_realloc_46\n"
// http://crbug.com/244385
"race:unixTempFileDir\n"
// http://crbug.com/244774
"race:webrtc::RTPReceiver::ProcessBitrate\n"
"race:webrtc::RTPSender::ProcessBitrate\n"
"race:webrtc::VideoCodingModuleImpl::Decode\n"
"race:webrtc::RTPSender::SendOutgoingData\n"
"race:webrtc::VP8EncoderImpl::GetEncodedPartitions\n"
"race:webrtc::VP8EncoderImpl::Encode\n"
"race:webrtc::ViEEncoder::DeliverFrame\n"
"race:webrtc::vcm::VideoReceiver::Decode\n"
"race:webrtc::VCMReceiver::FrameForDecoding\n"
"race:*trace_event_unique_catstatic*\n"
// http://crbug.com/244856
"race:AutoPulseLock\n"
// http://crbug.com/246968
"race:webrtc::VideoCodingModuleImpl::RegisterPacketRequestCallback\n"
// http://crbug.com/246970
"race:webrtc::EventPosix::StartTimer\n"
// http://crbug.com/258479
"race:SamplingStateScope\n"
"race:g_trace_state\n"
// http://crbug.com/270037
"race:gLibCleanupFunctions\n"
// http://crbug.com/272987
"race:webrtc::MediaStreamTrack<webrtc::AudioTrackInterface>::set_enabled\n"
// http://crbug.com/345245
"race:jingle_glue::JingleThreadWrapper::~JingleThreadWrapper\n"
"race:webrtc::voe::Channel::UpdatePacketDelay\n"
"race:webrtc::voe::Channel::GetDelayEstimate\n"
"race:webrtc::VCMCodecDataBase::DeregisterReceiveCodec\n"
"race:webrtc::GainControlImpl::set_stream_analog_level\n"
// http://crbug.com/347538
"race:sctp_timer_start\n"
// http://crbug.com/347548
"race:cricket::WebRtcVideoMediaChannel::MaybeResetVieSendCodec\n"
"race:cricket::WebRtcVideoMediaChannel::SetSendCodec\n"
// http://crbug.com/348511
"race:webrtc::acm1::AudioCodingModuleImpl::PlayoutData10Ms\n"
// http://crbug.com/348982
"race:cricket::P2PTransportChannel::OnConnectionDestroyed\n"
"race:cricket::P2PTransportChannel::AddConnection\n"
// http://crbug.com/348984
"race:sctp_express_handle_sack\n"
// http://crbug.com/350982
"race:libvpx/vp9/decoder/vp9_thread.c\n"
// http://crbug.com/372807
"deadlock:net::X509Certificate::CreateCertificateListFromBytes\n"
"deadlock:net::X509Certificate::CreateFromBytes\n"
"deadlock:net::SSLClientSocketNSS::Core::DoHandshakeLoop\n"
// False positive in libc's tzset_internal, http://crbug.com/379738.
"race:tzset_internal\n"
// http://crbug.com/380554
"deadlock:g_type_add_interface_static\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
|
/*
* Copyright (c) 2014 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.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// False positive in system wrappers.
// https://code.google.com/p/webrtc/issues/detail?id=300
"race:webrtc/system_wrappers/source/thread_posix.cc\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/messagequeue.cc\n"
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/base/messagequeue.cc\n"
"race:talk/base/testclient.cc\n"
"race:talk/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// libjingle_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
"race:webrtc/base/thread.cc\n"
"race:talk/base/logging.cc\n"
"race:talk/base/sharedexclusivelock_unittest.cc\n"
"race:talk/base/signalthread_unittest.cc\n"
"race:talk/base/thread.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:third_party/usrsctp/usrsctplib/user_sctp_timer_iterate.c\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::InputFrame\n"
"deadlock:cricket::WebRtcVideoChannel2::WebRtcVideoSendStream::SetCapturer\n"
"deadlock:talk_base::AsyncResolver::~AsyncResolver\n"
"deadlock:webrtc::ProcessThreadImpl::RegisterModule\n"
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::RTPSenderAudio::RegisterAudioPayload\n"
"deadlock:webrtc/system_wrappers/source/logging_unittest.cc\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::VideoSendStreamTest_SuspendBelowMinBitrate_Test::TestBody\n"
"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n"
"deadlock:webrtc::ViEChannel::StartSend\n"
"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
"deadlock:webrtc::ViESender::RegisterSendTransport\n"
// From Chromium's tsan_suppressions.cc file.
// False positives in libglib.so. Since we don't instrument them, we cannot
// reason about the synchronization in them.
"race:libglib*.so\n"
// Races in libevent, http://crbug.com/23244.
"race:libevent/event.c\n"
// http://crbug.com/84094.
"race:sqlite3StatusSet\n"
"race:pcache1EnforceMaxPage\n"
"race:pcache1AllocPage\n"
// http://crbug.com/157586
"race:third_party/libvpx/source/libvpx/vp8/decoder/threading.c\n"
// http://crbug.com/158922
"race:third_party/libvpx/source/libvpx/vp8/encoder/*\n"
// http://crbug.com/223352
"race:uprv_malloc_46\n"
"race:uprv_realloc_46\n"
// http://crbug.com/244385
"race:unixTempFileDir\n"
// http://crbug.com/244774
"race:webrtc::RTPReceiver::ProcessBitrate\n"
"race:webrtc::RTPSender::ProcessBitrate\n"
"race:webrtc::VideoCodingModuleImpl::Decode\n"
"race:webrtc::RTPSender::SendOutgoingData\n"
"race:webrtc::VP8EncoderImpl::GetEncodedPartitions\n"
"race:webrtc::VP8EncoderImpl::Encode\n"
"race:webrtc::ViEEncoder::DeliverFrame\n"
"race:webrtc::vcm::VideoReceiver::Decode\n"
"race:webrtc::VCMReceiver::FrameForDecoding\n"
"race:*trace_event_unique_catstatic*\n"
// http://crbug.com/244856
"race:AutoPulseLock\n"
// http://crbug.com/246968
"race:webrtc::VideoCodingModuleImpl::RegisterPacketRequestCallback\n"
// http://crbug.com/246970
"race:webrtc::EventPosix::StartTimer\n"
// http://crbug.com/258479
"race:SamplingStateScope\n"
"race:g_trace_state\n"
// http://crbug.com/270037
"race:gLibCleanupFunctions\n"
// http://crbug.com/272987
"race:webrtc::MediaStreamTrack<webrtc::AudioTrackInterface>::set_enabled\n"
// http://crbug.com/345245
"race:jingle_glue::JingleThreadWrapper::~JingleThreadWrapper\n"
"race:webrtc::voe::Channel::UpdatePacketDelay\n"
"race:webrtc::voe::Channel::GetDelayEstimate\n"
"race:webrtc::VCMCodecDataBase::DeregisterReceiveCodec\n"
"race:webrtc::GainControlImpl::set_stream_analog_level\n"
// http://crbug.com/347538
"race:sctp_timer_start\n"
// http://crbug.com/347548
"race:cricket::WebRtcVideoMediaChannel::MaybeResetVieSendCodec\n"
"race:cricket::WebRtcVideoMediaChannel::SetSendCodec\n"
// http://crbug.com/348511
"race:webrtc::acm1::AudioCodingModuleImpl::PlayoutData10Ms\n"
// http://crbug.com/348982
"race:cricket::P2PTransportChannel::OnConnectionDestroyed\n"
"race:cricket::P2PTransportChannel::AddConnection\n"
// http://crbug.com/348984
"race:sctp_express_handle_sack\n"
// http://crbug.com/350982
"race:libvpx/vp9/decoder/vp9_thread.c\n"
// http://crbug.com/372807
"deadlock:net::X509Certificate::CreateCertificateListFromBytes\n"
"deadlock:net::X509Certificate::CreateFromBytes\n"
"deadlock:net::SSLClientSocketNSS::Core::DoHandshakeLoop\n"
// False positive in libc's tzset_internal, http://crbug.com/379738.
"race:tzset_internal\n"
// http://crbug.com/380554
"deadlock:g_type_add_interface_static\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
|
Make deadlock suppressions less generic.
|
Make deadlock suppressions less generic.
Previously they were enabled on all webrtc and talk primitives directly when TSAN config changed to enable deadlock detections.
BUG=3509
[email protected]
Review URL: https://webrtc-codereview.appspot.com/18679004
git-svn-id: 03ae4fbe531b1eefc9d815f31e49022782c42458@6583 4adac7df-926f-26a2-2b94-8c16560cd09d
|
C++
|
bsd-3-clause
|
PersonifyInc/chromium_webrtc,aleonliao/webrtc-trunk,krieger-od/nwjs_chromium_webrtc,bpsinc-native/src_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,MIPS/external-chromium_org-third_party-webrtc,MIPS/external-chromium_org-third_party-webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,aleonliao/webrtc-trunk,xin3liang/platform_external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,MIPS/external-chromium_org-third_party-webrtc,svn2github/webrtc-Revision-8758,xin3liang/platform_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,android-ia/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,krieger-od/webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,sippet/webrtc,krieger-od/webrtc,sippet/webrtc,aleonliao/webrtc-trunk,jchavanton/webrtc,krieger-od/webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,aleonliao/webrtc-trunk,android-ia/platform_external_chromium_org_third_party_webrtc,jchavanton/webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,jchavanton/webrtc,aleonliao/webrtc-trunk,Omegaphora/external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,Alkalyne/webrtctrunk,krieger-od/nwjs_chromium_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,aleonliao/webrtc-trunk,MIPS/external-chromium_org-third_party-webrtc,MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,sippet/webrtc,PersonifyInc/chromium_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,Omegaphora/external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,krieger-od/webrtc,Alkalyne/webrtctrunk,xin3liang/platform_external_chromium_org_third_party_webrtc,svn2github/webrtc-Revision-8758,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,bpsinc-native/src_third_party_webrtc,sippet/webrtc,bpsinc-native/src_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,jchavanton/webrtc,svn2github/webrtc-Revision-8758,sippet/webrtc,bpsinc-native/src_third_party_webrtc,geekboxzone/lollipop_external_chromium_org_third_party_webrtc,PersonifyInc/chromium_webrtc,krieger-od/webrtc,PersonifyInc/chromium_webrtc,krieger-od/nwjs_chromium_webrtc,svn2github/webrtc-Revision-8758,Alkalyne/webrtctrunk,Omegaphora/external_chromium_org_third_party_webrtc,xin3liang/platform_external_chromium_org_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,bpsinc-native/src_third_party_webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,android-ia/platform_external_chromium_org_third_party_webrtc,sippet/webrtc,bpsinc-native/src_third_party_webrtc,MIPS/external-chromium_org-third_party-webrtc,jgcaaprom/android_external_chromium_org_third_party_webrtc,krieger-od/nwjs_chromium_webrtc,krieger-od/webrtc,bpsinc-native/src_third_party_webrtc,Alkalyne/webrtctrunk
|
005e60ce388cfc170ceb78e16ec1aff2f00008c6
|
runtime/test/ompt/misc/interoperability.cpp
|
runtime/test/ompt/misc/interoperability.cpp
|
// RUN: %libomp-cxx-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
#include <iostream>
#include <thread>
#include "callback.h"
int condition = 0;
void f() {
OMPT_SIGNAL(condition);
// wait for both pthreads to arrive
OMPT_WAIT(condition, 2);
int i = 0;
#pragma omp parallel num_threads(2)
{
OMPT_SIGNAL(condition);
OMPT_WAIT(condition, 6);
}
}
int main() {
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_schedule'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_begin'
// CHECK: 0: NULL_POINTER=[[NULL:.*$]]
// first master thread
// CHECK: {{^}}[[MASTER_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_1]]
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_1:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1:[0-9]+]], requested_team_size=2
// CHECK-SAME: codeptr_ra=0x{{[0-f]+}}, invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1]], task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_1]]
// second master thread
// CHECK: {{^}}[[MASTER_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_2]]
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_2:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2:[0-9]+]]
// CHECK-SAME: requested_team_size=2, codeptr_ra=0x{{[0-f]+}}
// CHECK-SAME: invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2]], task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_2]]
// first worker thread
// CHECK: {{^}}[[THREAD_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_1]]
// CHECK: {{^}}[[THREAD_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_1]]
// second worker thread
// CHECK: {{^}}[[THREAD_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_2]]
// CHECK: {{^}}[[THREAD_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_2]]
|
// RUN: %libomp-cxx-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
#include <iostream>
#include <thread>
#include "callback.h"
#include "omp.h"
int condition = 0;
void f() {
// Call OpenMP API function to force initialization of OMPT.
// (omp_get_thread_num() does not work because it just returns 0 if the
// runtime isn't initialized yet...)
omp_get_num_threads();
OMPT_SIGNAL(condition);
// Wait for both initial threads to arrive that will eventually become the
// master threads in the following parallel region.
OMPT_WAIT(condition, 2);
#pragma omp parallel num_threads(2)
{
// Wait for all threads to arrive so that no worker thread can be reused...
OMPT_SIGNAL(condition);
OMPT_WAIT(condition, 6);
}
}
int main() {
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_schedule'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_implicit_task'
// CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_begin'
// CHECK: 0: NULL_POINTER=[[NULL:.*$]]
// first master thread
// CHECK: {{^}}[[MASTER_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_1]]
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_1:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1:[0-9]+]], requested_team_size=2
// CHECK-SAME: codeptr_ra=0x{{[0-f]+}}, invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_1]], task_id=[[PARENT_TASK_ID_1]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_1]]
// second master thread
// CHECK: {{^}}[[MASTER_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_initial=1, thread_id=[[MASTER_ID_2]]
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_task_create: parent_task_id=0
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id=[[PARENT_TASK_ID_2:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[NULL]], task_type=ompt_task_initial=1
// CHECK-SAME: has_dependences=no
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2:[0-9]+]]
// CHECK-SAME: requested_team_size=2, codeptr_ra=0x{{[0-f]+}}
// CHECK-SAME: invoker={{.*}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_parallel_end:
// CHECK-SAME: parallel_id=[[PARALLEL_ID_2]], task_id=[[PARENT_TASK_ID_2]]
// CHECK-SAME: invoker={{[0-9]+}}
// CHECK: {{^}}[[MASTER_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[MASTER_ID_2]]
// first worker thread
// CHECK: {{^}}[[THREAD_ID_1:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_1]]
// CHECK: {{^}}[[THREAD_ID_1]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_1]]
// second worker thread
// CHECK: {{^}}[[THREAD_ID_2:[0-9]+]]: ompt_event_thread_begin:
// CHECK-SAME: thread_type=ompt_thread_worker=2, thread_id=[[THREAD_ID_2]]
// CHECK: {{^}}[[THREAD_ID_2]]: ompt_event_thread_end:
// CHECK-SAME: thread_id=[[THREAD_ID_2]]
|
Fix interoperability test with GCC
|
[OMPT] Fix interoperability test with GCC
We have to ensure that the runtime is initialized _before_ waiting
for the two started threads to guarantee that the master threads
post their ompt_event_thread_begin before the worker threads. This
is not guaranteed in the parallel region where one worker thread
could start before the other master thread has invoked the callback.
The problem did not happen with Clang becauses the generated code
calls __kmpc_global_thread_num() and cashes its result for functions
that contain OpenMP pragmas.
Differential Revision: https://reviews.llvm.org/D43882
git-svn-id: f99161ee8ccfe2101cbe1bdda2220bce2ed25485@326435 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/openmp,llvm-mirror/openmp,llvm-mirror/openmp,llvm-mirror/openmp,llvm-mirror/openmp
|
9df3d8ccd7a3130faccb73933d0c196a81d605eb
|
src/libutil/tests/config.cc
|
src/libutil/tests/config.cc
|
#include "json.hh"
#include "config.hh"
#include "args.hh"
#include <sstream>
#include <gtest/gtest.h>
namespace nix {
/* ----------------------------------------------------------------------------
* Config
* --------------------------------------------------------------------------*/
TEST(Config, setUndefinedSetting) {
Config config;
ASSERT_EQ(config.set("undefined-key", "value"), false);
}
TEST(Config, setDefinedSetting) {
Config config;
std::string value;
Setting<std::string> foo{&config, value, "name-of-the-setting", "description"};
ASSERT_EQ(config.set("name-of-the-setting", "value"), true);
}
TEST(Config, getDefinedSetting) {
Config config;
std::string value;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> foo{&config, value, "name-of-the-setting", "description"};
config.getSettings(settings, /* overridenOnly = */ false);
const auto iter = settings.find("name-of-the-setting");
ASSERT_NE(iter, settings.end());
ASSERT_EQ(iter->second.value, "");
ASSERT_EQ(iter->second.description, "description");
}
TEST(Config, getDefinedOverridenSettingNotSet) {
Config config;
std::string value;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> foo{&config, value, "name-of-the-setting", "description"};
config.getSettings(settings, /* overridenOnly = */ true);
const auto e = settings.find("name-of-the-setting");
ASSERT_EQ(e, settings.end());
}
TEST(Config, getDefinedSettingSet1) {
Config config;
std::string value;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, value, "name-of-the-setting", "description"};
setting.assign("value");
config.getSettings(settings, /* overridenOnly = */ false);
const auto iter = settings.find("name-of-the-setting");
ASSERT_NE(iter, settings.end());
ASSERT_EQ(iter->second.value, "value");
ASSERT_EQ(iter->second.description, "description");
}
TEST(Config, getDefinedSettingSet2) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
ASSERT_TRUE(config.set("name-of-the-setting", "value"));
config.getSettings(settings, /* overridenOnly = */ false);
const auto e = settings.find("name-of-the-setting");
ASSERT_NE(e, settings.end());
ASSERT_EQ(e->second.value, "value");
ASSERT_EQ(e->second.description, "description");
}
TEST(Config, addSetting) {
class TestSetting : public AbstractSetting {
public:
TestSetting() : AbstractSetting("test", "test", {}) {}
void set(const std::string & value) {}
std::string to_string() const { return {}; }
};
Config config;
TestSetting setting;
ASSERT_FALSE(config.set("test", "value"));
config.addSetting(&setting);
ASSERT_TRUE(config.set("test", "value"));
}
TEST(Config, withInitialValue) {
const StringMap initials = {
{ "key", "value" },
};
Config config(initials);
{
std::map<std::string, Config::SettingInfo> settings;
config.getSettings(settings, /* overridenOnly = */ false);
ASSERT_EQ(settings.find("key"), settings.end());
}
Setting<std::string> setting{&config, "default-value", "key", "description"};
{
std::map<std::string, Config::SettingInfo> settings;
config.getSettings(settings, /* overridenOnly = */ false);
ASSERT_EQ(settings["key"].value, "value");
}
}
TEST(Config, resetOverriden) {
Config config;
config.resetOverriden();
}
TEST(Config, resetOverridenWithSetting) {
Config config;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
{
std::map<std::string, Config::SettingInfo> settings;
setting.set("foo");
ASSERT_EQ(setting.get(), "foo");
config.getSettings(settings, /* overridenOnly = */ true);
ASSERT_TRUE(settings.empty());
}
{
std::map<std::string, Config::SettingInfo> settings;
setting.override("bar");
ASSERT_TRUE(setting.overriden);
ASSERT_EQ(setting.get(), "bar");
config.getSettings(settings, /* overridenOnly = */ true);
ASSERT_FALSE(settings.empty());
}
{
std::map<std::string, Config::SettingInfo> settings;
config.resetOverriden();
ASSERT_FALSE(setting.overriden);
config.getSettings(settings, /* overridenOnly = */ true);
ASSERT_TRUE(settings.empty());
}
}
TEST(Config, toJSONOnEmptyConfig) {
std::stringstream out;
{ // Scoped to force the destructor of JSONObject to write the final `}`
JSONObject obj(out);
Config config;
config.toJSON(obj);
}
ASSERT_EQ(out.str(), "{}");
}
TEST(Config, toJSONOnNonEmptyConfig) {
std::stringstream out;
{ // Scoped to force the destructor of JSONObject to write the final `}`
JSONObject obj(out);
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
setting.assign("value");
config.toJSON(obj);
}
ASSERT_EQ(out.str(), R"#({"name-of-the-setting":{"description":"description","value":"value"}})#");
}
TEST(Config, setSettingAlias) {
Config config;
Setting<std::string> setting{&config, "", "some-int", "best number", { "another-int" }};
ASSERT_TRUE(config.set("some-int", "1"));
ASSERT_EQ(setting.get(), "1");
ASSERT_TRUE(config.set("another-int", "2"));
ASSERT_EQ(setting.get(), "2");
ASSERT_TRUE(config.set("some-int", "3"));
ASSERT_EQ(setting.get(), "3");
}
/* FIXME: The reapplyUnknownSettings method doesn't seem to do anything
* useful (these days). Whenever we add a new setting to Config the
* unknown settings are always considered. In which case is this function
* actually useful? Is there some way to register a Setting without calling
* addSetting? */
TEST(Config, DISABLED_reapplyUnknownSettings) {
Config config;
ASSERT_FALSE(config.set("name-of-the-setting", "unknownvalue"));
Setting<std::string> setting{&config, "default", "name-of-the-setting", "description"};
ASSERT_EQ(setting.get(), "default");
config.reapplyUnknownSettings();
ASSERT_EQ(setting.get(), "unknownvalue");
}
}
|
#include "json.hh"
#include "config.hh"
#include "args.hh"
#include <sstream>
#include <gtest/gtest.h>
namespace nix {
/* ----------------------------------------------------------------------------
* Config
* --------------------------------------------------------------------------*/
TEST(Config, setUndefinedSetting) {
Config config;
ASSERT_EQ(config.set("undefined-key", "value"), false);
}
TEST(Config, setDefinedSetting) {
Config config;
std::string value;
Setting<std::string> foo{&config, value, "name-of-the-setting", "description"};
ASSERT_EQ(config.set("name-of-the-setting", "value"), true);
}
TEST(Config, getDefinedSetting) {
Config config;
std::string value;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> foo{&config, value, "name-of-the-setting", "description"};
config.getSettings(settings, /* overridenOnly = */ false);
const auto iter = settings.find("name-of-the-setting");
ASSERT_NE(iter, settings.end());
ASSERT_EQ(iter->second.value, "");
ASSERT_EQ(iter->second.description, "description");
}
TEST(Config, getDefinedOverridenSettingNotSet) {
Config config;
std::string value;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> foo{&config, value, "name-of-the-setting", "description"};
config.getSettings(settings, /* overridenOnly = */ true);
const auto e = settings.find("name-of-the-setting");
ASSERT_EQ(e, settings.end());
}
TEST(Config, getDefinedSettingSet1) {
Config config;
std::string value;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, value, "name-of-the-setting", "description"};
setting.assign("value");
config.getSettings(settings, /* overridenOnly = */ false);
const auto iter = settings.find("name-of-the-setting");
ASSERT_NE(iter, settings.end());
ASSERT_EQ(iter->second.value, "value");
ASSERT_EQ(iter->second.description, "description");
}
TEST(Config, getDefinedSettingSet2) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
ASSERT_TRUE(config.set("name-of-the-setting", "value"));
config.getSettings(settings, /* overridenOnly = */ false);
const auto e = settings.find("name-of-the-setting");
ASSERT_NE(e, settings.end());
ASSERT_EQ(e->second.value, "value");
ASSERT_EQ(e->second.description, "description");
}
TEST(Config, addSetting) {
class TestSetting : public AbstractSetting {
public:
TestSetting() : AbstractSetting("test", "test", {}) {}
void set(const std::string & value) {}
std::string to_string() const { return {}; }
};
Config config;
TestSetting setting;
ASSERT_FALSE(config.set("test", "value"));
config.addSetting(&setting);
ASSERT_TRUE(config.set("test", "value"));
}
TEST(Config, withInitialValue) {
const StringMap initials = {
{ "key", "value" },
};
Config config(initials);
{
std::map<std::string, Config::SettingInfo> settings;
config.getSettings(settings, /* overridenOnly = */ false);
ASSERT_EQ(settings.find("key"), settings.end());
}
Setting<std::string> setting{&config, "default-value", "key", "description"};
{
std::map<std::string, Config::SettingInfo> settings;
config.getSettings(settings, /* overridenOnly = */ false);
ASSERT_EQ(settings["key"].value, "value");
}
}
TEST(Config, resetOverriden) {
Config config;
config.resetOverriden();
}
TEST(Config, resetOverridenWithSetting) {
Config config;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
{
std::map<std::string, Config::SettingInfo> settings;
setting.set("foo");
ASSERT_EQ(setting.get(), "foo");
config.getSettings(settings, /* overridenOnly = */ true);
ASSERT_TRUE(settings.empty());
}
{
std::map<std::string, Config::SettingInfo> settings;
setting.override("bar");
ASSERT_TRUE(setting.overriden);
ASSERT_EQ(setting.get(), "bar");
config.getSettings(settings, /* overridenOnly = */ true);
ASSERT_FALSE(settings.empty());
}
{
std::map<std::string, Config::SettingInfo> settings;
config.resetOverriden();
ASSERT_FALSE(setting.overriden);
config.getSettings(settings, /* overridenOnly = */ true);
ASSERT_TRUE(settings.empty());
}
}
TEST(Config, toJSONOnEmptyConfig) {
std::stringstream out;
{ // Scoped to force the destructor of JSONObject to write the final `}`
JSONObject obj(out);
Config config;
config.toJSON(obj);
}
ASSERT_EQ(out.str(), "{}");
}
TEST(Config, toJSONOnNonEmptyConfig) {
std::stringstream out;
{ // Scoped to force the destructor of JSONObject to write the final `}`
JSONObject obj(out);
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
setting.assign("value");
config.toJSON(obj);
}
ASSERT_EQ(out.str(), R"#({"name-of-the-setting":{"description":"description","value":"value"}})#");
}
TEST(Config, setSettingAlias) {
Config config;
Setting<std::string> setting{&config, "", "some-int", "best number", { "another-int" }};
ASSERT_TRUE(config.set("some-int", "1"));
ASSERT_EQ(setting.get(), "1");
ASSERT_TRUE(config.set("another-int", "2"));
ASSERT_EQ(setting.get(), "2");
ASSERT_TRUE(config.set("some-int", "3"));
ASSERT_EQ(setting.get(), "3");
}
/* FIXME: The reapplyUnknownSettings method doesn't seem to do anything
* useful (these days). Whenever we add a new setting to Config the
* unknown settings are always considered. In which case is this function
* actually useful? Is there some way to register a Setting without calling
* addSetting? */
TEST(Config, DISABLED_reapplyUnknownSettings) {
Config config;
ASSERT_FALSE(config.set("name-of-the-setting", "unknownvalue"));
Setting<std::string> setting{&config, "default", "name-of-the-setting", "description"};
ASSERT_EQ(setting.get(), "default");
config.reapplyUnknownSettings();
ASSERT_EQ(setting.get(), "unknownvalue");
}
TEST(Config, applyConfigEmpty) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
config.applyConfig("");
config.getSettings(settings);
ASSERT_TRUE(settings.empty());
}
TEST(Config, applyConfigEmptyWithComment) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
config.applyConfig("# just a comment");
config.getSettings(settings);
ASSERT_TRUE(settings.empty());
}
TEST(Config, applyConfigAssignment) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
config.applyConfig(
"name-of-the-setting = value-from-file #useful comment\n"
"# name-of-the-setting = foo\n"
);
config.getSettings(settings);
ASSERT_FALSE(settings.empty());
ASSERT_EQ(settings["name-of-the-setting"].value, "value-from-file");
}
TEST(Config, applyConfigWithReassignedSetting) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
config.applyConfig(
"name-of-the-setting = first-value\n"
"name-of-the-setting = second-value\n"
);
config.getSettings(settings);
ASSERT_FALSE(settings.empty());
ASSERT_EQ(settings["name-of-the-setting"].value, "second-value");
}
TEST(Config, applyConfigFailsOnMissingIncludes) {
Config config;
std::map<std::string, Config::SettingInfo> settings;
Setting<std::string> setting{&config, "", "name-of-the-setting", "description"};
ASSERT_THROW(config.applyConfig(
"name-of-the-setting = value-from-file\n"
"# name-of-the-setting = foo\n"
"include /nix/store/does/not/exist.nix"
), Error);
}
TEST(Config, applyConfigInvalidThrows) {
Config config;
ASSERT_THROW(config.applyConfig("value == key"), UsageError);
ASSERT_THROW(config.applyConfig("value "), UsageError);
}
}
|
add tests for Config::applyConfig
|
tests/config.cc: add tests for Config::applyConfig
|
C++
|
lgpl-2.1
|
NixOS/nix,NixOS/nix,rycee/nix,rycee/nix,rycee/nix,NixOS/nix,NixOS/nix,rycee/nix,rycee/nix,NixOS/nix
|
b73619b11b1ac4798d2f0061f196d2096344476a
|
src/SparseLinearSolvers.cpp
|
src/SparseLinearSolvers.cpp
|
#include "SparseLinearSolvers.hpp"
extern "C" {
#include <SuiteSparse_config.h>
#include <umfpack.h>
#include "cblas.h"
#include "amd.h"
#include "colamd.h"
#include "ldl.h"
#include "umfpack_get_determinant.h"
}
#include <iostream>
#include <Eigen/Sparse>
#include <Eigen/UmfPackSupport>
Eigen::VectorXd solveBICG(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b
)
{
using namespace Eigen;
BiCGSTAB<SparseMatrix<double>> solver(A);
return solver.solve(b);
}
Eigen::VectorXd solveLU(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b
)
{
using namespace Eigen;
SparseLU<SparseMatrix<double>> solver;
solver.analyzePattern(A);
solver.factorize(A);
return solver.solve(b);
}
Eigen::VectorXd solveUMFLU(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b
)
{
using namespace Eigen;
UmfPackLU<SparseMatrix<double>> solver;
solver.analyzePattern(A);
solver.factorize(A);
return solver.solve(b);
}
void SparseLinearSolvers::EigenSolver::solve(
const Eigen::SparseMatrix<double>& A,
double* x, double *b)
{
int n = A.cols();
Eigen::VectorXd eb(n), ex(n);
for (int i = 0; i < n; i++) {
eb(i) = b[i];
ex(i) = 0;
}
ex = solveBICG(A, eb);
// ex = solveUMFLU(A, eb);
// ex = solveLU(A, eb);
for (int i = 0; i < n; i++) {
x[i] = ex(i);
// std::cout << ex(i) << " ";
}
}
|
#include <Spark/SparseLinearSolvers.hpp>
extern "C" {
#include <SuiteSparse_config.h>
#include <umfpack.h>
#include "cblas.h"
#include "amd.h"
#include "colamd.h"
#include "ldl.h"
#include "umfpack_get_determinant.h"
}
#include <iostream>
#include <Eigen/Sparse>
#include <Eigen/UmfPackSupport>
Eigen::VectorXd solveBICG(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b
)
{
using namespace Eigen;
BiCGSTAB<SparseMatrix<double>> solver(A);
return solver.solve(b);
}
Eigen::VectorXd solveLU(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b
)
{
using namespace Eigen;
SparseLU<SparseMatrix<double>> solver;
solver.analyzePattern(A);
solver.factorize(A);
return solver.solve(b);
}
Eigen::VectorXd solveUMFLU(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b
)
{
using namespace Eigen;
UmfPackLU<SparseMatrix<double>> solver;
solver.analyzePattern(A);
solver.factorize(A);
return solver.solve(b);
}
void SparseLinearSolvers::EigenSolver::solve(
const Eigen::SparseMatrix<double>& A,
double* x, double *b)
{
int n = A.cols();
Eigen::VectorXd eb(n), ex(n);
for (int i = 0; i < n; i++) {
eb(i) = b[i];
ex(i) = 0;
}
ex = solveBICG(A, eb);
// ex = solveUMFLU(A, eb);
// ex = solveLU(A, eb);
for (int i = 0; i < n; i++) {
x[i] = ex(i);
// std::cout << ex(i) << " ";
}
}
|
Fix some other compilation issues.
|
Fix some other compilation issues.
|
C++
|
mit
|
caskorg/cask,caskorg/cask,caskorg/cask,caskorg/cask,caskorg/cask
|
dbbda42a4373dcd28c9f3b11a9d66fa1f69bbb85
|
desktop/win32/source/applauncher/launcher.hxx
|
desktop/win32/source/applauncher/launcher.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#pragma once
#ifndef __cplusplus
#error Need C++ to compile
#endif
#include <Windows.h>
#ifndef _INC_TCHAR
# ifdef UNICODE
# define _UNICODE
# endif
# include <tchar.h>
#endif
#ifdef UNICODE
# define GetArgv( pArgc ) CommandLineToArgvW( GetCommandLine(), pArgc )
#else
# define GetArgv( pArgc ) (*pArgc = __argc, __argv)
#endif
#define OFFICE_IMAGE_NAME _T("soffice")
extern _TCHAR APPLICATION_SWITCH[];
extern LPCWSTR APPUSERMODELID;
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#pragma once
#ifndef __cplusplus
#error Need C++ to compile
#endif
#include <windows.h>
#ifndef _INC_TCHAR
# ifdef UNICODE
# define _UNICODE
# endif
# include <tchar.h>
#endif
#ifdef UNICODE
# define GetArgv( pArgc ) CommandLineToArgvW( GetCommandLine(), pArgc )
#else
# define GetArgv( pArgc ) (*pArgc = __argc, __argv)
#endif
#define OFFICE_IMAGE_NAME _T("soffice")
extern _TCHAR APPLICATION_SWITCH[];
extern LPCWSTR APPUSERMODELID;
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
include files always in lowercase
|
include files always in lowercase
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
c99a6a3e4cf69734e51f250a8b0143921730f2d0
|
src/window.cc
|
src/window.cc
|
#include "window.hh"
#include "assert.hh"
#include "highlighter_registry.hh"
#include "hooks_manager.hh"
#include "context.hh"
#include <algorithm>
#include <sstream>
namespace Kakoune
{
Window::Window(Buffer& buffer)
: Editor(buffer),
m_position(0, 0),
m_dimensions(0, 0)
{
HighlighterRegistry& registry = HighlighterRegistry::instance();
GlobalHooksManager::instance().run_hook("WinCreate", buffer.name(),
Context(*this));
registry.add_highlighter_to_window(*this, "expand_tabs", HighlighterParameters());
registry.add_highlighter_to_window(*this, "highlight_selections", HighlighterParameters());
}
DisplayCoord Window::cursor_position() const
{
return line_and_column_at(cursor_iterator());
}
BufferIterator Window::cursor_iterator() const
{
return selections().back().last();
}
template<typename Iterator>
static DisplayCoord measure_string(Iterator begin, Iterator end)
{
DisplayCoord result(0, 0);
while (begin != end)
{
if (*begin == '\n')
{
++result.line;
result.column = 0;
}
else
++result.column;
++begin;
}
return result;
}
static DisplayCoord measure_string(const Editor::String& string)
{
return measure_string(string.begin(), string.end());
}
BufferIterator Window::iterator_at(const DisplayCoord& window_pos) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return buffer().begin();
if (DisplayCoord(0,0) <= window_pos)
{
for (auto atom_it = m_display_buffer.begin();
atom_it != m_display_buffer.end(); ++atom_it)
{
if (window_pos < atom_it->coord())
{
return (--atom_it)->iterator_at(window_pos);
}
}
}
return buffer().iterator_at(m_position + BufferCoord(window_pos));
}
DisplayCoord Window::line_and_column_at(const BufferIterator& iterator) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return DisplayCoord(0, 0);
if (iterator >= m_display_buffer.front().begin() and
iterator < m_display_buffer.back().end())
{
for (auto& atom : m_display_buffer)
{
if (atom.end() > iterator)
{
assert(atom.begin() <= iterator);
return atom.line_and_column_at(iterator);
}
}
}
BufferCoord coord = buffer().line_and_column_at(iterator);
return DisplayCoord(coord.line - m_position.line,
coord.column - m_position.column);
}
void Window::update_display_buffer()
{
scroll_to_keep_cursor_visible_ifn();
m_display_buffer.clear();
BufferIterator begin = buffer().iterator_at(m_position);
BufferIterator end = buffer().iterator_at(m_position +
BufferCoord(m_dimensions.line, m_dimensions.column))+1;
if (begin == end)
return;
m_display_buffer.append(DisplayAtom(DisplayCoord(0,0), begin, end));
m_highlighters(m_display_buffer);
m_display_buffer.check_invariant();
}
void Window::set_dimensions(const DisplayCoord& dimensions)
{
m_dimensions = dimensions;
}
void Window::scroll_to_keep_cursor_visible_ifn()
{
DisplayCoord cursor = line_and_column_at(selections().back().last());
if (cursor.line < 0)
{
m_position.line = std::max(m_position.line + cursor.line, 0);
}
else if (cursor.line >= m_dimensions.line)
{
m_position.line += cursor.line - (m_dimensions.line - 1);
}
if (cursor.column < 0)
{
m_position.column = std::max(m_position.column + cursor.column, 0);
}
else if (cursor.column >= m_dimensions.column)
{
m_position.column += cursor.column - (m_dimensions.column - 1);
}
}
std::string Window::status_line() const
{
BufferCoord cursor = buffer().line_and_column_at(selections().back().last());
std::ostringstream oss;
oss << buffer().name();
if (buffer().is_modified())
oss << " [+]";
oss << " -- " << cursor.line+1 << "," << cursor.column+1
<< " -- " << selections().size() << " sel -- ";
if (is_editing())
oss << "[Insert]";
return oss.str();
}
void Window::on_incremental_insertion_end()
{
push_selections();
hooks_manager().run_hook("InsertEnd", "", Context(*this));
pop_selections();
}
}
|
#include "window.hh"
#include "assert.hh"
#include "highlighter_registry.hh"
#include "hooks_manager.hh"
#include "context.hh"
#include <algorithm>
#include <sstream>
namespace Kakoune
{
Window::Window(Buffer& buffer)
: Editor(buffer),
m_position(0, 0),
m_dimensions(0, 0)
{
HighlighterRegistry& registry = HighlighterRegistry::instance();
GlobalHooksManager::instance().run_hook("WinCreate", buffer.name(),
Context(*this));
registry.add_highlighter_to_window(*this, "expand_tabs", HighlighterParameters());
registry.add_highlighter_to_window(*this, "highlight_selections", HighlighterParameters());
}
DisplayCoord Window::cursor_position() const
{
return line_and_column_at(cursor_iterator());
}
BufferIterator Window::cursor_iterator() const
{
return selections().back().last();
}
template<typename Iterator>
static DisplayCoord measure_string(Iterator begin, Iterator end)
{
DisplayCoord result(0, 0);
while (begin != end)
{
if (*begin == '\n')
{
++result.line;
result.column = 0;
}
else
++result.column;
++begin;
}
return result;
}
static DisplayCoord measure_string(const Editor::String& string)
{
return measure_string(string.begin(), string.end());
}
BufferIterator Window::iterator_at(const DisplayCoord& window_pos) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return buffer().begin();
if (DisplayCoord(0,0) <= window_pos)
{
for (auto atom_it = m_display_buffer.begin();
atom_it != m_display_buffer.end(); ++atom_it)
{
if (window_pos < atom_it->coord())
{
return (--atom_it)->iterator_at(window_pos);
}
}
}
return buffer().iterator_at(m_position + BufferCoord(window_pos));
}
DisplayCoord Window::line_and_column_at(const BufferIterator& iterator) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return DisplayCoord(0, 0);
if (iterator >= m_display_buffer.front().begin() and
iterator < m_display_buffer.back().end())
{
for (auto& atom : m_display_buffer)
{
if (atom.end() > iterator)
{
assert(atom.begin() <= iterator);
return atom.line_and_column_at(iterator);
}
}
}
BufferCoord coord = buffer().line_and_column_at(iterator);
return DisplayCoord(coord.line - m_position.line,
coord.column - m_position.column);
}
void Window::update_display_buffer()
{
scroll_to_keep_cursor_visible_ifn();
m_display_buffer.clear();
BufferIterator begin = buffer().iterator_at(m_position);
BufferIterator end = buffer().iterator_at(m_position +
BufferCoord(m_dimensions.line, m_dimensions.column))+2;
if (begin == end)
return;
m_display_buffer.append(DisplayAtom(DisplayCoord(0,0), begin, end));
m_highlighters(m_display_buffer);
m_display_buffer.check_invariant();
}
void Window::set_dimensions(const DisplayCoord& dimensions)
{
m_dimensions = dimensions;
}
void Window::scroll_to_keep_cursor_visible_ifn()
{
DisplayCoord cursor = line_and_column_at(selections().back().last());
if (cursor.line < 0)
{
m_position.line = std::max(m_position.line + cursor.line, 0);
}
else if (cursor.line >= m_dimensions.line)
{
m_position.line += cursor.line - (m_dimensions.line - 1);
}
if (cursor.column < 0)
{
m_position.column = std::max(m_position.column + cursor.column, 0);
}
else if (cursor.column >= m_dimensions.column)
{
m_position.column += cursor.column - (m_dimensions.column - 1);
}
}
std::string Window::status_line() const
{
BufferCoord cursor = buffer().line_and_column_at(selections().back().last());
std::ostringstream oss;
oss << buffer().name();
if (buffer().is_modified())
oss << " [+]";
oss << " -- " << cursor.line+1 << "," << cursor.column+1
<< " -- " << selections().size() << " sel -- ";
if (is_editing())
oss << "[Insert]";
return oss.str();
}
void Window::on_incremental_insertion_end()
{
push_selections();
hooks_manager().run_hook("InsertEnd", "", Context(*this));
pop_selections();
}
}
|
fix last line handling in window display buffer
|
fix last line handling in window display buffer
|
C++
|
unlicense
|
jjthrash/kakoune,xificurC/kakoune,elegios/kakoune,flavius/kakoune,xificurC/kakoune,mawww/kakoune,jjthrash/kakoune,zakgreant/kakoune,elegios/kakoune,lenormf/kakoune,casimir/kakoune,jkonecny12/kakoune,Asenar/kakoune,danr/kakoune,danielma/kakoune,rstacruz/kakoune,Asenar/kakoune,jjthrash/kakoune,alpha123/kakoune,ekie/kakoune,occivink/kakoune,elegios/kakoune,xificurC/kakoune,danr/kakoune,zakgreant/kakoune,danielma/kakoune,jkonecny12/kakoune,alpha123/kakoune,Asenar/kakoune,Somasis/kakoune,ekie/kakoune,lenormf/kakoune,casimir/kakoune,occivink/kakoune,occivink/kakoune,alexherbo2/kakoune,zakgreant/kakoune,alexherbo2/kakoune,jjthrash/kakoune,danielma/kakoune,Somasis/kakoune,occivink/kakoune,jkonecny12/kakoune,ekie/kakoune,danr/kakoune,alexherbo2/kakoune,danielma/kakoune,lenormf/kakoune,danr/kakoune,lenormf/kakoune,zakgreant/kakoune,Asenar/kakoune,alpha123/kakoune,ekie/kakoune,rstacruz/kakoune,xificurC/kakoune,flavius/kakoune,mawww/kakoune,flavius/kakoune,rstacruz/kakoune,Somasis/kakoune,alexherbo2/kakoune,Somasis/kakoune,rstacruz/kakoune,jkonecny12/kakoune,flavius/kakoune,mawww/kakoune,alpha123/kakoune,mawww/kakoune,casimir/kakoune,elegios/kakoune,casimir/kakoune
|
a7166dc1ec1e5e8cbb2cc80a5fdc3c5160bfd6b8
|
samples/sharedcategoricaldata/src/frame.cpp
|
samples/sharedcategoricaldata/src/frame.cpp
|
/*
Copyright (c) 2018-2019 Xavier Leclercq
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 "frame.h"
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/charts/wxcharts.h>
Frame::Frame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title)
{
// Create a top-level panel to hold all the contents of the frame
wxPanel* panel = new wxPanel(this, wxID_ANY);
// Create the data for the bar chart widget
wxVector<wxString> labels;
labels.push_back("January");
labels.push_back("February");
labels.push_back("March");
labels.push_back("April");
labels.push_back("May");
labels.push_back("June");
labels.push_back("July");
wxChartsCategoricalData::ptr chartData = wxChartsCategoricalData::make_shared(labels);
// Add the first dataset
wxVector<wxDouble> points1;
points1.push_back(3);
points1.push_back(2.5);
points1.push_back(1.2);
points1.push_back(3);
points1.push_back(6);
points1.push_back(5);
points1.push_back(1);
wxChartsDoubleDataset::ptr dataset1(new wxChartsDoubleDataset(points1));
chartData->AddDataset(dataset1);
// Add the second dataset
wxVector<wxDouble> points2;
points2.push_back(1);
points2.push_back(1.33);
points2.push_back(2.5);
points2.push_back(2);
points2.push_back(3);
points2.push_back(1.8);
points2.push_back(0.4);
wxChartsDoubleDataset::ptr dataset2(new wxChartsDoubleDataset(points2));
chartData->AddDataset(dataset2);
// Create a column chart widget
wxColumnChartCtrl* columnChartCtrl = new wxColumnChartCtrl(panel, wxID_ANY, chartData);
// Create a bar chart widget
wxBarChartCtrl* barChartCtrl = new wxBarChartCtrl(panel, wxID_ANY, chartData);
// Create a stacked column chart widget
wxStackedColumnChartCtrl* stackedColumnChartCtrl = new wxStackedColumnChartCtrl(panel, wxID_ANY, chartData);
// Create a stacked bar chart widget
wxStackedBarChartCtrl* stackedBarChartCtrl = new wxStackedBarChartCtrl(panel, wxID_ANY, chartData);
// Set up the sizer for the bar and column charts
wxBoxSizer* firstSizer = new wxBoxSizer(wxHORIZONTAL);
firstSizer->Add(columnChartCtrl, 1, wxEXPAND);
firstSizer->Add(barChartCtrl, 1, wxEXPAND);
// Set up the sizer for the stacked bar and stacked column charts
wxBoxSizer* secondSizer = new wxBoxSizer(wxHORIZONTAL);
secondSizer->Add(stackedColumnChartCtrl, 1, wxEXPAND);
secondSizer->Add(stackedBarChartCtrl, 1, wxEXPAND);
// Set up the sizer for the panel
wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL);
panelSizer->Add(firstSizer, 1, wxEXPAND);
panelSizer->Add(secondSizer, 1, wxEXPAND);
panel->SetSizer(panelSizer);
// Set up the sizer for the frame
wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);
topSizer->Add(panel, 1, wxEXPAND);
SetSizerAndFit(topSizer);
}
|
/*
Copyright (c) 2018-2019 Xavier Leclercq
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 "frame.h"
#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/charts/wxcharts.h>
Frame::Frame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title)
{
// Create a top-level panel to hold all the contents of the frame
wxPanel* panel = new wxPanel(this, wxID_ANY);
// Create the data for the bar chart widget
wxVector<wxString> labels;
labels.push_back("January");
labels.push_back("February");
labels.push_back("March");
labels.push_back("April");
labels.push_back("May");
labels.push_back("June");
labels.push_back("July");
wxChartsCategoricalData::ptr chartData = wxChartsCategoricalData::make_shared(labels);
// Add the first dataset
wxVector<wxDouble> points1;
points1.push_back(3);
points1.push_back(2.5);
points1.push_back(1.2);
points1.push_back(3);
points1.push_back(6);
points1.push_back(5);
points1.push_back(1);
wxChartsDoubleDataset::ptr dataset1(new wxChartsDoubleDataset("Dataset 1", points1));
chartData->AddDataset(dataset1);
// Add the second dataset
wxVector<wxDouble> points2;
points2.push_back(1);
points2.push_back(1.33);
points2.push_back(2.5);
points2.push_back(2);
points2.push_back(3);
points2.push_back(1.8);
points2.push_back(0.4);
wxChartsDoubleDataset::ptr dataset2(new wxChartsDoubleDataset("Dataset 2", points2));
chartData->AddDataset(dataset2);
// Create a column chart widget
wxColumnChartCtrl* columnChartCtrl = new wxColumnChartCtrl(panel, wxID_ANY, chartData);
// Create a bar chart widget
wxBarChartCtrl* barChartCtrl = new wxBarChartCtrl(panel, wxID_ANY, chartData);
// Create a stacked column chart widget
wxStackedColumnChartCtrl* stackedColumnChartCtrl = new wxStackedColumnChartCtrl(panel, wxID_ANY, chartData);
// Create a stacked bar chart widget
wxStackedBarChartCtrl* stackedBarChartCtrl = new wxStackedBarChartCtrl(panel, wxID_ANY, chartData);
// Set up the sizer for the bar and column charts
wxBoxSizer* firstSizer = new wxBoxSizer(wxHORIZONTAL);
firstSizer->Add(columnChartCtrl, 1, wxEXPAND);
firstSizer->Add(barChartCtrl, 1, wxEXPAND);
// Set up the sizer for the stacked bar and stacked column charts
wxBoxSizer* secondSizer = new wxBoxSizer(wxHORIZONTAL);
secondSizer->Add(stackedColumnChartCtrl, 1, wxEXPAND);
secondSizer->Add(stackedBarChartCtrl, 1, wxEXPAND);
// Set up the sizer for the panel
wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL);
panelSizer->Add(firstSizer, 1, wxEXPAND);
panelSizer->Add(secondSizer, 1, wxEXPAND);
panel->SetSizer(panelSizer);
// Set up the sizer for the frame
wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);
topSizer->Add(panel, 1, wxEXPAND);
SetSizerAndFit(topSizer);
}
|
Fix sample
|
Fix sample
|
C++
|
mit
|
wxIshiko/wxCharts,wxIshiko/wxCharts
|
f11c50e3444232129d0c326f124e46c18f9d0a69
|
jni/MPACK/Graphics/Texture/Image/PNGImage.cpp
|
jni/MPACK/Graphics/Texture/Image/PNGImage.cpp
|
#include "PNGImage.hpp"
#include "Resource.hpp"
#include "SDInputFile.hpp"
#include "Asset.hpp"
#include "Misc.hpp"
#include "Log.hpp"
using namespace MPACK::Core;
namespace MPACK
{
namespace Graphics
{
PNGImage::PNGImage()
: m_imageBuffer(NULL)
{
}
PNGImage::~PNGImage()
{
Unload();
}
ReturnValue PNGImage::Load(const std::string& filename)
{
LOGI("PNGImage::Load Loading texture %s", filename.c_str());
Resource *pResource=LoadResource(filename.c_str());
png_byte header[8];
png_structp pngPtr = NULL;
png_infop infoPtr = NULL;
png_bytep* rowPtrs = NULL;
png_int_32 rowSize;
bool transparency;
// Opens and checks image signature (first 8 bytes).
if (pResource->Open() != RETURN_VALUE_OK)
{
goto ERROR_LABEL;
}
if (pResource->Read(header, sizeof(header)) != RETURN_VALUE_OK)
{
goto ERROR_LABEL;
}
if (png_sig_cmp(header, 0, 8) != 0)
{
goto ERROR_LABEL;
}
// Creates required structures.
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!pngPtr)
{
LOGE("PNGImage::Load failed to create read structure!");
goto ERROR_LABEL;
}
infoPtr = png_create_info_struct(pngPtr);
if (!infoPtr)
{
goto ERROR_LABEL;
}
// Prepares reading operation by setting-up a read callback.
png_set_read_fn(pngPtr, pResource, callback_read);
// Set-up error management. If an error occurs while reading,
// code will come back here and jump
if (setjmp(png_jmpbuf(pngPtr)))
{
goto ERROR_LABEL;
}
// Ignores first 8 bytes already read and processes header.
png_set_sig_bytes(pngPtr, 8);
png_read_info(pngPtr, infoPtr);
// Retrieves PNG info and updates PNG struct accordingly.
int depth, colorType;
png_uint_32 width, height;
png_get_IHDR(pngPtr, infoPtr, &width, &height, &depth, &colorType, NULL, NULL, NULL);
m_width = width; m_height = height;
// Creates a full alpha channel if transparency is encoded as
// an array of palette entries or a single transparent color.
transparency = false;
if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS))
{
png_set_tRNS_to_alpha(pngPtr);
transparency = true;
return RETURN_VALUE_KO;
//goto ERROR_LABEL;
}
// Expands PNG with less than 8bits per channel to 8bits.
if (depth < 8)
{
png_set_packing (pngPtr);
// Shrinks PNG with 16bits per color channel down to 8bits.
}
else if (depth == 16)
{
png_set_strip_16(pngPtr);
}
// Indicates that image needs conversion to RGBA if needed.
m_alphaChannel = transparency;
switch (colorType)
{
case PNG_COLOR_TYPE_PALETTE:
png_set_palette_to_rgb(pngPtr);
m_format = transparency ? GL_RGBA : GL_RGB;
break;
case PNG_COLOR_TYPE_RGB:
m_format = transparency ? GL_RGBA : GL_RGB;
break;
case PNG_COLOR_TYPE_RGBA:
m_format = GL_RGBA;
m_alphaChannel=true;
break;
case PNG_COLOR_TYPE_GRAY:
png_set_expand_gray_1_2_4_to_8(pngPtr);
m_format = transparency ? GL_LUMINANCE_ALPHA:GL_LUMINANCE;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
png_set_expand_gray_1_2_4_to_8(pngPtr);
m_format = GL_LUMINANCE_ALPHA;
m_alphaChannel=true;
break;
}
// Validates all tranformations.
png_read_update_info(pngPtr, infoPtr);
m_bytesPerPixel=GetBPP(m_format);
// Get row size in bytes.
rowSize = png_get_rowbytes(pngPtr, infoPtr);
if (rowSize <= 0)
{
goto ERROR_LABEL;
}
// Ceates the image buffer that will be sent to OpenGL.
m_imageBuffer = new png_byte[rowSize * height];
LOGD("rowSize * height = %d", rowSize * height);
if (!m_imageBuffer)
{
goto ERROR_LABEL;
}
// Pointers to each row of the image buffer. Row order is
// inverted because different coordinate systems are used by
// OpenGL (1st pixel is at bottom left) and PNGs (top-left).
rowPtrs = new png_bytep[height];
if (!rowPtrs)
{
goto ERROR_LABEL;
}
for (::int32_t i = 0; i < height; ++i)
{
rowPtrs[height - (i + 1)] = m_imageBuffer + i * rowSize;
}
// Reads image content.
png_read_image(pngPtr, rowPtrs);
// Frees memory and resources.
pResource->Close();
delete pResource;
png_destroy_read_struct(&pngPtr, &infoPtr, NULL);
delete[] rowPtrs;
return RETURN_VALUE_OK;
ERROR_LABEL:
LOGE("Error while reading PNG file");
pResource->Close();
delete pResource;
if(rowPtrs)
{
delete[] rowPtrs;
}
if(m_imageBuffer)
{
delete[] m_imageBuffer;
}
if(pngPtr)
{
png_infop* infoPtrP = infoPtr != NULL ? &infoPtr: NULL;
png_destroy_read_struct(&pngPtr, infoPtrP, NULL);
}
return RETURN_VALUE_KO;
}
void PNGImage::Unload()
{
m_width=0;
m_height=0;
m_format=0;
delete[] m_imageBuffer;
}
const BYTE* PNGImage::GetImageData() const
{
return m_imageBuffer;
}
const BYTE* PNGImage::GetPixelPointer(GLushort x, GLushort y) const
{
int index=x*m_width+y;
index*=m_bytesPerPixel;
return m_imageBuffer+index;
}
Color PNGImage::GetPixel(GLushort x, GLushort y) const
{
int index=x*m_width+y;
index*=m_bytesPerPixel;
if (m_bytesPerPixel == 4)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], m_imageBuffer[index+3]);
}
else if(m_bytesPerPixel == 3)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], 255);
}
else if(m_bytesPerPixel == 2)
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], m_imageBuffer[index+1]);
}
else
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], 255);
}
}
void PNGImage::FlipVertical()
{
for(int i=0;i<(m_width>>1);++i)
{
for(int j=0;j<m_height;++j)
{
int offset1=i*m_width+j;
offset1*=m_bytesPerPixel;
int vi=m_width-i-1;
int vj=j;
int offset2=vi*m_width+vj;
offset2*=m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer+offset1),(char*)(m_imageBuffer+offset2),m_bytesPerPixel);
}
}
}
void PNGImage::FlipHorizontal()
{
for(int i=0;i<m_width;++i)
{
for(int j=0;j<(m_height>>1);++j)
{
int offset1=i*m_width+j;
offset1*=m_bytesPerPixel;
int vi=i;
int vj=m_height-j+1;
int offset2=vi*m_width+vj;
offset2*=m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer+offset1),(char*)(m_imageBuffer+offset2),m_bytesPerPixel);
}
}
}
void PNGImage::callback_read(png_structp pStruct, png_bytep pData, png_size_t pSize)
{
Resource* lResource = ((Resource*) png_get_io_ptr(pStruct));
if (lResource->Read(pData, pSize) != RETURN_VALUE_OK)
{
lResource->Close();
}
}
}
}
|
#include "PNGImage.hpp"
#include "Resource.hpp"
#include "SDInputFile.hpp"
#include "Asset.hpp"
#include "Misc.hpp"
#include "Log.hpp"
using namespace MPACK::Core;
namespace MPACK
{
namespace Graphics
{
PNGImage::PNGImage()
: m_imageBuffer(NULL)
{
}
PNGImage::~PNGImage()
{
Unload();
}
ReturnValue PNGImage::Load(const std::string& filename)
{
LOGI("PNGImage::Load Loading texture %s", filename.c_str());
Resource *pResource=LoadResource(filename.c_str());
png_byte header[8];
png_structp pngPtr = NULL;
png_infop infoPtr = NULL;
png_bytep* rowPtrs = NULL;
png_int_32 rowSize;
bool transparency;
// Opens and checks image signature (first 8 bytes).
if (pResource->Open() != RETURN_VALUE_OK)
{
goto ERROR_LABEL;
}
if (pResource->Read(header, sizeof(header)) != RETURN_VALUE_OK)
{
goto ERROR_LABEL;
}
if (png_sig_cmp(header, 0, 8) != 0)
{
goto ERROR_LABEL;
}
// Creates required structures.
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!pngPtr)
{
LOGE("PNGImage::Load failed to create read structure!");
goto ERROR_LABEL;
}
infoPtr = png_create_info_struct(pngPtr);
if (!infoPtr)
{
goto ERROR_LABEL;
}
// Prepares reading operation by setting-up a read callback.
png_set_read_fn(pngPtr, pResource, callback_read);
// Set-up error management. If an error occurs while reading,
// code will come back here and jump
if (setjmp(png_jmpbuf(pngPtr)))
{
goto ERROR_LABEL;
}
// Ignores first 8 bytes already read and processes header.
png_set_sig_bytes(pngPtr, 8);
png_read_info(pngPtr, infoPtr);
// Retrieves PNG info and updates PNG struct accordingly.
int depth, colorType;
png_uint_32 width, height;
png_get_IHDR(pngPtr, infoPtr, &width, &height, &depth, &colorType, NULL, NULL, NULL);
m_width = width; m_height = height;
// Creates a full alpha channel if transparency is encoded as
// an array of palette entries or a single transparent color.
transparency = false;
if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS))
{
png_set_tRNS_to_alpha(pngPtr);
transparency = true;
return RETURN_VALUE_KO;
//goto ERROR_LABEL;
}
// Expands PNG with less than 8bits per channel to 8bits.
if (depth < 8)
{
png_set_packing (pngPtr);
// Shrinks PNG with 16bits per color channel down to 8bits.
}
else if (depth == 16)
{
png_set_strip_16(pngPtr);
}
// Indicates that image needs conversion to RGBA if needed.
m_alphaChannel = transparency;
switch (colorType)
{
case PNG_COLOR_TYPE_PALETTE:
png_set_palette_to_rgb(pngPtr);
m_format = transparency ? GL_RGBA : GL_RGB;
break;
case PNG_COLOR_TYPE_RGB:
m_format = transparency ? GL_RGBA : GL_RGB;
break;
case PNG_COLOR_TYPE_RGBA:
m_format = GL_RGBA;
m_alphaChannel=true;
break;
case PNG_COLOR_TYPE_GRAY:
png_set_expand_gray_1_2_4_to_8(pngPtr);
m_format = transparency ? GL_LUMINANCE_ALPHA:GL_LUMINANCE;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
png_set_expand_gray_1_2_4_to_8(pngPtr);
m_format = GL_LUMINANCE_ALPHA;
m_alphaChannel=true;
break;
}
// Validates all tranformations.
png_read_update_info(pngPtr, infoPtr);
m_bytesPerPixel=GetBPP(m_format);
// Get row size in bytes.
rowSize = png_get_rowbytes(pngPtr, infoPtr);
if (rowSize <= 0)
{
goto ERROR_LABEL;
}
// Ceates the image buffer that will be sent to OpenGL.
m_imageBuffer = new png_byte[rowSize * height];
if (!m_imageBuffer)
{
goto ERROR_LABEL;
}
// Pointers to each row of the image buffer. Row order is
// inverted because different coordinate systems are used by
// OpenGL (1st pixel is at bottom left) and PNGs (top-left).
rowPtrs = new png_bytep[height];
if (!rowPtrs)
{
goto ERROR_LABEL;
}
for (::int32_t i = 0; i < height; ++i)
{
rowPtrs[height - (i + 1)] = m_imageBuffer + i * rowSize;
}
// Reads image content.
png_read_image(pngPtr, rowPtrs);
// Frees memory and resources.
pResource->Close();
delete pResource;
png_destroy_read_struct(&pngPtr, &infoPtr, NULL);
delete[] rowPtrs;
return RETURN_VALUE_OK;
ERROR_LABEL:
LOGE("Error while reading PNG file");
pResource->Close();
delete pResource;
if(rowPtrs)
{
delete[] rowPtrs;
}
if(m_imageBuffer)
{
delete[] m_imageBuffer;
}
if(pngPtr)
{
png_infop* infoPtrP = infoPtr != NULL ? &infoPtr: NULL;
png_destroy_read_struct(&pngPtr, infoPtrP, NULL);
}
return RETURN_VALUE_KO;
}
void PNGImage::Unload()
{
m_width=0;
m_height=0;
m_format=0;
delete[] m_imageBuffer;
}
const BYTE* PNGImage::GetImageData() const
{
return m_imageBuffer;
}
const BYTE* PNGImage::GetPixelPointer(GLushort x, GLushort y) const
{
int index=x*m_width+y;
index*=m_bytesPerPixel;
return m_imageBuffer+index;
}
Color PNGImage::GetPixel(GLushort x, GLushort y) const
{
int index=x*m_width+y;
index*=m_bytesPerPixel;
if (m_bytesPerPixel == 4)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], m_imageBuffer[index+3]);
}
else if(m_bytesPerPixel == 3)
{
return Color(m_imageBuffer[index], m_imageBuffer[index+1],
m_imageBuffer[index+2], 255);
}
else if(m_bytesPerPixel == 2)
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], m_imageBuffer[index+1]);
}
else
{
return Color(m_imageBuffer[index], m_imageBuffer[index],
m_imageBuffer[index], 255);
}
}
void PNGImage::FlipVertical()
{
for(int i=0;i<(m_width>>1);++i)
{
for(int j=0;j<m_height;++j)
{
int offset1=i*m_width+j;
offset1*=m_bytesPerPixel;
int vi=m_width-i-1;
int vj=j;
int offset2=vi*m_width+vj;
offset2*=m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer+offset1),(char*)(m_imageBuffer+offset2),m_bytesPerPixel);
}
}
}
void PNGImage::FlipHorizontal()
{
for(int i=0;i<m_width;++i)
{
for(int j=0;j<(m_height>>1);++j)
{
int offset1=i*m_width+j;
offset1*=m_bytesPerPixel;
int vi=i;
int vj=m_height-j+1;
int offset2=vi*m_width+vj;
offset2*=m_bytesPerPixel;
StringEx::MemSwap((char*)(m_imageBuffer+offset1),(char*)(m_imageBuffer+offset2),m_bytesPerPixel);
}
}
}
void PNGImage::callback_read(png_structp pStruct, png_bytep pData, png_size_t pSize)
{
Resource* lResource = ((Resource*) png_get_io_ptr(pStruct));
if (lResource->Read(pData, pSize) != RETURN_VALUE_OK)
{
lResource->Close();
}
}
}
}
|
Remove debug message
|
Remove debug message
|
C++
|
apache-2.0
|
links234/MPACK,links234/MPACK,links234/MPACK,links234/MPACK,links234/MPACK
|
af3ab4586751aab7b3169c00478bff6a67ee5f06
|
test/test_vector_test.cc
|
test/test_vector_test.cc
|
/*
* Copyright (c) 2013 The WebM 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 <cstdio>
#include <cstdlib>
#include <set>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "../tools_common.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/md5_helper.h"
#include "test/test_vectors.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"
namespace {
const int kThreads = 0;
const int kFileName = 1;
typedef std::tr1::tuple<int, const char *> DecodeParam;
class TestVectorTest : public ::libvpx_test::DecoderTest,
public ::libvpx_test::CodecTestWithParam<DecodeParam> {
protected:
TestVectorTest() : DecoderTest(GET_PARAM(0)), md5_file_(NULL) {
#if CONFIG_VP9_DECODER
resize_clips_.insert(::libvpx_test::kVP9TestVectorsResize,
::libvpx_test::kVP9TestVectorsResize +
::libvpx_test::kNumVP9TestVectorsResize);
#endif
}
virtual ~TestVectorTest() {
if (md5_file_) fclose(md5_file_);
}
void OpenMD5File(const std::string &md5_file_name_) {
md5_file_ = libvpx_test::OpenTestDataFile(md5_file_name_);
ASSERT_TRUE(md5_file_ != NULL) << "Md5 file open failed. Filename: "
<< md5_file_name_;
}
virtual void DecompressedFrameHook(const vpx_image_t &img,
const unsigned int frame_number) {
ASSERT_TRUE(md5_file_ != NULL);
char expected_md5[33];
char junk[128];
// Read correct md5 checksums.
const int res = fscanf(md5_file_, "%s %s", expected_md5, junk);
ASSERT_NE(res, EOF) << "Read md5 data failed";
expected_md5[32] = '\0';
::libvpx_test::MD5 md5_res;
md5_res.Add(&img);
const char *actual_md5 = md5_res.Get();
// Check md5 match.
ASSERT_STREQ(expected_md5, actual_md5)
<< "Md5 checksums don't match: frame number = " << frame_number;
}
#if CONFIG_VP9_DECODER
std::set<std::string> resize_clips_;
#endif
private:
FILE *md5_file_;
};
// This test runs through the whole set of test vectors, and decodes them.
// The md5 checksums are computed for each frame in the video file. If md5
// checksums match the correct md5 data, then the test is passed. Otherwise,
// the test failed.
TEST_P(TestVectorTest, MD5Match) {
const DecodeParam input = GET_PARAM(1);
const std::string filename = std::tr1::get<kFileName>(input);
vpx_codec_flags_t flags = 0;
vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
char str[256];
cfg.threads = std::tr1::get<kThreads>(input);
snprintf(str, sizeof(str) / sizeof(str[0]) - 1, "file: %s threads: %d",
filename.c_str(), cfg.threads);
SCOPED_TRACE(str);
// Open compressed video file.
testing::internal::scoped_ptr<libvpx_test::CompressedVideoSource> video;
if (filename.substr(filename.length() - 3, 3) == "ivf") {
video.reset(new libvpx_test::IVFVideoSource(filename));
} else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
video.reset(new libvpx_test::WebMVideoSource(filename));
#else
fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
filename.c_str());
return;
#endif
}
ASSERT_TRUE(video.get() != NULL);
video->Init();
// Construct md5 file name.
const std::string md5_filename = filename + ".md5";
OpenMD5File(md5_filename);
// Set decode config and flags.
set_cfg(cfg);
set_flags(flags);
// Decode frame, and check the md5 matching.
ASSERT_NO_FATAL_FAILURE(RunLoop(video.get(), cfg));
}
#if CONFIG_VP8_DECODER
VP8_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP8TestVectors,
libvpx_test::kVP8TestVectors +
libvpx_test::kNumVP8TestVectors)));
// Test VP8 decode in with different numbers of threads.
INSTANTIATE_TEST_CASE_P(
VP8MultiThreaded, TestVectorTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP8)),
::testing::Combine(
::testing::Range(1, 8), // With 1 ~ 8 threads.
::testing::ValuesIn(libvpx_test::kVP8TestVectors,
libvpx_test::kVP8TestVectors +
libvpx_test::kNumVP8TestVectors))));
#endif // CONFIG_VP8_DECODER
#if CONFIG_VP9_DECODER
VP9_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors)));
INSTANTIATE_TEST_CASE_P(
VP9MultiThreaded, TestVectorTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)),
::testing::Combine(
::testing::Range(2, 9), // With 2 ~ 8 threads.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors))));
#endif
} // namespace
|
/*
* Copyright (c) 2013 The WebM 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 <cstdio>
#include <cstdlib>
#include <set>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "../tools_common.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/md5_helper.h"
#include "test/test_vectors.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"
namespace {
const int kThreads = 0;
const int kFileName = 1;
typedef std::tr1::tuple<int, const char *> DecodeParam;
class TestVectorTest : public ::libvpx_test::DecoderTest,
public ::libvpx_test::CodecTestWithParam<DecodeParam> {
protected:
TestVectorTest() : DecoderTest(GET_PARAM(0)), md5_file_(NULL) {
#if CONFIG_VP9_DECODER
resize_clips_.insert(::libvpx_test::kVP9TestVectorsResize,
::libvpx_test::kVP9TestVectorsResize +
::libvpx_test::kNumVP9TestVectorsResize);
#endif
}
virtual ~TestVectorTest() {
if (md5_file_) fclose(md5_file_);
}
void OpenMD5File(const std::string &md5_file_name_) {
md5_file_ = libvpx_test::OpenTestDataFile(md5_file_name_);
ASSERT_TRUE(md5_file_ != NULL) << "Md5 file open failed. Filename: "
<< md5_file_name_;
}
virtual void DecompressedFrameHook(const vpx_image_t &img,
const unsigned int frame_number) {
ASSERT_TRUE(md5_file_ != NULL);
char expected_md5[33];
char junk[128];
// Read correct md5 checksums.
const int res = fscanf(md5_file_, "%s %s", expected_md5, junk);
ASSERT_NE(res, EOF) << "Read md5 data failed";
expected_md5[32] = '\0';
::libvpx_test::MD5 md5_res;
md5_res.Add(&img);
const char *actual_md5 = md5_res.Get();
// Check md5 match.
ASSERT_STREQ(expected_md5, actual_md5)
<< "Md5 checksums don't match: frame number = " << frame_number;
}
#if CONFIG_VP9_DECODER
std::set<std::string> resize_clips_;
#endif
private:
FILE *md5_file_;
};
// This test runs through the whole set of test vectors, and decodes them.
// The md5 checksums are computed for each frame in the video file. If md5
// checksums match the correct md5 data, then the test is passed. Otherwise,
// the test failed.
TEST_P(TestVectorTest, MD5Match) {
const DecodeParam input = GET_PARAM(1);
const std::string filename = std::tr1::get<kFileName>(input);
vpx_codec_flags_t flags = 0;
vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
char str[256];
cfg.threads = std::tr1::get<kThreads>(input);
snprintf(str, sizeof(str) / sizeof(str[0]) - 1, "file: %s threads: %d",
filename.c_str(), cfg.threads);
SCOPED_TRACE(str);
// Open compressed video file.
testing::internal::scoped_ptr<libvpx_test::CompressedVideoSource> video;
if (filename.substr(filename.length() - 3, 3) == "ivf") {
video.reset(new libvpx_test::IVFVideoSource(filename));
} else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
video.reset(new libvpx_test::WebMVideoSource(filename));
#else
fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
filename.c_str());
return;
#endif
}
ASSERT_TRUE(video.get() != NULL);
video->Init();
// Construct md5 file name.
const std::string md5_filename = filename + ".md5";
OpenMD5File(md5_filename);
// Set decode config and flags.
set_cfg(cfg);
set_flags(flags);
// Decode frame, and check the md5 matching.
ASSERT_NO_FATAL_FAILURE(RunLoop(video.get(), cfg));
}
#if CONFIG_VP8_DECODER
VP8_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP8TestVectors,
libvpx_test::kVP8TestVectors +
libvpx_test::kNumVP8TestVectors)));
// Test VP8 decode in with different numbers of threads.
INSTANTIATE_TEST_CASE_P(
VP8MultiThreaded, TestVectorTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP8)),
::testing::Combine(
::testing::Range(2, 9), // With 2 ~ 8 threads.
::testing::ValuesIn(libvpx_test::kVP8TestVectors,
libvpx_test::kVP8TestVectors +
libvpx_test::kNumVP8TestVectors))));
#endif // CONFIG_VP8_DECODER
#if CONFIG_VP9_DECODER
VP9_INSTANTIATE_TEST_CASE(
TestVectorTest,
::testing::Combine(
::testing::Values(1), // Single thread.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors)));
INSTANTIATE_TEST_CASE_P(
VP9MultiThreaded, TestVectorTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)),
::testing::Combine(
::testing::Range(2, 9), // With 2 ~ 8 threads.
::testing::ValuesIn(libvpx_test::kVP9TestVectors,
libvpx_test::kVP9TestVectors +
libvpx_test::kNumVP9TestVectors))));
#endif
} // namespace
|
correct thread range
|
test_vector_test,vp8: correct thread range
testing::Range does not include the end parameter in the set of values.
also adjust the start to 2 as the single threaded case is already
covered in another instantiation
Change-Id: Iae3bf3ed4363dd434eccfa5ad4e3c5e553fbee60
|
C++
|
bsd-3-clause
|
ShiftMediaProject/libvpx,ShiftMediaProject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx,webmproject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx,webmproject/libvpx,webmproject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx
|
e70ad59bab02edbc91bffbef272e893d88736bef
|
sb_topic_transport/src/tcp/tcp_receiver.cpp
|
sb_topic_transport/src/tcp/tcp_receiver.cpp
|
// TCP receiver
// Author: Max Schwarz <[email protected]>
#include "tcp_receiver.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include "tcp_packet.h"
#include "../topic_info.h"
#include <topic_tools/shape_shifter.h>
#include <bzlib.h>
namespace sb_topic_transport
{
static bool sureRead(int fd, void* dest, ssize_t size)
{
ssize_t ret = read(fd, dest, size);
if(ret < 0)
{
ROS_ERROR("Could not read(): %s", strerror(errno));
return false;
}
if(ret == 0)
{
// Client has closed connection (ignore silently)
return false;
}
if(ret != size)
{
ROS_ERROR("Invalid read size %d (expected %d)", (int)ret, (int)size);
return false;
}
return true;
}
TCPReceiver::TCPReceiver()
: m_nh("~")
{
m_fd = socket(AF_INET, SOCK_STREAM, 0);
if(m_fd < 0)
{
ROS_FATAL("Could not create socket: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
int port;
m_nh.param("port", port, 5050);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
int on = 1;
if(setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0)
{
ROS_FATAL("Could not enable SO_REUSEADDR: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
ROS_DEBUG("Binding to :%d", port);
if(bind(m_fd, (sockaddr*)&addr, sizeof(addr)) != 0)
{
ROS_FATAL("Could not bind socket: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
if(listen(m_fd, 10) != 0)
{
ROS_FATAL("Could not listen: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
}
TCPReceiver::~TCPReceiver()
{
}
void TCPReceiver::run()
{
fd_set fds;
while(ros::ok())
{
ros::spinOnce();
// Clean up any exited threads
std::list<ClientHandler*>::iterator it = m_handlers.begin();
while(it != m_handlers.end())
{
if(!(*it)->isRunning())
{
delete *it;
it = m_handlers.erase(it);
}
else
it++;
}
FD_ZERO(&fds);
FD_SET(m_fd, &fds);
timeval timeout;
timeout.tv_usec = 0;
timeout.tv_sec = 1;
int ret = select(m_fd+1, &fds, 0, 0, &timeout);
if(ret < 0)
{
if(errno == EINTR || errno == EAGAIN)
continue;
ROS_ERROR("Could not select(): %s", strerror(errno));
throw std::runtime_error("Could not select");
}
if(ret == 0)
continue;
int client_fd = accept(m_fd, 0, 0);
m_handlers.push_back(
new ClientHandler(client_fd)
);
}
}
TCPReceiver::ClientHandler::ClientHandler(int fd)
: m_fd(fd)
, m_running(true)
{
m_thread = boost::thread(boost::bind(&ClientHandler::start, this));
}
TCPReceiver::ClientHandler::~ClientHandler()
{
close(m_fd);
}
class VectorStream
{
public:
VectorStream(std::vector<uint8_t>* vector)
: m_vector(vector)
{}
inline const uint8_t* getData()
{ return m_vector->data(); }
inline size_t getLength()
{ return m_vector->size(); }
private:
std::vector<uint8_t>* m_vector;
};
void TCPReceiver::ClientHandler::start()
{
run();
m_running = false;
}
void TCPReceiver::ClientHandler::run()
{
while(1)
{
TCPHeader header;
if(!sureRead(m_fd, &header, sizeof(header)))
return;
std::vector<char> buf(header.topic_len + 1);
if(!sureRead(m_fd, buf.data(), header.topic_len))
return;
buf[buf.size()-1] = 0;
std::string topic(buf.data());
buf.resize(header.type_len+1);
if(!sureRead(m_fd, buf.data(), header.type_len))
return;
buf[buf.size()-1] = 0;
std::string type(buf.data());
std::string md5;
topic_info::unpackMD5(header.topic_md5sum, &md5);
std::vector<uint8_t> data(header.data_len);
if(!sureRead(m_fd, data.data(), header.data_len))
return;
topic_tools::ShapeShifter shifter;
if(header.flags() & TCP_FLAG_COMPRESSED)
{
int ret = 0;
unsigned int len = m_uncompressBuf.size();
while(1)
{
int ret = BZ2_bzBuffToBuffDecompress((char*)m_uncompressBuf.data(), &len, (char*)data.data(), data.size(), 0, 0);
if(ret == BZ_OUTBUFF_FULL)
{
ROS_INFO("Increasing buffer size...");
m_uncompressBuf.resize(m_uncompressBuf.size() * 2);
continue;
}
else
break;
}
if(ret != BZ_OK)
{
ROS_ERROR("Could not decompress bz2 data, dropping msg");
continue;
}
VectorStream stream(&m_uncompressBuf);
shifter.read(stream);
}
else
{
VectorStream stream(&data);
shifter.read(stream);
}
ROS_DEBUG("Got message from topic '%s' (type '%s', md5 '%s')", topic.c_str(), type.c_str(), md5.c_str());
shifter.morph(md5, type, "", "");
std::map<std::string, ros::Publisher>::iterator it = m_pub.find(topic);
if(it == m_pub.end())
{
ROS_DEBUG("Advertising new topic '%s'", topic.c_str());
std::string msgDef = topic_info::getMsgDef(type);
ros::NodeHandle nh;
ros::AdvertiseOptions options(
topic,
2,
md5,
type,
topic_info::getMsgDef(type)
);
// It will take subscribers some time to connect to our publisher.
// Therefore, latch messages so they will not be lost.
options.latch = true;
m_pub[topic] = nh.advertise(options);
it = m_pub.find(topic);
}
it->second.publish(shifter);
uint8_t ack = 1;
if(write(m_fd, &ack, 1) != 1)
{
ROS_ERROR("Could not write(): %s", strerror(errno));
return;
}
}
}
bool TCPReceiver::ClientHandler::isRunning() const
{
return m_running;
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "tcp_receiver");
sb_topic_transport::TCPReceiver recv;
recv.run();
return 0;
}
|
// TCP receiver
// Author: Max Schwarz <[email protected]>
#include "tcp_receiver.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include "tcp_packet.h"
#include "../topic_info.h"
#include <topic_tools/shape_shifter.h>
#include <bzlib.h>
namespace sb_topic_transport
{
static bool sureRead(int fd, void* dest, ssize_t size)
{
ssize_t ret = read(fd, dest, size);
if(ret < 0)
{
ROS_ERROR("Could not read(): %s", strerror(errno));
return false;
}
if(ret == 0)
{
// Client has closed connection (ignore silently)
return false;
}
if(ret != size)
{
ROS_ERROR("Invalid read size %d (expected %d)", (int)ret, (int)size);
return false;
}
return true;
}
TCPReceiver::TCPReceiver()
: m_nh("~")
{
m_fd = socket(AF_INET, SOCK_STREAM, 0);
if(m_fd < 0)
{
ROS_FATAL("Could not create socket: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
int port;
m_nh.param("port", port, 5050);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
int on = 1;
if(setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0)
{
ROS_FATAL("Could not enable SO_REUSEADDR: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
ROS_DEBUG("Binding to :%d", port);
if(bind(m_fd, (sockaddr*)&addr, sizeof(addr)) != 0)
{
ROS_FATAL("Could not bind socket: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
if(listen(m_fd, 10) != 0)
{
ROS_FATAL("Could not listen: %s", strerror(errno));
throw std::runtime_error(strerror(errno));
}
}
TCPReceiver::~TCPReceiver()
{
}
void TCPReceiver::run()
{
fd_set fds;
while(ros::ok())
{
ros::spinOnce();
// Clean up any exited threads
std::list<ClientHandler*>::iterator it = m_handlers.begin();
while(it != m_handlers.end())
{
if(!(*it)->isRunning())
{
delete *it;
it = m_handlers.erase(it);
}
else
it++;
}
FD_ZERO(&fds);
FD_SET(m_fd, &fds);
timeval timeout;
timeout.tv_usec = 0;
timeout.tv_sec = 1;
int ret = select(m_fd+1, &fds, 0, 0, &timeout);
if(ret < 0)
{
if(errno == EINTR || errno == EAGAIN)
continue;
ROS_ERROR("Could not select(): %s", strerror(errno));
throw std::runtime_error("Could not select");
}
if(ret == 0)
continue;
int client_fd = accept(m_fd, 0, 0);
m_handlers.push_back(
new ClientHandler(client_fd)
);
}
}
TCPReceiver::ClientHandler::ClientHandler(int fd)
: m_fd(fd)
, m_uncompressBuf(1024)
, m_running(true)
{
m_thread = boost::thread(boost::bind(&ClientHandler::start, this));
}
TCPReceiver::ClientHandler::~ClientHandler()
{
close(m_fd);
}
class VectorStream
{
public:
VectorStream(std::vector<uint8_t>* vector)
: m_vector(vector)
{}
inline const uint8_t* getData()
{ return m_vector->data(); }
inline size_t getLength()
{ return m_vector->size(); }
private:
std::vector<uint8_t>* m_vector;
};
void TCPReceiver::ClientHandler::start()
{
run();
m_running = false;
}
void TCPReceiver::ClientHandler::run()
{
while(1)
{
TCPHeader header;
if(!sureRead(m_fd, &header, sizeof(header)))
return;
std::vector<char> buf(header.topic_len + 1);
if(!sureRead(m_fd, buf.data(), header.topic_len))
return;
buf[buf.size()-1] = 0;
std::string topic(buf.data());
buf.resize(header.type_len+1);
if(!sureRead(m_fd, buf.data(), header.type_len))
return;
buf[buf.size()-1] = 0;
std::string type(buf.data());
std::string md5;
topic_info::unpackMD5(header.topic_md5sum, &md5);
std::vector<uint8_t> data(header.data_len);
if(!sureRead(m_fd, data.data(), header.data_len))
return;
topic_tools::ShapeShifter shifter;
ROS_INFO("Got msg with flags: %d", header.flags());
if(header.flags() & TCP_FLAG_COMPRESSED)
{
int ret = 0;
unsigned int len = m_uncompressBuf.size();
while(1)
{
int ret = BZ2_bzBuffToBuffDecompress((char*)m_uncompressBuf.data(), &len, (char*)data.data(), data.size(), 0, 0);
if(ret == BZ_OUTBUFF_FULL)
{
len = 4 * m_uncompressBuf.size();
ROS_INFO("Increasing buffer size to %d KiB", (int)len / 1024);
m_uncompressBuf.resize(len);
continue;
}
else
break;
}
if(ret != BZ_OK)
{
ROS_ERROR("Could not decompress bz2 data, dropping msg");
continue;
}
ROS_INFO("decompress %d KiB to %d KiB", (int)data.size() / 1024, (int)len / 1024);
VectorStream stream(&m_uncompressBuf);
shifter.read(stream);
}
else
{
VectorStream stream(&data);
shifter.read(stream);
}
ROS_DEBUG("Got message from topic '%s' (type '%s', md5 '%s')", topic.c_str(), type.c_str(), md5.c_str());
shifter.morph(md5, type, "", "");
std::map<std::string, ros::Publisher>::iterator it = m_pub.find(topic);
if(it == m_pub.end())
{
ROS_DEBUG("Advertising new topic '%s'", topic.c_str());
std::string msgDef = topic_info::getMsgDef(type);
ros::NodeHandle nh;
ros::AdvertiseOptions options(
topic,
2,
md5,
type,
topic_info::getMsgDef(type)
);
// It will take subscribers some time to connect to our publisher.
// Therefore, latch messages so they will not be lost.
options.latch = true;
m_pub[topic] = nh.advertise(options);
it = m_pub.find(topic);
}
it->second.publish(shifter);
uint8_t ack = 1;
if(write(m_fd, &ack, 1) != 1)
{
ROS_ERROR("Could not write(): %s", strerror(errno));
return;
}
}
}
bool TCPReceiver::ClientHandler::isRunning() const
{
return m_running;
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "tcp_receiver");
sb_topic_transport::TCPReceiver recv;
recv.run();
return 0;
}
|
fix decompression
|
sb_topic_transport: fix decompression
|
C++
|
bsd-3-clause
|
dreuter/nimbro_network,AIS-Bonn/nimbro_network,dreuter/nimbro_network,dreuter/nimbro_network,AIS-Bonn/nimbro_network,AIS-Bonn/nimbro_network
|
b8ee0e19a78d81ce5573a0343c4e2c941e821bf2
|
include/commonpp/core/ExecuteOnScopeExit.hpp
|
include/commonpp/core/ExecuteOnScopeExit.hpp
|
/*
* File: ExecuteOnScopeExit.hpp
* Part of commonpp.
*
* Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2015 Thomas Sanchez. All rights reserved.
*
*/
#pragma once
#include <functional>
namespace commonpp
{
// compared to the boost one, this one can be cancelled.
template <typename Callable>
struct ExecuteOnScopeExit final
{
ExecuteOnScopeExit(Callable&& cb)
: fn(std::forward<Callable>(cb))
{
}
~ExecuteOnScopeExit()
{
if (!cancelled)
{
fn();
}
}
void cancel()
{
cancelled = true;
}
Callable fn;
bool cancelled = false;
};
template <typename Callable>
ExecuteOnScopeExit<Callable> execute_on_scope_exit(Callable&& callable)
{
return {std::forward<Callable>(callable)};
}
} // namespace commonpp
|
/*
* File: ExecuteOnScopeExit.hpp
* Part of commonpp.
*
* Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2015 Thomas Sanchez. All rights reserved.
*
*/
#pragma once
#include <functional>
namespace commonpp
{
// compared to the boost one, this one can be cancelled.
struct ExecuteOnScopeExit final
{
template <typename Callable>
ExecuteOnScopeExit(Callable&& cb)
: fn(std::forward<Callable>(cb))
{
}
ExecuteOnScopeExit(const ExecuteOnScopeExit&) = delete;
ExecuteOnScopeExit& operator=(const ExecuteOnScopeExit&) = delete;
~ExecuteOnScopeExit()
{
if (!cancelled)
{
fn();
}
}
void cancel()
{
cancelled = true;
}
std::function<void()> fn;
bool cancelled = false;
};
} // namespace commonpp
|
Fix wrong ExecuteOnScopeExit, I thought I already fixed it...
|
Fix wrong ExecuteOnScopeExit, I thought I already fixed it...
|
C++
|
bsd-2-clause
|
daedric/commonpp,daedric/commonpp
|
ebcf67a8131da1034809263a3627faeaa88fc7cf
|
PWG2/FLOW/Tools/glauberMC/runGlauberMCexample.C
|
PWG2/FLOW/Tools/glauberMC/runGlauberMCexample.C
|
{
//load libraries
gROOT->Macro("initGlauberMC.C");
//run the example code:
AliGlauberMC::runAndSaveNucleons(100);
AliGlauberMC::runAndSaveNtuple(100);
}
|
{
//load libraries
gROOT->Macro("initGlauberMC.C");
//run the example code:
//AliGlauberMC::runAndSaveNucleons(10000,"Pb","Pb",72);
AliGlauberMC::runAndSaveNtuple(10000,"Pb","Pb",72);
}
|
set defaults for PbPb at LHC
|
set defaults for PbPb at LHC
|
C++
|
bsd-3-clause
|
miranov25/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,shahor02/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,coppedis/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,alisw/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,alisw/AliRoot,sebaleh/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,coppedis/AliRoot
|
8b39d8e96b8e8d5ec59364e09928d5f78d47780f
|
HLT/BASE/AliHLTControlTask.cxx
|
HLT/BASE/AliHLTControlTask.cxx
|
// $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <[email protected]> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTControlTask.cxx
@author Matthias Richter
@date
@brief Special task to produce the control events.
*/
#include "AliHLTControlTask.h"
#include "AliHLTComponentHandler.h"
#include <cassert>
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTControlTask)
AliHLTControlTask::AliHLTControlTask()
: AliHLTTask()
, fBlocks()
, fpData(NULL)
, fSize(0)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTControlTask::~AliHLTControlTask()
{
// see header file for class documentation
ResetBlocks();
}
int AliHLTControlTask::CreateComponent(AliHLTConfiguration* /*pConf*/, AliHLTComponentHandler* pCH, AliHLTComponent*& pComponent) const
{
// see header file for class documentation
int iResult=0;
if ((pComponent=new AliHLTControlEventComponent(this))) {
const AliHLTAnalysisEnvironment* pEnv=pCH->GetEnvironment();
if ((iResult=pComponent->Init(pEnv, NULL, 0, NULL))>=0) {
//HLTDebug("component %s (%p) created", pComponent->GetComponentID(), pComponent);
} else {
HLTError("Initialization of component \"%s\" failed with error %d", pComponent->GetComponentID(), iResult);
}
return iResult;
}
return -ENOMEM;
}
void AliHLTControlTask::SetBlocks(const AliHLTComponentBlockDataList& list)
{
// see header file for class documentation
fBlocks.assign(list.begin(), list.end());
AliHLTComponentBlockDataList::iterator element=fBlocks.begin();
for (;element!=fBlocks.end(); element++) fSize+=element->fSize;
// allocate buffer for the payload of all blocks
fpData=new AliHLTUInt8_t[fSize];
AliHLTUInt8_t offset=0;
// copy and redirect
for (element=fBlocks.begin();element!=fBlocks.end(); element++) {
memcpy(fpData+offset, element->fPtr, element->fSize);
element->fPtr=fpData+offset;
offset+=element->fSize;
}
}
void AliHLTControlTask::ResetBlocks()
{
// see header file for class documentation
fBlocks.clear();
if (fpData) delete [] fpData;
fpData=NULL;
fSize=0;
}
AliHLTControlTask::AliHLTControlEventComponent::AliHLTControlEventComponent(const AliHLTControlTask* pParent)
:
fpParent(pParent)
{
// see header file for class documentation
assert(pParent);
}
AliHLTControlTask::AliHLTControlEventComponent::~AliHLTControlEventComponent()
{
// see header file for class documentation
}
AliHLTComponentDataType AliHLTControlTask::AliHLTControlEventComponent::GetOutputDataType()
{
// see header file for class documentation
return kAliHLTMultipleDataType;
}
int AliHLTControlTask::AliHLTControlEventComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
{
// see header file for class documentation
tgtList.clear();
tgtList.push_back(kAliHLTDataTypeSOR);
tgtList.push_back(kAliHLTDataTypeEOR);
return tgtList.size();
}
void AliHLTControlTask::AliHLTControlEventComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// see header file for class documentation
if (fpParent && fpParent->fSize>0) constBase=fpParent->fSize;
else constBase=0;
inputMultiplier=0;
}
int AliHLTControlTask::AliHLTControlEventComponent::GetEvent(const AliHLTComponentEventData& /*evtData*/,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
vector<AliHLTComponentBlockData>& outputBlocks )
{
// see header file for class documentation
if (!fpParent) return -ENODEV;
const AliHLTControlTask* pParent=fpParent;
AliHLTUInt32_t capacity=size;
size=0;
if (capacity<pParent->fSize) {
return -ENOSPC;
}
// return if no event has been set
if (pParent->fpData==NULL ||
pParent->fBlocks.size()==0) {
//HLTInfo("no control event to send");
return 0;
}
for (unsigned int i=0; i<pParent->fBlocks.size(); i++) {
HLTDebug("publishing control block %s", DataType2Text(pParent->fBlocks[i].fDataType).c_str());
memcpy(outputPtr+size, pParent->fBlocks[i].fPtr, pParent->fBlocks[i].fSize);
AliHLTComponentBlockData bd;
FillBlockData(bd);
bd.fOffset=size;
bd.fSize=pParent->fBlocks[i].fSize;
bd.fDataType=pParent->fBlocks[i].fDataType;
bd.fSpecification=pParent->fBlocks[i].fSpecification;
outputBlocks.push_back( bd );
size+=bd.fSize;
}
return size;
}
|
// $Id$
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Matthias Richter <[email protected]> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/** @file AliHLTControlTask.cxx
@author Matthias Richter
@date
@brief Special task to produce the control events.
*/
#include "AliHLTControlTask.h"
#include "AliHLTComponentHandler.h"
#include <cassert>
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTControlTask)
AliHLTControlTask::AliHLTControlTask()
: AliHLTTask()
, fBlocks()
, fpData(NULL)
, fSize(0)
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTControlTask::~AliHLTControlTask()
{
// see header file for class documentation
ResetBlocks();
}
int AliHLTControlTask::CreateComponent(AliHLTConfiguration* /*pConf*/, AliHLTComponentHandler* pCH, AliHLTComponent*& pComponent) const
{
// see header file for class documentation
int iResult=0;
if ((pComponent=new AliHLTControlEventComponent(this))) {
const AliHLTAnalysisEnvironment* pEnv=pCH->GetEnvironment();
const char* argv[]={
"-disable-component-stat"
};
int argc=sizeof(argv)/sizeof(const char*);
if ((iResult=pComponent->Init(pEnv, NULL, argc, argv))>=0) {
//HLTDebug("component %s (%p) created", pComponent->GetComponentID(), pComponent);
} else {
HLTError("Initialization of component \"%s\" failed with error %d", pComponent->GetComponentID(), iResult);
}
return iResult;
}
return -ENOMEM;
}
void AliHLTControlTask::SetBlocks(const AliHLTComponentBlockDataList& list)
{
// see header file for class documentation
fBlocks.assign(list.begin(), list.end());
AliHLTComponentBlockDataList::iterator element=fBlocks.begin();
for (;element!=fBlocks.end(); element++) fSize+=element->fSize;
// allocate buffer for the payload of all blocks
fpData=new AliHLTUInt8_t[fSize];
AliHLTUInt8_t offset=0;
// copy and redirect
for (element=fBlocks.begin();element!=fBlocks.end(); element++) {
memcpy(fpData+offset, element->fPtr, element->fSize);
element->fPtr=fpData+offset;
offset+=element->fSize;
}
}
void AliHLTControlTask::ResetBlocks()
{
// see header file for class documentation
fBlocks.clear();
if (fpData) delete [] fpData;
fpData=NULL;
fSize=0;
}
AliHLTControlTask::AliHLTControlEventComponent::AliHLTControlEventComponent(const AliHLTControlTask* pParent)
:
fpParent(pParent)
{
// see header file for class documentation
assert(pParent);
}
AliHLTControlTask::AliHLTControlEventComponent::~AliHLTControlEventComponent()
{
// see header file for class documentation
}
AliHLTComponentDataType AliHLTControlTask::AliHLTControlEventComponent::GetOutputDataType()
{
// see header file for class documentation
return kAliHLTMultipleDataType;
}
int AliHLTControlTask::AliHLTControlEventComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
{
// see header file for class documentation
tgtList.clear();
tgtList.push_back(kAliHLTDataTypeSOR);
tgtList.push_back(kAliHLTDataTypeEOR);
return tgtList.size();
}
void AliHLTControlTask::AliHLTControlEventComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// see header file for class documentation
if (fpParent && fpParent->fSize>0) constBase=fpParent->fSize;
else constBase=0;
inputMultiplier=0;
}
int AliHLTControlTask::AliHLTControlEventComponent::GetEvent(const AliHLTComponentEventData& /*evtData*/,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
vector<AliHLTComponentBlockData>& outputBlocks )
{
// see header file for class documentation
if (!fpParent) return -ENODEV;
const AliHLTControlTask* pParent=fpParent;
AliHLTUInt32_t capacity=size;
size=0;
if (capacity<pParent->fSize) {
return -ENOSPC;
}
// return if no event has been set
if (pParent->fpData==NULL ||
pParent->fBlocks.size()==0) {
//HLTInfo("no control event to send");
return 0;
}
for (unsigned int i=0; i<pParent->fBlocks.size(); i++) {
HLTDebug("publishing control block %s", DataType2Text(pParent->fBlocks[i].fDataType).c_str());
memcpy(outputPtr+size, pParent->fBlocks[i].fPtr, pParent->fBlocks[i].fSize);
AliHLTComponentBlockData bd;
FillBlockData(bd);
bd.fOffset=size;
bd.fSize=pParent->fBlocks[i].fSize;
bd.fDataType=pParent->fBlocks[i].fDataType;
bd.fSpecification=pParent->fBlocks[i].fSpecification;
outputBlocks.push_back( bd );
size+=bd.fSize;
}
return size;
}
|
disable component statistics for the control task, only inserts the desired control data blocks
|
disable component statistics for the control task, only inserts the desired control data blocks
|
C++
|
bsd-3-clause
|
ecalvovi/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,alisw/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,shahor02/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,miranov25/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,alisw/AliRoot,shahor02/AliRoot,alisw/AliRoot,coppedis/AliRoot,miranov25/AliRoot,coppedis/AliRoot,coppedis/AliRoot
|
a30ffb461726f7de1ebf4066a53ebbb498af350f
|
include/opengm/inference/auxiliary/lpdef.hxx
|
include/opengm/inference/auxiliary/lpdef.hxx
|
#ifndef OPENGM_LPDEF_HXX_
#define OPENGM_LPDEF_HXX_
namespace opengm {
class LPDef{
public:
enum LP_SOLVER {LP_SOLVER_AUTO, LP_SOLVER_PRIMAL_SIMPLEX, LP_SOLVER_DUAL_SIMPLEX, LP_SOLVER_NETWORK_SIMPLEX, LP_SOLVER_BARRIER, LP_SOLVER_SIFTING, LP_SOLVER_CONCURRENT};
enum LP_PRESOLVE{LP_PRESOLVE_AUTO, LP_PRESOLVE_OFF, LP_PRESOLVE_CONSERVATIVE, LP_PRESOLVE_AGGRESSIVE};
enum MIP_EMPHASIS{MIP_EMPHASIS_BALANCED, MIP_EMPHASIS_FEASIBILITY, MIP_EMPHASIS_OPTIMALITY, MIP_EMPHASIS_BESTBOUND, MIP_EMPHASIS_HIDDENFEAS};
enum MIP_CUT{MIP_CUT_DEFAULT, MIP_CUT_AUTO, MIP_CUT_OFF, MIP_CUT_ON, MIP_CUT_AGGRESSIVE, MIP_CUT_VERYAGGRESSIVE};
static const int default_numberOfThreads_; // number of threads (0=autoselect)
static const bool default_verbose_; // switch on/off verbose mode
static const double default_cutUp_; // upper cutoff
static const double default_epOpt_; // Optimality tolerance
static const double default_epMrk_; // Markowitz tolerance
static const double default_epRHS_; // Feasibility Tolerance
static const double default_epInt_; // amount by which an integer variable can differ from an integer
static const double default_epAGap_; // Absolute MIP gap tolerance
static const double default_epGap_; // Relative MIP gap tolerance
static const double default_workMem_; // maximal amount of memory in MB used for workspace
static const double default_treeMemoryLimit_; // maximal amount of memory in MB used for tree
static const double default_timeLimit_; // maximal time in seconds the solver has
static const int default_probingLevel_;
static const LP_SOLVER default_rootAlg_;
static const LP_SOLVER default_nodeAlg_;
static const MIP_EMPHASIS default_mipEmphasis_;
static const LP_PRESOLVE default_presolve_;
static const MIP_CUT default_cutLevel_; // Determines whether or not to cuts for the problem and how aggressively (will be overruled by specific ones).
static const MIP_CUT default_cliqueCutLevel_; // Determines whether or not to generate clique cuts for the problem and how aggressively.
static const MIP_CUT default_coverCutLevel_; // Determines whether or not to generate cover cuts for the problem and how aggressively.
static const MIP_CUT default_gubCutLevel_; // Determines whether or not to generate generalized upper bound (GUB) cuts for the problem and how aggressively.
static const MIP_CUT default_mirCutLevel_; // Determines whether or not mixed integer rounding (MIR) cuts should be generated for the problem and how aggressively.
static const MIP_CUT default_iboundCutLevel_; // Determines whether or not to generate implied bound cuts for the problem and how aggressively.
static const MIP_CUT default_flowcoverCutLevel_; // Determines whether or not to generate flow cover cuts for the problem and how aggressively.
static const MIP_CUT default_flowpathCutLevel_; // Determines whether or not to generate flow path cuts for the problem and how aggressively.
static const MIP_CUT default_disjunctCutLevel_; // Determines whether or not to generate disjunctive cuts for the problem and how aggressively.
static const MIP_CUT default_gomoryCutLevel_; // Determines whether or not to generate gomory fractional cuts for the problem and how aggressively.
};
const int LPDef::default_numberOfThreads_(0);
const bool LPDef::default_verbose_(false);
const double LPDef::default_cutUp_(1.0e+75);
const double LPDef::default_epOpt_(1e-5);
const double LPDef::default_epMrk_(0.01);
const double LPDef::default_epRHS_(1e-5);
const double LPDef::default_epInt_(1e-5);
const double LPDef::default_epAGap_(0.0);
const double LPDef::default_epGap_(0.0);
const double LPDef::default_workMem_(128.0);
const double LPDef::default_treeMemoryLimit_(1e+75);
const double LPDef::default_timeLimit_(1e+75);
const int LPDef::default_probingLevel_(0);
const LPDef::LP_SOLVER LPDef::default_rootAlg_(LP_SOLVER_AUTO);
const LPDef::LP_SOLVER LPDef::default_nodeAlg_(LP_SOLVER_AUTO);
const LPDef::MIP_EMPHASIS LPDef::default_mipEmphasis_(MIP_EMPHASIS_BALANCED);
const LPDef::LP_PRESOLVE LPDef::default_presolve_(LP_PRESOLVE_AUTO);
const LPDef::MIP_CUT LPDef::default_cutLevel_(MIP_CUT_AUTO);
const LPDef::MIP_CUT LPDef::default_cliqueCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_coverCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_gubCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_mirCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_iboundCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_flowcoverCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_flowpathCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_disjunctCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_gomoryCutLevel_(MIP_CUT_DEFAULT);
}
#endif
|
#ifndef OPENGM_LPDEF_HXX_
#define OPENGM_LPDEF_HXX_
namespace opengm {
class LPDef{
public:
enum LP_SOLVER {LP_SOLVER_AUTO, LP_SOLVER_PRIMAL_SIMPLEX, LP_SOLVER_DUAL_SIMPLEX, LP_SOLVER_NETWORK_SIMPLEX, LP_SOLVER_BARRIER, LP_SOLVER_SIFTING, LP_SOLVER_CONCURRENT};
enum LP_PRESOLVE{LP_PRESOLVE_AUTO, LP_PRESOLVE_OFF, LP_PRESOLVE_CONSERVATIVE, LP_PRESOLVE_AGGRESSIVE};
enum MIP_EMPHASIS{MIP_EMPHASIS_BALANCED, MIP_EMPHASIS_FEASIBILITY, MIP_EMPHASIS_OPTIMALITY, MIP_EMPHASIS_BESTBOUND, MIP_EMPHASIS_HIDDENFEAS};
enum MIP_CUT{MIP_CUT_DEFAULT, MIP_CUT_AUTO, MIP_CUT_OFF, MIP_CUT_ON, MIP_CUT_AGGRESSIVE, MIP_CUT_VERYAGGRESSIVE};
static const int default_numberOfThreads_; // number of threads (0=autoselect)
static const bool default_verbose_; // switch on/off verbose mode
static const double default_cutUp_; // upper cutoff
static const double default_epOpt_; // Optimality tolerance
static const double default_epMrk_; // Markowitz tolerance
static const double default_epRHS_; // Feasibility Tolerance
static const double default_epInt_; // amount by which an integer variable can differ from an integer
static const double default_epAGap_; // Absolute MIP gap tolerance
static const double default_epGap_; // Relative MIP gap tolerance
static const double default_workMem_; // maximal amount of memory in MB used for workspace
static const double default_treeMemoryLimit_; // maximal amount of memory in MB used for tree
static const double default_timeLimit_; // maximal time in seconds the solver has
static const int default_probingLevel_;
static const LP_SOLVER default_rootAlg_;
static const LP_SOLVER default_nodeAlg_;
static const MIP_EMPHASIS default_mipEmphasis_;
static const LP_PRESOLVE default_presolve_;
static const MIP_CUT default_cutLevel_; // Determines whether or not to cuts for the problem and how aggressively (will be overruled by specific ones).
static const MIP_CUT default_cliqueCutLevel_; // Determines whether or not to generate clique cuts for the problem and how aggressively.
static const MIP_CUT default_coverCutLevel_; // Determines whether or not to generate cover cuts for the problem and how aggressively.
static const MIP_CUT default_gubCutLevel_; // Determines whether or not to generate generalized upper bound (GUB) cuts for the problem and how aggressively.
static const MIP_CUT default_mirCutLevel_; // Determines whether or not mixed integer rounding (MIR) cuts should be generated for the problem and how aggressively.
static const MIP_CUT default_iboundCutLevel_; // Determines whether or not to generate implied bound cuts for the problem and how aggressively.
static const MIP_CUT default_flowcoverCutLevel_; // Determines whether or not to generate flow cover cuts for the problem and how aggressively.
static const MIP_CUT default_flowpathCutLevel_; // Determines whether or not to generate flow path cuts for the problem and how aggressively.
static const MIP_CUT default_disjunctCutLevel_; // Determines whether or not to generate disjunctive cuts for the problem and how aggressively.
static const MIP_CUT default_gomoryCutLevel_; // Determines whether or not to generate gomory fractional cuts for the problem and how aggressively.
};
#ifndef OPENGM_LPDEF_NO_SYMBOLS
const int LPDef::default_numberOfThreads_(0);
const bool LPDef::default_verbose_(false);
const double LPDef::default_cutUp_(1.0e+75);
const double LPDef::default_epOpt_(1e-5);
const double LPDef::default_epMrk_(0.01);
const double LPDef::default_epRHS_(1e-5);
const double LPDef::default_epInt_(1e-5);
const double LPDef::default_epAGap_(0.0);
const double LPDef::default_epGap_(0.0);
const double LPDef::default_workMem_(128.0);
const double LPDef::default_treeMemoryLimit_(1e+75);
const double LPDef::default_timeLimit_(1e+75);
const int LPDef::default_probingLevel_(0);
const LPDef::LP_SOLVER LPDef::default_rootAlg_(LP_SOLVER_AUTO);
const LPDef::LP_SOLVER LPDef::default_nodeAlg_(LP_SOLVER_AUTO);
const LPDef::MIP_EMPHASIS LPDef::default_mipEmphasis_(MIP_EMPHASIS_BALANCED);
const LPDef::LP_PRESOLVE LPDef::default_presolve_(LP_PRESOLVE_AUTO);
const LPDef::MIP_CUT LPDef::default_cutLevel_(MIP_CUT_AUTO);
const LPDef::MIP_CUT LPDef::default_cliqueCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_coverCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_gubCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_mirCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_iboundCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_flowcoverCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_flowpathCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_disjunctCutLevel_(MIP_CUT_DEFAULT);
const LPDef::MIP_CUT LPDef::default_gomoryCutLevel_(MIP_CUT_DEFAULT);
#endif
}
#endif
|
Introduce include guard around LPDef symbols to allow linking several modules which included lpdef.
|
Introduce include guard around LPDef symbols to allow linking several modules which included lpdef.
|
C++
|
mit
|
CVML/opengm,recarroll/opengm,recarroll/opengm,plstcharles/opengm,DerThorsten/opengm,DerThorsten/opengm,plstcharles/opengm,heartvalve/opengm,plstcharles/opengm,joergkappes/opengm,recarroll/opengm,joergkappes/opengm,CVML/opengm,CVML/opengm,DerThorsten/opengm,heartvalve/opengm,chaubold/opengm,opengm/opengm,CVML/opengm,joergkappes/opengm,joergkappes/opengm,chaubold/opengm,DerThorsten/opengm,chaubold/opengm,heartvalve/opengm,opengm/opengm,heartvalve/opengm,joergkappes/opengm,DerThorsten/opengm,chaubold/opengm,heartvalve/opengm,chaubold/opengm,plstcharles/opengm,opengm/opengm,CVML/opengm,opengm/opengm,opengm/opengm,plstcharles/opengm,recarroll/opengm,recarroll/opengm
|
cbedb544086e77abc367b900a244e4f29baa74dd
|
drivers/unix/file_access_unix.cpp
|
drivers/unix/file_access_unix.cpp
|
/*************************************************************************/
/* file_access_unix.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "file_access_unix.h"
#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)
#include "core/os/os.h"
#include "print_string.h"
#include <sys/stat.h>
#include <sys/types.h>
#if defined(UNIX_ENABLED)
#include <unistd.h>
#endif
#ifndef ANDROID_ENABLED
#include <sys/statvfs.h>
#endif
#ifdef MSVC
#define S_ISREG(m) ((m)&_S_IFREG)
#include <io.h>
#endif
#ifndef S_ISREG
#define S_ISREG(m) ((m)&S_IFREG)
#endif
void FileAccessUnix::check_errors() const {
ERR_FAIL_COND(!f);
if (feof(f)) {
last_error = ERR_FILE_EOF;
}
}
Error FileAccessUnix::_open(const String &p_path, int p_mode_flags) {
if (f)
fclose(f);
f = NULL;
path = fix_path(p_path);
//printf("opening %ls, %i\n", path.c_str(), Memory::get_static_mem_usage());
ERR_FAIL_COND_V(f, ERR_ALREADY_IN_USE);
const char *mode_string;
if (p_mode_flags == READ)
mode_string = "rb";
else if (p_mode_flags == WRITE)
mode_string = "wb";
else if (p_mode_flags == READ_WRITE)
mode_string = "rb+";
else if (p_mode_flags == WRITE_READ)
mode_string = "wb+";
else
return ERR_INVALID_PARAMETER;
/* pretty much every implementation that uses fopen as primary
backend (unix-compatible mostly) supports utf8 encoding */
//printf("opening %s as %s\n", p_path.utf8().get_data(), path.utf8().get_data());
struct stat st;
int err = stat(path.utf8().get_data(), &st);
if (!err) {
switch (st.st_mode & S_IFMT) {
case S_IFLNK:
case S_IFREG:
break;
default:
return ERR_FILE_CANT_OPEN;
}
}
if (is_backup_save_enabled() && (p_mode_flags & WRITE) && !(p_mode_flags & READ)) {
save_path = path;
path = path + ".tmp";
//print_line("saving instead to "+path);
}
f = fopen(path.utf8().get_data(), mode_string);
if (f == NULL) {
last_error = ERR_FILE_CANT_OPEN;
return ERR_FILE_CANT_OPEN;
} else {
last_error = OK;
flags = p_mode_flags;
return OK;
}
}
void FileAccessUnix::close() {
if (!f)
return;
fclose(f);
f = NULL;
if (close_notification_func) {
close_notification_func(path, flags);
}
if (save_path != "") {
//unlink(save_path.utf8().get_data());
//print_line("renaming..");
int rename_error = rename((save_path + ".tmp").utf8().get_data(), save_path.utf8().get_data());
if (rename_error && close_fail_notify) {
close_fail_notify(save_path);
}
save_path = "";
ERR_FAIL_COND(rename_error != 0);
}
}
bool FileAccessUnix::is_open() const {
return (f != NULL);
}
void FileAccessUnix::seek(size_t p_position) {
ERR_FAIL_COND(!f);
last_error = OK;
if (fseek(f, p_position, SEEK_SET))
check_errors();
}
void FileAccessUnix::seek_end(int64_t p_position) {
ERR_FAIL_COND(!f);
last_error = OK;
if (fseek(f, p_position, SEEK_END))
check_errors();
}
size_t FileAccessUnix::get_pos() const {
ERR_FAIL_COND_V(!f, 0);
last_error = OK;
int pos = ftell(f);
if (pos < 0) {
check_errors();
ERR_FAIL_V(0);
}
return pos;
}
size_t FileAccessUnix::get_len() const {
ERR_FAIL_COND_V(!f, 0);
int pos = ftell(f);
ERR_FAIL_COND_V(pos < 0, 0);
ERR_FAIL_COND_V(fseek(f, 0, SEEK_END), 0);
int size = ftell(f);
ERR_FAIL_COND_V(size < 0, 0);
ERR_FAIL_COND_V(fseek(f, pos, SEEK_SET), 0);
return size;
}
bool FileAccessUnix::eof_reached() const {
return last_error == ERR_FILE_EOF;
}
uint8_t FileAccessUnix::get_8() const {
ERR_FAIL_COND_V(!f, 0);
uint8_t b;
if (fread(&b, 1, 1, f) == 0) {
check_errors();
};
return b;
}
int FileAccessUnix::get_buffer(uint8_t *p_dst, int p_length) const {
ERR_FAIL_COND_V(!f, -1);
int read = fread(p_dst, 1, p_length, f);
check_errors();
return read;
};
Error FileAccessUnix::get_error() const {
return last_error;
}
void FileAccessUnix::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!f);
ERR_FAIL_COND(fwrite(&p_dest, 1, 1, f) != 1);
}
bool FileAccessUnix::file_exists(const String &p_path) {
int err;
struct stat st;
String filename = fix_path(p_path);
// Does the name exist at all?
err = stat(filename.utf8().get_data(), &st);
if (err)
return false;
#ifdef UNIX_ENABLED
// See if we have access to the file
if (access(filename.utf8().get_data(), F_OK))
return false;
#else
if (_access(filename.utf8().get_data(), 4) == -1)
return false;
#endif
// See if this is a regular file
switch (st.st_mode & S_IFMT) {
case S_IFLNK:
case S_IFREG:
return true;
default:
return false;
}
}
uint64_t FileAccessUnix::_get_modified_time(const String &p_file) {
String file = fix_path(p_file);
struct stat flags;
int err = stat(file.utf8().get_data(), &flags);
if (!err) {
return flags.st_mtime;
} else {
print_line("ERROR IN: " + p_file);
ERR_FAIL_V(0);
};
}
FileAccess *FileAccessUnix::create_libc() {
return memnew(FileAccessUnix);
}
CloseNotificationFunc FileAccessUnix::close_notification_func = NULL;
FileAccessUnix::FileAccessUnix() {
f = NULL;
flags = 0;
last_error = OK;
}
FileAccessUnix::~FileAccessUnix() {
close();
}
#endif
|
/*************************************************************************/
/* file_access_unix.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "file_access_unix.h"
#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)
#include "core/os/os.h"
#include "print_string.h"
#include <sys/stat.h>
#include <sys/types.h>
#if defined(UNIX_ENABLED)
#include <unistd.h>
#endif
#ifndef ANDROID_ENABLED
#include <sys/statvfs.h>
#endif
#ifdef MSVC
#define S_ISREG(m) ((m)&_S_IFREG)
#include <io.h>
#endif
#ifndef S_ISREG
#define S_ISREG(m) ((m)&S_IFREG)
#endif
void FileAccessUnix::check_errors() const {
ERR_FAIL_COND(!f);
if (feof(f)) {
last_error = ERR_FILE_EOF;
}
}
Error FileAccessUnix::_open(const String &p_path, int p_mode_flags) {
if (f)
fclose(f);
f = NULL;
path = fix_path(p_path);
//printf("opening %ls, %i\n", path.c_str(), Memory::get_static_mem_usage());
ERR_FAIL_COND_V(f, ERR_ALREADY_IN_USE);
const char *mode_string;
if (p_mode_flags == READ)
mode_string = "rb";
else if (p_mode_flags == WRITE)
mode_string = "wb";
else if (p_mode_flags == READ_WRITE)
mode_string = "rb+";
else if (p_mode_flags == WRITE_READ)
mode_string = "wb+";
else
return ERR_INVALID_PARAMETER;
/* pretty much every implementation that uses fopen as primary
backend (unix-compatible mostly) supports utf8 encoding */
//printf("opening %s as %s\n", p_path.utf8().get_data(), path.utf8().get_data());
struct stat st;
int err = stat(path.utf8().get_data(), &st);
if (!err) {
switch (st.st_mode & S_IFMT) {
case S_IFLNK:
case S_IFREG:
break;
default:
return ERR_FILE_CANT_OPEN;
}
}
if (is_backup_save_enabled() && (p_mode_flags & WRITE) && !(p_mode_flags & READ)) {
save_path = path;
path = path + ".tmp";
//print_line("saving instead to "+path);
}
f = fopen(path.utf8().get_data(), mode_string);
if (f == NULL) {
last_error = ERR_FILE_CANT_OPEN;
return ERR_FILE_CANT_OPEN;
} else {
last_error = OK;
flags = p_mode_flags;
return OK;
}
}
void FileAccessUnix::close() {
if (!f)
return;
fclose(f);
f = NULL;
if (close_notification_func) {
close_notification_func(path, flags);
}
if (save_path != "") {
//unlink(save_path.utf8().get_data());
//print_line("renaming..");
int rename_error = rename((save_path + ".tmp").utf8().get_data(), save_path.utf8().get_data());
if (rename_error && close_fail_notify) {
close_fail_notify(save_path);
}
save_path = "";
ERR_FAIL_COND(rename_error != 0);
}
}
bool FileAccessUnix::is_open() const {
return (f != NULL);
}
void FileAccessUnix::seek(size_t p_position) {
ERR_FAIL_COND(!f);
last_error = OK;
if (fseek(f, p_position, SEEK_SET))
check_errors();
}
void FileAccessUnix::seek_end(int64_t p_position) {
ERR_FAIL_COND(!f);
if (fseek(f, p_position, SEEK_END))
check_errors();
}
size_t FileAccessUnix::get_pos() const {
ERR_FAIL_COND_V(!f, 0);
int pos = ftell(f);
if (pos < 0) {
check_errors();
ERR_FAIL_V(0);
}
return pos;
}
size_t FileAccessUnix::get_len() const {
ERR_FAIL_COND_V(!f, 0);
int pos = ftell(f);
ERR_FAIL_COND_V(pos < 0, 0);
ERR_FAIL_COND_V(fseek(f, 0, SEEK_END), 0);
int size = ftell(f);
ERR_FAIL_COND_V(size < 0, 0);
ERR_FAIL_COND_V(fseek(f, pos, SEEK_SET), 0);
return size;
}
bool FileAccessUnix::eof_reached() const {
return last_error == ERR_FILE_EOF;
}
uint8_t FileAccessUnix::get_8() const {
ERR_FAIL_COND_V(!f, 0);
uint8_t b;
if (fread(&b, 1, 1, f) == 0) {
check_errors();
b = '\0';
}
return b;
}
int FileAccessUnix::get_buffer(uint8_t *p_dst, int p_length) const {
ERR_FAIL_COND_V(!f, -1);
int read = fread(p_dst, 1, p_length, f);
check_errors();
return read;
};
Error FileAccessUnix::get_error() const {
return last_error;
}
void FileAccessUnix::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!f);
ERR_FAIL_COND(fwrite(&p_dest, 1, 1, f) != 1);
}
bool FileAccessUnix::file_exists(const String &p_path) {
int err;
struct stat st;
String filename = fix_path(p_path);
// Does the name exist at all?
err = stat(filename.utf8().get_data(), &st);
if (err)
return false;
#ifdef UNIX_ENABLED
// See if we have access to the file
if (access(filename.utf8().get_data(), F_OK))
return false;
#else
if (_access(filename.utf8().get_data(), 4) == -1)
return false;
#endif
// See if this is a regular file
switch (st.st_mode & S_IFMT) {
case S_IFLNK:
case S_IFREG:
return true;
default:
return false;
}
}
uint64_t FileAccessUnix::_get_modified_time(const String &p_file) {
String file = fix_path(p_file);
struct stat flags;
int err = stat(file.utf8().get_data(), &flags);
if (!err) {
return flags.st_mtime;
} else {
print_line("ERROR IN: " + p_file);
ERR_FAIL_V(0);
};
}
FileAccess *FileAccessUnix::create_libc() {
return memnew(FileAccessUnix);
}
CloseNotificationFunc FileAccessUnix::close_notification_func = NULL;
FileAccessUnix::FileAccessUnix() {
f = NULL;
flags = 0;
last_error = OK;
}
FileAccessUnix::~FileAccessUnix() {
close();
}
#endif
|
Fix EOF in wav file importer
|
Fix EOF in wav file importer
In #10973 I reset the state of the stream in get_pos() assuming that the
ftell failing would cause proper error checking. This is not how this
class was designed, however. This commit fixes the get_8() method to
not return unitialized data on eof, and removes the wrong error resets
added in #10973.
This fixes #11022
|
C++
|
mit
|
BastiaanOlij/godot,honix/godot,ZuBsPaCe/godot,Valentactive/godot,n-pigeon/godot,RandomShaper/godot,firefly2442/godot,firefly2442/godot,Zylann/godot,josempans/godot,Paulloz/godot,Shockblast/godot,okamstudio/godot,BastiaanOlij/godot,Faless/godot,sanikoyes/godot,Zylann/godot,ageazrael/godot,sanikoyes/godot,vkbsb/godot,godotengine/godot,godotengine/godot,ex/godot,okamstudio/godot,ex/godot,Zylann/godot,akien-mga/godot,FateAce/godot,RandomShaper/godot,DmitriySalnikov/godot,Faless/godot,zicklag/godot,groud/godot,pkowal1982/godot,Paulloz/godot,ex/godot,guilhermefelipecgs/godot,josempans/godot,Faless/godot,Shockblast/godot,vnen/godot,godotengine/godot,Paulloz/godot,sanikoyes/godot,honix/godot,Shockblast/godot,mcanders/godot,pkowal1982/godot,NateWardawg/godot,okamstudio/godot,josempans/godot,Paulloz/godot,NateWardawg/godot,pkowal1982/godot,pkowal1982/godot,Brickcaster/godot,n-pigeon/godot,Valentactive/godot,okamstudio/godot,FateAce/godot,n-pigeon/godot,Paulloz/godot,akien-mga/godot,DmitriySalnikov/godot,jejung/godot,BastiaanOlij/godot,jejung/godot,RandomShaper/godot,NateWardawg/godot,ZuBsPaCe/godot,Valentactive/godot,josempans/godot,okamstudio/godot,Brickcaster/godot,NateWardawg/godot,firefly2442/godot,vnen/godot,jejung/godot,Shockblast/godot,ZuBsPaCe/godot,honix/godot,ageazrael/godot,vnen/godot,akien-mga/godot,MarianoGnu/godot,zicklag/godot,pkowal1982/godot,groud/godot,MarianoGnu/godot,mcanders/godot,guilhermefelipecgs/godot,vnen/godot,zicklag/godot,josempans/godot,Faless/godot,ex/godot,mcanders/godot,RandomShaper/godot,pkowal1982/godot,sanikoyes/godot,guilhermefelipecgs/godot,Valentactive/godot,Valentactive/godot,RandomShaper/godot,zicklag/godot,Brickcaster/godot,MarianoGnu/godot,NateWardawg/godot,josempans/godot,jejung/godot,pkowal1982/godot,ZuBsPaCe/godot,FateAce/godot,Shockblast/godot,Faless/godot,ex/godot,Shockblast/godot,Zylann/godot,godotengine/godot,godotengine/godot,firefly2442/godot,akien-mga/godot,MarianoGnu/godot,vkbsb/godot,RandomShaper/godot,vnen/godot,NateWardawg/godot,groud/godot,NateWardawg/godot,FateAce/godot,Brickcaster/godot,DmitriySalnikov/godot,FateAce/godot,mcanders/godot,Brickcaster/godot,zicklag/godot,sanikoyes/godot,ageazrael/godot,godotengine/godot,jejung/godot,DmitriySalnikov/godot,n-pigeon/godot,Paulloz/godot,okamstudio/godot,guilhermefelipecgs/godot,RandomShaper/godot,Brickcaster/godot,BastiaanOlij/godot,n-pigeon/godot,guilhermefelipecgs/godot,ex/godot,MarianoGnu/godot,Faless/godot,pkowal1982/godot,MarianoGnu/godot,ageazrael/godot,ageazrael/godot,Valentactive/godot,firefly2442/godot,Paulloz/godot,okamstudio/godot,okamstudio/godot,firefly2442/godot,guilhermefelipecgs/godot,vnen/godot,josempans/godot,Faless/godot,okamstudio/godot,ZuBsPaCe/godot,Valentactive/godot,akien-mga/godot,vnen/godot,n-pigeon/godot,honix/godot,DmitriySalnikov/godot,honix/godot,Zylann/godot,FateAce/godot,godotengine/godot,groud/godot,vkbsb/godot,BastiaanOlij/godot,vnen/godot,vkbsb/godot,akien-mga/godot,honix/godot,firefly2442/godot,mcanders/godot,sanikoyes/godot,ageazrael/godot,Faless/godot,n-pigeon/godot,guilhermefelipecgs/godot,Zylann/godot,ZuBsPaCe/godot,guilhermefelipecgs/godot,Zylann/godot,NateWardawg/godot,Shockblast/godot,jejung/godot,mcanders/godot,ex/godot,akien-mga/godot,godotengine/godot,Brickcaster/godot,ex/godot,MarianoGnu/godot,zicklag/godot,groud/godot,BastiaanOlij/godot,ZuBsPaCe/godot,okamstudio/godot,vkbsb/godot,vkbsb/godot,josempans/godot,MarianoGnu/godot,ageazrael/godot,groud/godot,ZuBsPaCe/godot,akien-mga/godot,BastiaanOlij/godot,DmitriySalnikov/godot,Valentactive/godot,vkbsb/godot,sanikoyes/godot,BastiaanOlij/godot,sanikoyes/godot,Shockblast/godot,vkbsb/godot,Zylann/godot,NateWardawg/godot,DmitriySalnikov/godot,firefly2442/godot
|
0a035e7e721cbe94883dcd0028900b87b18f3381
|
source/SCORING/COMPONENTS/rotationalEntropy.C
|
source/SCORING/COMPONENTS/rotationalEntropy.C
|
/* rotationalEntropy.C
*
* Copyright (C) 2011 Marcel Schumann
*
* This program 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.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
// ----------------------------------------------------
// $Maintainer: Marcel Schumann $
// $Authors: Marcel Schumann $
// ----------------------------------------------------
#include <BALL/SCORING/COMPONENTS/rotationalEntropy.h>
#include <BALL/SCORING/COMMON/scoringFunction.h>
using namespace BALL;
RotationalEntropy::RotationalEntropy(ScoringFunction& sf)
: ScoringComponent(sf)
{
ligand_intra_molecular_ = 0;
gridable_ = 0;
atom_pairwise_ = 0;
setName("(nRot>14)");
type_name_ = "nRot";
}
void RotationalEntropy::setLigandIntraMolecular(bool b)
{
if (b == true)
{
cout<<"RotationalEntropy ScoringComponent can not be used to compute ligand conformation score !"<<endl;
}
}
void RotationalEntropy::update(const vector<std::pair<Atom*, Atom*> >& /*pair_vector*/)
{
// nothing needs to be done here
}
double RotationalEntropy::updateScore()
{
score_ = scoring_function_->getRotatableLigandBonds()->size();
if (score_ == 0 && scoring_function_->getStaticLigandFragments()->size() == 0)
{
throw BALL::Exception::GeneralException(__FILE__, __LINE__, "RotationalEntropy::updateScore() error", "Rotatable bonds have not been searched yet; you therefore need to set Option 'use_static_lig_fragments' to true !");
}
// prevent score-decrease for small ligands,
// since we only want to increase the score ( = add penalty) for ligands with very many rotatable bonds
if (score_ < 14)
{
score_ = 0;
return 0;
}
/*
scaleScore();
return score_;
*/
return getScaledScore();
}
|
/* rotationalEntropy.C
*
* Copyright (C) 2011 Marcel Schumann
*
* This program 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.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
// ----------------------------------------------------
// $Maintainer: Marcel Schumann $
// $Authors: Marcel Schumann $
// ----------------------------------------------------
#include <BALL/SCORING/COMPONENTS/rotationalEntropy.h>
#include <BALL/SCORING/COMMON/scoringFunction.h>
using namespace BALL;
RotationalEntropy::RotationalEntropy(ScoringFunction& sf)
: ScoringComponent(sf)
{
ligand_intra_molecular_ = 0;
gridable_ = 0;
atom_pairwise_ = 0;
setName("(nRot>14)");
type_name_ = "nRot";
}
void RotationalEntropy::setLigandIntraMolecular(bool b)
{
if (b == true)
{
std::cout<<"RotationalEntropy ScoringComponent can not be used to compute ligand conformation score !"<<std::endl;
}
}
void RotationalEntropy::update(const std::vector<std::pair<Atom*, Atom*> >& /*pair_vector*/)
{
// nothing needs to be done here
}
double RotationalEntropy::updateScore()
{
score_ = scoring_function_->getRotatableLigandBonds()->size();
if (score_ == 0 && scoring_function_->getStaticLigandFragments()->size() == 0)
{
throw BALL::Exception::GeneralException(__FILE__, __LINE__, "RotationalEntropy::updateScore() error", "Rotatable bonds have not been searched yet; you therefore need to set Option 'use_static_lig_fragments' to true !");
}
// prevent score-decrease for small ligands,
// since we only want to increase the score ( = add penalty) for ligands with very many rotatable bonds
if (score_ < 14)
{
score_ = 0;
return 0;
}
/*
scaleScore();
return score_;
*/
return getScaledScore();
}
|
Add required namespaces to rotationalEntropy.C
|
Add required namespaces to rotationalEntropy.C
|
C++
|
lgpl-2.1
|
tkemmer/ball,tkemmer/ball,tkemmer/ball,tkemmer/ball,tkemmer/ball,tkemmer/ball
|
ac681ae36eb3608183bf68fe0ed974c40ed36854
|
Project/Dev_class11_handout/Motor2D/P_Zelda.cpp
|
Project/Dev_class11_handout/Motor2D/P_Zelda.cpp
|
#include "P_Zelda.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1FileSystem.h"
#include "j1Player.h"
#include "Character.h"
#include "j1InputManager.h"
#define JUMP_DISTANCE 112
void P_Zelda::Attack(float dt)
{
switch (character_direction) {
case up:
CreateArrow({ pos.x + 4,pos.y - 16,8,16 });
break;
case down:
CreateArrow({ pos.x + 4,pos.y + 16,8,16 });
break;
case left:
CreateArrow({ pos.x - 16,pos.y + 4,16,8 });
break;
case right:
CreateArrow({ pos.x + 16,pos.y + 4,16,8 });
break;
}
actual_event = idle;
doing_script = false;
}
void P_Zelda::CreateArrow(SDL_Rect rect)
{
Arrow* temp_arrow = new Arrow();
temp_arrow->collider = App->collision->AddCollider(rect, collider_arrow, App->player->Zelda, App->player);
temp_arrow->collider->rect = rect;
temp_arrow->pos.x = rect.x;
temp_arrow->pos.y = rect.y;
temp_arrow->direction = character_direction;
temp_arrow->timer = SDL_GetTicks();
Vec_Arrow->push_back(temp_arrow);
}
void P_Zelda::UpdateArrows()
{
int arrow_speed = 10;
for (int i = 0; i < Vec_Arrow->size(); i++) {
switch (Vec_Arrow[0][i]->direction) {
case up:
Vec_Arrow[0][i]->pos.y -= arrow_speed;
break;
case down:
Vec_Arrow[0][i]->pos.y += arrow_speed;
break;
case left:
Vec_Arrow[0][i]->pos.x -= arrow_speed;
break;
case right:
Vec_Arrow[0][i]->pos.x += arrow_speed;
break;
}
Vec_Arrow[0][i]->collider->SetPos(Vec_Arrow[0][i]->pos.x, Vec_Arrow[0][i]->pos.y, App->player->Zelda->GetLogicHeightPlayer());
if (SDL_GetTicks() - Vec_Arrow[0][i]->timer > 1000) {
Vec_Arrow[0][i]->collider->to_delete = true;
Vec_Arrow->erase(Vec_Arrow->begin() + i);
i--;
}
}
}
void P_Zelda::ThrowFunction(float dt, int &pos, bool add, bool is_horitzontal)
{
static int final_pos = 0;
int temp_pos = pos;
static bool can_pass_wall = true;
static bool zelda_collides = false;
bool is_on_collision = false;
int count = 1;
if (GetLogicHeightPlayer() == 2) {
count = 1;
}
int i = 1;
if (!add)
i = -1;
bool stop_jumping = false;
iPoint temp_point = tilepos;
iPoint next_point = tilepos;
static int before_wall_pos = 0;
if (!temp) {
zelda_collides = false;
final_pos = pos + (i * JUMP_DISTANCE);
before_wall_pos = final_pos;
while ((i * temp_pos < i*final_pos)) {
next_point.x = temp_point.x + is_horitzontal * i;
next_point.y = temp_point.y + !is_horitzontal * i;
if (GetLogic(count, temp_point) == TILE_COL_ID && !is_on_collision) {
is_on_collision = true;
before_wall_pos = temp_pos;
if (GetLogic(count, next_point) == TILE_COL_ID)
break;
if (!can_pass_wall) {
before_wall_pos = temp_pos + i * 64;
}
can_pass_wall = !can_pass_wall;
count = false;
if (GetLogicHeightPlayer() == 2)
count = 2;
zelda_collides = true;
}
else if (GetLogic(count, temp_point) != TILE_COL_ID) {
is_on_collision = false;
}
temp_pos = temp_pos + (i * 4);
temp_point.x = (temp_pos / 16) * is_horitzontal + temp_point.x * !is_horitzontal;
temp_point.y = (temp_pos / 16) * !is_horitzontal + temp_point.y * is_horitzontal;
}
int decrease = 1;
if (!can_pass_wall || !zelda_collides) {
can_pass_wall = true;
ChangeLogicHeightPlayer(GetLogicHeightPlayer() - decrease);
}
else {
if (GetLogicHeightPlayer() == 2 && zelda_collides) {
decrease = 2;
ChangeLogicHeightPlayer(GetLogicHeightPlayer() - decrease);
}
}
}
temp = true;
if ((i * pos < i*before_wall_pos)) {
pos = pos + (i * 4);
}
// if player reached the final pos, player height decreases 1
else {
temp = false;
doing_script = false;
}
}
player_event P_Zelda::GetEvent()
{
SDL_Scancode UP;
SDL_Scancode DOWN;
SDL_Scancode LEFT;
SDL_Scancode RIGHT;
//Change the actual event, direction and move_direction depending ont he key pressed
if (App->player->cooperative == false) {
UP = SDL_SCANCODE_W;
DOWN = SDL_SCANCODE_S;
LEFT = SDL_SCANCODE_A;
RIGHT = SDL_SCANCODE_D;
}
else {
UP = SDL_SCANCODE_UP;
DOWN = SDL_SCANCODE_DOWN;
LEFT = SDL_SCANCODE_LEFT;
RIGHT = SDL_SCANCODE_RIGHT;
}
if (doing_script == false) {
static direction aim_direction = down;
//FIRST THINGS FIRST
if (App->input->GetKey(SDL_SCANCODE_T) == KEY_DOWN) {
aim_direction = character_direction;
}
if (App->inputM->EventPressed(INPUTEVENT::MUP, 0) == EVENTSTATE::E_REPEAT) {
if (App->inputM->EventPressed(INPUTEVENT::MRIGHT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_up_right;
}
else if (App->inputM->EventPressed(INPUTEVENT::MLEFT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_up_left;
}
else {
movement_direction = move_up;
}
character_direction = up;
actual_event = move;
}
else if (App->inputM->EventPressed(INPUTEVENT::MDOWN, 0) == EVENTSTATE::E_REPEAT) {
if (App->inputM->EventPressed(INPUTEVENT::MLEFT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_down_left;
}
else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_down_right;
}
else {
movement_direction = move_down;
}
character_direction = down;
actual_event = move;
}
else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_right;
character_direction = right;
actual_event = move;
}
else if (App->inputM->EventPressed(INPUTEVENT::MLEFT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_left;
character_direction = left;
actual_event = move;
}
if (is_picked) {
static bool can_throw = false;
actual_event = pick;
ChangeLogicHeightPlayer(App->player->Link->GetLogicHeightPlayer() + 1);
pos = App->player->Link->pos;
if (((App->inputM->EventPressed(INPUTEVENT::PICK, 1) == EVENTSTATE::E_DOWN) && can_throw) || ((App->inputM->EventPressed(INPUTEVENT::PICK, 0) == EVENTSTATE::E_DOWN) && can_throw)) {
actual_event = throw_;
doing_script = true;
is_picked = false;
App->player->Link->im_lifting = false;
can_throw = false;
}
else can_throw = true;
}
if (App->inputM->EventPressed(INPUTEVENT::JUMP, 0) == EVENTSTATE::E_DOWN && !is_picked) {
actual_event = roll;
doing_script = true;
}
else if (App->input->GetKey(UP) == KEY_REPEAT) {
if (App->input->GetKey(LEFT) == KEY_REPEAT) {
movement_direction = move_up_left;
}
else if (App->input->GetKey(RIGHT) == KEY_REPEAT) {
movement_direction = move_up_right;
}
else {
movement_direction = move_up;
}
character_direction = up;
actual_event = move;
}
else if (App->input->GetKey(DOWN) == KEY_REPEAT) {
if (App->input->GetKey(LEFT) == KEY_REPEAT) {
movement_direction = move_down_left;
}
else if (App->input->GetKey(RIGHT) == KEY_REPEAT) {
movement_direction = move_down_right;
}
else {
movement_direction = move_down;
}
character_direction = down;
actual_event = move;
}
else if (App->input->GetKey(RIGHT) == KEY_REPEAT) {
movement_direction = move_right;
character_direction = right;
actual_event = move;
}
else if (App->input->GetKey(LEFT) == KEY_REPEAT) {
movement_direction = move_left;
character_direction = left;
actual_event = move;
}
else {
movement_direction = move_idle;
actual_event = idle;
}
if (can_jump) {
actual_event = jump;
doing_script = true;
LOG("I'm Jumping :DDDD");
can_jump = false;
}
if (is_picked) {
static bool can_throw = false;
actual_event = pick;
ChangeLogicHeightPlayer(App->player->Link->GetLogicHeightPlayer() + 1);
pos = App->player->Link->pos;
if (((App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN) && can_throw)|| ((App->inputM->EventPressed(INPUTEVENT::PICK, 0) == EVENTSTATE::E_DOWN) && can_throw)) {
actual_event = throw_;
doing_script = true;
is_picked = false;
App->player->Link->im_lifting = false;
can_throw = false;
}
else can_throw = true;
}
if (App->input->GetKey(SDL_SCANCODE_C) == KEY_DOWN && !is_picked) {
actual_event = roll;
doing_script = true;
}
if (App->input->GetKey(SDL_SCANCODE_T) == KEY_REPEAT) {
character_direction = aim_direction;
}
if (App->input->GetKey(SDL_SCANCODE_T) == KEY_UP ) {
actual_event = attack;
doing_script = true;
character_direction = aim_direction;
}
return actual_event;
}
}
|
#include "P_Zelda.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1FileSystem.h"
#include "j1Player.h"
#include "Character.h"
#include "j1InputManager.h"
#define JUMP_DISTANCE 96
void P_Zelda::Attack(float dt)
{
switch (character_direction) {
case up:
CreateArrow({ pos.x + 4,pos.y - 16,8,16 });
break;
case down:
CreateArrow({ pos.x + 4,pos.y + 16,8,16 });
break;
case left:
CreateArrow({ pos.x - 16,pos.y + 4,16,8 });
break;
case right:
CreateArrow({ pos.x + 16,pos.y + 4,16,8 });
break;
}
actual_event = idle;
doing_script = false;
}
void P_Zelda::CreateArrow(SDL_Rect rect)
{
Arrow* temp_arrow = new Arrow();
temp_arrow->collider = App->collision->AddCollider(rect, collider_arrow, App->player->Zelda, App->player);
temp_arrow->collider->rect = rect;
temp_arrow->pos.x = rect.x;
temp_arrow->pos.y = rect.y;
temp_arrow->direction = character_direction;
temp_arrow->timer = SDL_GetTicks();
Vec_Arrow->push_back(temp_arrow);
}
void P_Zelda::UpdateArrows()
{
int arrow_speed = 10;
for (int i = 0; i < Vec_Arrow->size(); i++) {
switch (Vec_Arrow[0][i]->direction) {
case up:
Vec_Arrow[0][i]->pos.y -= arrow_speed;
break;
case down:
Vec_Arrow[0][i]->pos.y += arrow_speed;
break;
case left:
Vec_Arrow[0][i]->pos.x -= arrow_speed;
break;
case right:
Vec_Arrow[0][i]->pos.x += arrow_speed;
break;
}
Vec_Arrow[0][i]->collider->SetPos(Vec_Arrow[0][i]->pos.x, Vec_Arrow[0][i]->pos.y, App->player->Zelda->GetLogicHeightPlayer());
if (SDL_GetTicks() - Vec_Arrow[0][i]->timer > 1000) {
Vec_Arrow[0][i]->collider->to_delete = true;
Vec_Arrow->erase(Vec_Arrow->begin() + i);
i--;
}
}
}
void P_Zelda::ThrowFunction(float dt, int &pos, bool add, bool is_horitzontal)
{
static int final_pos = 0;
int temp_pos = pos;
static bool can_pass_wall = true;
static bool zelda_collides = false;
int decrease = 1;
bool is_on_collision = false;
int count = 1;
if (GetLogicHeightPlayer() == 2) {
count = 1;
}
int n = 1;
if (!add)
n = -1;
bool stop_jumping = false;
iPoint temp_point = tilepos;
iPoint next_point = tilepos;
static int before_wall_pos = 0;
if (!temp) {
zelda_collides = false;
final_pos = pos + (n * JUMP_DISTANCE);
before_wall_pos = final_pos;
while ((n * temp_pos < n*final_pos)) {
next_point.x = temp_point.x + is_horitzontal * n;
next_point.y = temp_point.y + !is_horitzontal * n;
int i = 0;
if (!is_on_collision) {
for (i = 0; i <= GetLogicHeightPlayer(); i++) {
if (GetLogic(i, temp_point) == TILE_COL_ID) {
is_on_collision = true;
before_wall_pos = temp_pos;
if (GetLogic(count, next_point) == TILE_COL_ID)
break;
if (!can_pass_wall) {
before_wall_pos = temp_pos + n * 64;
}
can_pass_wall = !can_pass_wall;
zelda_collides = true;
decrease = i;
break;
}
}
}
if (GetLogic(decrease, temp_point) != TILE_COL_ID) {
is_on_collision = false;
}
temp_pos = temp_pos + (n * 4);
temp_point.x = (temp_pos / 16) * is_horitzontal + temp_point.x * !is_horitzontal;
temp_point.y = (temp_pos / 16) * !is_horitzontal + temp_point.y * is_horitzontal;
}
//int decrease = 1;
if (!can_pass_wall || !zelda_collides) {
can_pass_wall = true;
ChangeLogicHeightPlayer(GetLogicHeightPlayer() - decrease);
}
else {
if (GetLogicHeightPlayer() == 2 && zelda_collides) {
//decrease = 2;
ChangeLogicHeightPlayer(GetLogicHeightPlayer() - decrease);
}
}
}
temp = true;
if ((n * pos < n*before_wall_pos)) {
pos = pos + (n * 4);
}
// if player reached the final pos, player height decreases 1
else {
temp = false;
doing_script = false;
}
}
player_event P_Zelda::GetEvent()
{
SDL_Scancode UP;
SDL_Scancode DOWN;
SDL_Scancode LEFT;
SDL_Scancode RIGHT;
//Change the actual event, direction and move_direction depending ont he key pressed
if (App->player->cooperative == false) {
UP = SDL_SCANCODE_W;
DOWN = SDL_SCANCODE_S;
LEFT = SDL_SCANCODE_A;
RIGHT = SDL_SCANCODE_D;
}
else {
UP = SDL_SCANCODE_UP;
DOWN = SDL_SCANCODE_DOWN;
LEFT = SDL_SCANCODE_LEFT;
RIGHT = SDL_SCANCODE_RIGHT;
}
if (doing_script == false) {
static direction aim_direction = down;
//FIRST THINGS FIRST
if (App->input->GetKey(SDL_SCANCODE_T) == KEY_DOWN) {
aim_direction = character_direction;
}
if (App->inputM->EventPressed(INPUTEVENT::MUP, 0) == EVENTSTATE::E_REPEAT) {
if (App->inputM->EventPressed(INPUTEVENT::MRIGHT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_up_right;
}
else if (App->inputM->EventPressed(INPUTEVENT::MLEFT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_up_left;
}
else {
movement_direction = move_up;
}
character_direction = up;
actual_event = move;
}
else if (App->inputM->EventPressed(INPUTEVENT::MDOWN, 0) == EVENTSTATE::E_REPEAT) {
if (App->inputM->EventPressed(INPUTEVENT::MLEFT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_down_left;
}
else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_down_right;
}
else {
movement_direction = move_down;
}
character_direction = down;
actual_event = move;
}
else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_right;
character_direction = right;
actual_event = move;
}
else if (App->inputM->EventPressed(INPUTEVENT::MLEFT, 0) == EVENTSTATE::E_REPEAT) {
movement_direction = move_left;
character_direction = left;
actual_event = move;
}
if (is_picked) {
static bool can_throw = false;
actual_event = pick;
ChangeLogicHeightPlayer(App->player->Link->GetLogicHeightPlayer() + 1);
pos = App->player->Link->pos;
if (((App->inputM->EventPressed(INPUTEVENT::PICK, 1) == EVENTSTATE::E_DOWN) && can_throw) || ((App->inputM->EventPressed(INPUTEVENT::PICK, 0) == EVENTSTATE::E_DOWN) && can_throw)) {
actual_event = throw_;
doing_script = true;
is_picked = false;
App->player->Link->im_lifting = false;
can_throw = false;
}
else can_throw = true;
}
if (App->inputM->EventPressed(INPUTEVENT::JUMP, 0) == EVENTSTATE::E_DOWN && !is_picked) {
actual_event = roll;
doing_script = true;
}
else if (App->input->GetKey(UP) == KEY_REPEAT) {
if (App->input->GetKey(LEFT) == KEY_REPEAT) {
movement_direction = move_up_left;
}
else if (App->input->GetKey(RIGHT) == KEY_REPEAT) {
movement_direction = move_up_right;
}
else {
movement_direction = move_up;
}
character_direction = up;
actual_event = move;
}
else if (App->input->GetKey(DOWN) == KEY_REPEAT) {
if (App->input->GetKey(LEFT) == KEY_REPEAT) {
movement_direction = move_down_left;
}
else if (App->input->GetKey(RIGHT) == KEY_REPEAT) {
movement_direction = move_down_right;
}
else {
movement_direction = move_down;
}
character_direction = down;
actual_event = move;
}
else if (App->input->GetKey(RIGHT) == KEY_REPEAT) {
movement_direction = move_right;
character_direction = right;
actual_event = move;
}
else if (App->input->GetKey(LEFT) == KEY_REPEAT) {
movement_direction = move_left;
character_direction = left;
actual_event = move;
}
else {
movement_direction = move_idle;
actual_event = idle;
}
if (can_jump) {
actual_event = jump;
doing_script = true;
LOG("I'm Jumping :DDDD");
can_jump = false;
}
if (is_picked) {
static bool can_throw = false;
actual_event = pick;
ChangeLogicHeightPlayer(App->player->Link->GetLogicHeightPlayer() + 1);
pos = App->player->Link->pos;
if (((App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN) && can_throw)|| ((App->inputM->EventPressed(INPUTEVENT::PICK, 0) == EVENTSTATE::E_DOWN) && can_throw)) {
actual_event = throw_;
doing_script = true;
is_picked = false;
App->player->Link->im_lifting = false;
can_throw = false;
}
else can_throw = true;
}
if (App->input->GetKey(SDL_SCANCODE_C) == KEY_DOWN && !is_picked) {
actual_event = roll;
doing_script = true;
}
if (App->input->GetKey(SDL_SCANCODE_T) == KEY_REPEAT) {
character_direction = aim_direction;
}
if (App->input->GetKey(SDL_SCANCODE_T) == KEY_UP ) {
actual_event = attack;
doing_script = true;
character_direction = aim_direction;
}
return actual_event;
}
}
|
Throw Improved
|
Throw Improved
|
C++
|
apache-2.0
|
Guille1406/The-Legend-of-Zelda-Hyrule-Conquest,Guille1406/The-Legend-of-Zelda-Hyrule-Conquest,Guille1406/The-Legend-of-Zelda-Hyrule-Conquest,Guille1406/The-Legend-of-Zelda-Hyrule-Conquest
|
e4a9db6f450bffcb14a2c20a617ad4a9169fbee9
|
part/plugins/exporter/exporterpluginview.cpp
|
part/plugins/exporter/exporterpluginview.cpp
|
/**
* This file is part of the KDE libraries
* Copyright (C) 2009 Milian Wolff <[email protected]>
* Copyright (C) 2002 John Firebaugh <[email protected]>
* Copyright (C) 2001 Christoph Cullmann <[email protected]>
* Copyright (C) 2001 Joseph Wenninger <[email protected]>
* Copyright (C) 1999 Jochen Wilhelmy <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License version 2 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "exporterpluginview.h"
#include "exporterplugin.h"
#include "abstractexporter.h"
#include "htmlexporter.h"
#include <ktexteditor/document.h>
#include <ktexteditor/view.h>
#include <ktexteditor/highlightinterface.h>
#include <kactioncollection.h>
#include <kaction.h>
#include <kfiledialog.h>
#include <ktemporaryfile.h>
#include <ksavefile.h>
#include <kio/netaccess.h>
#include <QtCore/QMimeData>
#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtCore/QTextCodec>
#include <kdebug.h>
ExporterPluginView::ExporterPluginView(KTextEditor::View* view)
: QObject(view), KXMLGUIClient(view), m_view(view)
{
setComponentData( ExporterPluginFactory::componentData() );
setXMLFile("ktexteditor_exporterui.rc");
m_copyAction = actionCollection()->addAction("edit_copy_html", this, SLOT(exportToClipboard()));
m_copyAction->setIcon(KIcon("edit-copy"));
m_copyAction->setText(i18n("Copy as &HTML"));
m_copyAction->setWhatsThis(i18n("Use this command to copy the currently selected text as HTML to the system clipboard."));
m_copyAction->setEnabled(m_view->selection());
m_fileExportAction = actionCollection()->addAction("file_export_html", this, SLOT(exportToFile()));
m_fileExportAction->setText(i18n("E&xport as HTML..."));
m_fileExportAction->setWhatsThis(i18n("This command allows you to export the current document"
" with all highlighting information into a HTML document."));
connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)),
this, SLOT(updateSelectionAction(KTextEditor::View*)));
}
ExporterPluginView::~ExporterPluginView()
{
}
void ExporterPluginView::updateSelectionAction(KTextEditor::View* view)
{
Q_ASSERT(view == m_view); Q_UNUSED(view)
m_copyAction->setEnabled(m_view->selection());
}
void ExporterPluginView::exportToClipboard()
{
if (!m_view->selection()) {
return;
}
QMimeData *data = new QMimeData();
QString s;
QTextStream output( &s, QIODevice::WriteOnly );
exportData(true, output);
data->setHtml(s);
data->setText(s);
QApplication::clipboard()->setMimeData(data);
}
void ExporterPluginView::exportToFile()
{
KUrl url = KFileDialog::getSaveUrl(m_view->document()->documentName(), "text/html",
m_view, i18n("Export File as HTML"));
if ( url.isEmpty() ) {
return;
}
QString filename;
if ( url.isLocalFile() ) {
filename = url.toLocalFile();
} else {
///TODO: cleanup! don't let the temp files lay around
KTemporaryFile tmp; // ### only used for network export
tmp.setAutoRemove(false);
tmp.open();
filename = tmp.fileName();
}
KSaveFile savefile(filename);
if (savefile.open()) {
QTextStream outputStream ( &savefile );
exportData(false, outputStream);
savefile.finalize(); //check error?
}
// else
// {/*ERROR*/}
if ( !url.isLocalFile() ) {
KIO::NetAccess::upload( filename, url, 0 );
}
}
void ExporterPluginView::exportData(const bool useSelection, QTextStream &output)
{
const KTextEditor::Range range = useSelection ? m_view->selectionRange() : m_view->document()->documentRange();
const bool blockwise = useSelection ? m_view->blockSelection() : false;
if ( (blockwise || range.onSingleLine()) && (range.start().column() > range.end().column() ) ) {
return;
}
//outputStream.setEncoding(QTextStream::UnicodeUTF8);
output.setCodec(QTextCodec::codecForName("UTF-8"));
///TODO: add more exporters
AbstractExporter* exporter;
exporter = new HTMLExporter(m_view, output, !useSelection);
KTextEditor::HighlightInterface* hiface = qobject_cast<KTextEditor::HighlightInterface*>(m_view->document());
const KTextEditor::Attribute::Ptr noAttrib(0);
for (int i = range.start().line(); (i <= range.end().line()) && (i < m_view->document()->lines()); ++i)
{
const QString &line = m_view->document()->line(i);
QList<KTextEditor::HighlightInterface::AttributeBlock> attribs;
if ( hiface ) {
attribs = hiface->lineAttributes(i);
}
int lineStart = 0;
int remainingChars = line.length();
if ( blockwise || range.onSingleLine() ) {
lineStart = range.start().column();
remainingChars = range.columnWidth();
} else if ( i == range.start().line() ) {
lineStart = range.start().column();
} else if ( i == range.end().line() ) {
remainingChars = range.end().column();
}
int handledUntil = lineStart;
foreach ( const KTextEditor::HighlightInterface::AttributeBlock& block, attribs ) {
// honor (block-) selections
if ( block.start + block.length <= lineStart ) {
continue;
} else if ( block.start >= lineStart + remainingChars ) {
break;
}
int start = qMax(block.start, lineStart);
if ( start > handledUntil ) {
exporter->exportText( line.mid( handledUntil, start - handledUntil ), noAttrib );
}
int length = qMin(block.length, remainingChars);
exporter->exportText( line.mid( start, length ), block.attribute);
handledUntil = start + length;
}
if ( handledUntil < lineStart + remainingChars ) {
exporter->exportText( line.mid( handledUntil, remainingChars ), noAttrib );
}
exporter->closeLine(i == range.end().line());
}
delete exporter;
output.flush();
}
#include "exporterpluginview.moc"
// kate: space-indent on; indent-width 2; replace-tabs on;
|
/**
* This file is part of the KDE libraries
* Copyright (C) 2009 Milian Wolff <[email protected]>
* Copyright (C) 2002 John Firebaugh <[email protected]>
* Copyright (C) 2001 Christoph Cullmann <[email protected]>
* Copyright (C) 2001 Joseph Wenninger <[email protected]>
* Copyright (C) 1999 Jochen Wilhelmy <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License version 2 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "exporterpluginview.h"
#include "exporterplugin.h"
#include "abstractexporter.h"
#include "htmlexporter.h"
#include <ktexteditor/document.h>
#include <ktexteditor/view.h>
#include <ktexteditor/highlightinterface.h>
#include <kactioncollection.h>
#include <kaction.h>
#include <kfiledialog.h>
#include <ktemporaryfile.h>
#include <ksavefile.h>
#include <kio/netaccess.h>
#include <QtCore/QMimeData>
#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtCore/QTextCodec>
#include <kdebug.h>
ExporterPluginView::ExporterPluginView(KTextEditor::View* view)
: QObject(view), KXMLGUIClient(view), m_view(view)
{
setComponentData( ExporterPluginFactory::componentData() );
setXMLFile("ktexteditor_exporterui.rc");
m_copyAction = actionCollection()->addAction("edit_copy_html", this, SLOT(exportToClipboard()));
m_copyAction->setIcon(KIcon("edit-copy"));
m_copyAction->setText(i18n("Copy as &HTML"));
m_copyAction->setWhatsThis(i18n("Use this command to copy the currently selected text as HTML to the system clipboard."));
m_copyAction->setEnabled(m_view->selection());
m_fileExportAction = actionCollection()->addAction("file_export_html", this, SLOT(exportToFile()));
m_fileExportAction->setText(i18n("E&xport as HTML..."));
m_fileExportAction->setWhatsThis(i18n("This command allows you to export the current document"
" with all highlighting information into a HTML document."));
connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)),
this, SLOT(updateSelectionAction(KTextEditor::View*)));
}
ExporterPluginView::~ExporterPluginView()
{
}
void ExporterPluginView::updateSelectionAction(KTextEditor::View* view)
{
Q_ASSERT(view == m_view); Q_UNUSED(view)
m_copyAction->setEnabled(m_view->selection());
}
void ExporterPluginView::exportToClipboard()
{
if (!m_view->selection()) {
return;
}
QMimeData *data = new QMimeData();
QString s;
QTextStream output( &s, QIODevice::WriteOnly );
exportData(true, output);
data->setHtml(s);
data->setText(s);
QApplication::clipboard()->setMimeData(data);
}
void ExporterPluginView::exportToFile()
{
KUrl url = KFileDialog::getSaveUrl(m_view->document()->documentName(), "text/html",
m_view, i18n("Export File as HTML"));
if ( url.isEmpty() ) {
return;
}
QString filename;
if ( url.isLocalFile() ) {
filename = url.toLocalFile();
} else {
///TODO: cleanup! don't let the temp files lay around
KTemporaryFile tmp; // ### only used for network export
tmp.setAutoRemove(false);
tmp.open();
filename = tmp.fileName();
}
KSaveFile savefile(filename);
if (savefile.open()) {
QTextStream outputStream ( &savefile );
exportData(false, outputStream);
savefile.finalize(); //check error?
}
// else
// {/*ERROR*/}
if ( !url.isLocalFile() ) {
KIO::NetAccess::upload( filename, url, 0 );
}
}
void ExporterPluginView::exportData(const bool useSelection, QTextStream &output)
{
const KTextEditor::Range range = useSelection ? m_view->selectionRange() : m_view->document()->documentRange();
const bool blockwise = useSelection ? m_view->blockSelection() : false;
if ( (blockwise || range.onSingleLine()) && (range.start().column() > range.end().column() ) ) {
return;
}
//outputStream.setEncoding(QTextStream::UnicodeUTF8);
output.setCodec(QTextCodec::codecForName("UTF-8"));
///TODO: add more exporters
QScopedPointer<AbstractExporter> exporter;
exporter.reset(new HTMLExporter(m_view, output, !useSelection));
KTextEditor::HighlightInterface* hiface = qobject_cast<KTextEditor::HighlightInterface*>(m_view->document());
const KTextEditor::Attribute::Ptr noAttrib(0);
for (int i = range.start().line(); (i <= range.end().line()) && (i < m_view->document()->lines()); ++i)
{
const QString &line = m_view->document()->line(i);
QList<KTextEditor::HighlightInterface::AttributeBlock> attribs;
if ( hiface ) {
attribs = hiface->lineAttributes(i);
}
int lineStart = 0;
int remainingChars = line.length();
if ( blockwise || range.onSingleLine() ) {
lineStart = range.start().column();
remainingChars = range.columnWidth();
} else if ( i == range.start().line() ) {
lineStart = range.start().column();
} else if ( i == range.end().line() ) {
remainingChars = range.end().column();
}
int handledUntil = lineStart;
foreach ( const KTextEditor::HighlightInterface::AttributeBlock& block, attribs ) {
// honor (block-) selections
if ( block.start + block.length <= lineStart ) {
continue;
} else if ( block.start >= lineStart + remainingChars ) {
break;
}
int start = qMax(block.start, lineStart);
if ( start > handledUntil ) {
exporter->exportText( line.mid( handledUntil, start - handledUntil ), noAttrib );
}
int length = qMin(block.length, remainingChars);
exporter->exportText( line.mid( start, length ), block.attribute);
handledUntil = start + length;
}
if ( handledUntil < lineStart + remainingChars ) {
exporter->exportText( line.mid( handledUntil, remainingChars ), noAttrib );
}
exporter->closeLine(i == range.end().line());
}
output.flush();
}
#include "exporterpluginview.moc"
// kate: space-indent on; indent-width 2; replace-tabs on;
|
refactor to use scoped pointer instead of manual deletion
|
refactor to use scoped pointer instead of manual deletion
|
C++
|
lgpl-2.1
|
DickJ/kate,hlamer/kate,jfmcarreira/kate,cmacq2/kate,hlamer/kate,sandsmark/kate,hlamer/kate,hlamer/kate,DickJ/kate,hlamer/kate,cmacq2/kate,hlamer/kate,cmacq2/kate,hlamer/kate,hlamer/kate,hlamer/kate,DickJ/kate,sandsmark/kate,sandsmark/kate,hlamer/kate,jfmcarreira/kate,DickJ/kate,sandsmark/kate,jfmcarreira/kate
|
10649a1ed91573c7a7337c9d9e416d0f88e009c5
|
src/cpp/core/r_util/RSessionContext.cpp
|
src/cpp/core/r_util/RSessionContext.cpp
|
/*
* RSessionContext.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RSessionContext.hpp>
#include <iostream>
#include <boost/format.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/FilePath.hpp>
#include <core/Settings.hpp>
#include <core/FileSerializer.hpp>
#include <core/http/Util.hpp>
#include <core/http/URL.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#define kSessionSuffix "-session"
namespace rstudio {
namespace core {
namespace r_util {
SessionScope SessionScope::fromProjectPath(
const std::string& projPath,
const std::string& id,
const FilePathToProjectId& filePathToProjectId)
{
std::string project = filePathToProjectId(projPath);
return SessionScope(project, id);
}
std::string SessionScope::projectPathForScope(
const SessionScope& scope,
const ProjectIdToFilePath& projectIdToFilePath)
{
return projectIdToFilePath(scope.project());
}
SessionScope SessionScope::fromProjectId(const std::string& project,
const std::string& id)
{
return SessionScope(project, id);
}
SessionScope SessionScope::projectNone()
{
return SessionScope("c005c133-62fc-48e9-b486-451c0fc7847a", "0");
}
std::string urlPathForSessionScope(const SessionScope& scope)
{
// get a URL compatible project path
std::string project = http::util::urlEncode(scope.project());
boost::algorithm::replace_all(project, "%2F", "/");
// create url
boost::format fmt("/s/%1%/~%2%/");
return boost::str(fmt % project % scope.id());
}
void parseSessionUrl(const std::string& url,
SessionScope* pScope,
std::string* pUrlPrefix,
std::string* pUrlWithoutPrefix)
{
static boost::regex re("/s/(.+?)/~(\\d+)/");
boost::smatch match;
if (boost::regex_search(url, match, re))
{
if (pScope)
{
std::string project = http::util::urlDecode(match[1]);
std::string id = match[2];
*pScope = r_util::SessionScope::fromProjectId(project, id);
}
if (pUrlPrefix)
{
*pUrlPrefix = match[0];
}
if (pUrlWithoutPrefix)
{
*pUrlWithoutPrefix = boost::algorithm::replace_first_copy(
url, std::string(match[0]), "/");
}
}
else
{
if (pScope)
*pScope = SessionScope();
if (pUrlPrefix)
*pUrlPrefix = std::string();
if (pUrlWithoutPrefix)
*pUrlWithoutPrefix = url;
}
}
std::string createSessionUrl(const std::string& hostPageUrl,
const SessionScope& scope)
{
// get url without prefix
std::string url;
parseSessionUrl(hostPageUrl, NULL, NULL, &url);
// build path for project
std::string path = urlPathForSessionScope(scope);
// complete the url and return it
return http::URL::complete(url, path);
}
std::ostream& operator<< (std::ostream& os, const SessionContext& context)
{
os << context.username;
if (!context.scope.project().empty())
os << " -- " << context.scope.project();
if (!context.scope.id().empty())
os << " [" << context.scope.id() << "]";
return os;
}
std::string sessionScopeFile(std::string prefix,
const SessionScope& scope)
{
// resolve project path
std::string project = scope.project();
if (!project.empty())
{
// pluralize the prefix so there is no conflict when switching
// between the single file and directory based schemas
prefix += "s";
if (!boost::algorithm::starts_with(project, "/"))
project = "/" + project;
if (!scope.id().empty())
{
if (!boost::algorithm::ends_with(project, "/"))
project = project + "/";
}
}
// return file path
return prefix + project + scope.id();
}
std::string sessionContextFile(const SessionContext& context)
{
return sessionScopeFile(context.username + kSessionSuffix, context.scope);
}
} // namespace r_util
} // namespace core
} // namespace rstudio
|
/*
* RSessionContext.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/RSessionContext.hpp>
#include <iostream>
#include <boost/format.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/FilePath.hpp>
#include <core/Settings.hpp>
#include <core/FileSerializer.hpp>
#include <core/http/Util.hpp>
#include <core/http/URL.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#define kSessionSuffix "-session"
namespace rstudio {
namespace core {
namespace r_util {
SessionScope SessionScope::fromProjectPath(
const std::string& projPath,
const std::string& id,
const FilePathToProjectId& filePathToProjectId)
{
std::string project = filePathToProjectId(projPath);
return SessionScope(project, id);
}
std::string SessionScope::projectPathForScope(
const SessionScope& scope,
const ProjectIdToFilePath& projectIdToFilePath)
{
return projectIdToFilePath(scope.project());
}
SessionScope SessionScope::fromProjectId(const std::string& project,
const std::string& id)
{
return SessionScope(project, id);
}
SessionScope SessionScope::projectNone()
{
return SessionScope("c005c133-62fc-48e9-b486-451c0fc7847a", "1");
}
std::string urlPathForSessionScope(const SessionScope& scope)
{
// get a URL compatible project path
std::string project = http::util::urlEncode(scope.project());
boost::algorithm::replace_all(project, "%2F", "/");
// create url
boost::format fmt("/s/%1%/~%2%/");
return boost::str(fmt % project % scope.id());
}
void parseSessionUrl(const std::string& url,
SessionScope* pScope,
std::string* pUrlPrefix,
std::string* pUrlWithoutPrefix)
{
static boost::regex re("/s/(.+?)/~(\\d+)/");
boost::smatch match;
if (boost::regex_search(url, match, re))
{
if (pScope)
{
std::string project = http::util::urlDecode(match[1]);
std::string id = match[2];
*pScope = r_util::SessionScope::fromProjectId(project, id);
}
if (pUrlPrefix)
{
*pUrlPrefix = match[0];
}
if (pUrlWithoutPrefix)
{
*pUrlWithoutPrefix = boost::algorithm::replace_first_copy(
url, std::string(match[0]), "/");
}
}
else
{
if (pScope)
*pScope = SessionScope();
if (pUrlPrefix)
*pUrlPrefix = std::string();
if (pUrlWithoutPrefix)
*pUrlWithoutPrefix = url;
}
}
std::string createSessionUrl(const std::string& hostPageUrl,
const SessionScope& scope)
{
// get url without prefix
std::string url;
parseSessionUrl(hostPageUrl, NULL, NULL, &url);
// build path for project
std::string path = urlPathForSessionScope(scope);
// complete the url and return it
return http::URL::complete(url, path);
}
std::ostream& operator<< (std::ostream& os, const SessionContext& context)
{
os << context.username;
if (!context.scope.project().empty())
os << " -- " << context.scope.project();
if (!context.scope.id().empty())
os << " [" << context.scope.id() << "]";
return os;
}
std::string sessionScopeFile(std::string prefix,
const SessionScope& scope)
{
// resolve project path
std::string project = scope.project();
if (!project.empty())
{
// pluralize the prefix so there is no conflict when switching
// between the single file and directory based schemas
prefix += "s";
if (!boost::algorithm::starts_with(project, "/"))
project = "/" + project;
if (!scope.id().empty())
{
if (!boost::algorithm::ends_with(project, "/"))
project = project + "/";
}
}
// return file path
return prefix + project + scope.id();
}
std::string sessionContextFile(const SessionContext& context)
{
return sessionScopeFile(context.username + kSessionSuffix, context.scope);
}
} // namespace r_util
} // namespace core
} // namespace rstudio
|
tweak none scope
|
tweak none scope
|
C++
|
agpl-3.0
|
suribes/rstudio,piersharding/rstudio,suribes/rstudio,githubfun/rstudio,piersharding/rstudio,thklaus/rstudio,jar1karp/rstudio,suribes/rstudio,john-r-mcpherson/rstudio,john-r-mcpherson/rstudio,jar1karp/rstudio,githubfun/rstudio,githubfun/rstudio,more1/rstudio,more1/rstudio,tbarrongh/rstudio,jar1karp/rstudio,brsimioni/rstudio,jrnold/rstudio,vbelakov/rstudio,thklaus/rstudio,jrnold/rstudio,jzhu8803/rstudio,more1/rstudio,JanMarvin/rstudio,brsimioni/rstudio,brsimioni/rstudio,thklaus/rstudio,githubfun/rstudio,john-r-mcpherson/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,edrogers/rstudio,vbelakov/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,pssguy/rstudio,jrnold/rstudio,brsimioni/rstudio,more1/rstudio,thklaus/rstudio,sfloresm/rstudio,jrnold/rstudio,JanMarvin/rstudio,edrogers/rstudio,vbelakov/rstudio,thklaus/rstudio,more1/rstudio,brsimioni/rstudio,sfloresm/rstudio,pssguy/rstudio,jar1karp/rstudio,JanMarvin/rstudio,jar1karp/rstudio,vbelakov/rstudio,githubfun/rstudio,piersharding/rstudio,pssguy/rstudio,piersharding/rstudio,suribes/rstudio,jar1karp/rstudio,jzhu8803/rstudio,piersharding/rstudio,pssguy/rstudio,tbarrongh/rstudio,sfloresm/rstudio,jzhu8803/rstudio,thklaus/rstudio,more1/rstudio,tbarrongh/rstudio,edrogers/rstudio,JanMarvin/rstudio,thklaus/rstudio,pssguy/rstudio,more1/rstudio,piersharding/rstudio,pssguy/rstudio,edrogers/rstudio,jar1karp/rstudio,pssguy/rstudio,vbelakov/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,edrogers/rstudio,piersharding/rstudio,jzhu8803/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,vbelakov/rstudio,suribes/rstudio,edrogers/rstudio,JanMarvin/rstudio,piersharding/rstudio,jzhu8803/rstudio,jrnold/rstudio,more1/rstudio,suribes/rstudio,tbarrongh/rstudio,jrnold/rstudio,brsimioni/rstudio,tbarrongh/rstudio,vbelakov/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,githubfun/rstudio,jzhu8803/rstudio,sfloresm/rstudio,brsimioni/rstudio,sfloresm/rstudio,vbelakov/rstudio,jar1karp/rstudio,sfloresm/rstudio,githubfun/rstudio,edrogers/rstudio,piersharding/rstudio,JanMarvin/rstudio,jzhu8803/rstudio,suribes/rstudio,tbarrongh/rstudio,githubfun/rstudio,sfloresm/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,brsimioni/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,pssguy/rstudio,thklaus/rstudio,jzhu8803/rstudio,jrnold/rstudio,jrnold/rstudio
|
1430f510fc738e2356a60abac0a39701ebb12e6e
|
kdgantt/kdganttsummaryhandlingproxymodel.cpp
|
kdgantt/kdganttsummaryhandlingproxymodel.cpp
|
/****************************************************************************
** Copyright (C) 2001-2006 Klarälvdalens Datakonsult AB. All rights reserved.
**
** This file is part of the KD Gantt library.
**
** This file may be used under the terms of the GNU General Public
** License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Alternatively you may (at
** your option) use any later version of the GNU General Public
** License if such license has been publicly approved by
** Klarälvdalens Datakonsult AB (or its successors, if any).
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Klarälvdalens Datakonsult AB reserves all rights
** not expressly granted herein.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "kdganttsummaryhandlingproxymodel.h"
#include "kdganttsummaryhandlingproxymodel_p.h"
#include <QDebug>
#include <cassert>
using namespace KDGantt;
/*!\class KDGantt::SummaryHandlingProxyModel
* \brief Proxy model that supports summary gantt items.
*
* This proxy model provides the functionality of summary items.
* A summary item is an item with type KDGantt::TypeSummary and
* zero or more children in the model that it summarizes.
* GraphicsView itself does not dictate any policy for summary items,
* instead the logic for making the summary items start and end points
* span it's children is provided by this proxy.
*
* The start and end times of a summary is the min/max of the
* start/end times of it's children.
*
* \see GraphicsView::setModel
*/
typedef ForwardingProxyModel BASE;
bool SummaryHandlingProxyModel::Private::cacheLookup( const QModelIndex& idx,
QPair<QDateTime,QDateTime>* result ) const
{
//qDebug() << "cacheLookup("<<idx<<"), cache has " << cached_summary_items.count() << "items";
QHash<QModelIndex,QPair<QDateTime,QDateTime> >::const_iterator it =
cached_summary_items.find( idx );
if ( it != cached_summary_items.constEnd() ) {
*result = *it;
return true;
} else {
return false;
}
}
void SummaryHandlingProxyModel::Private::insertInCache( const SummaryHandlingProxyModel* model,
const QModelIndex& sourceIdx ) const
{
QAbstractItemModel* sourceModel = model->sourceModel();
const QModelIndex& mainIdx = sourceIdx;
QDateTime st;
QDateTime et;
for ( int r = 0; r < sourceModel->rowCount( mainIdx ); ++r ) {
QModelIndex pdIdx = model->mapFromSource( sourceModel->index( r, 0, mainIdx ) );
/* The probably results in recursive calls here */
QVariant tmpsv = model->data( pdIdx, StartTimeRole );
QVariant tmpev = model->data( pdIdx, EndTimeRole );
if( !qVariantCanConvert<QDateTime>(tmpsv) ||
!qVariantCanConvert<QDateTime>(tmpev) ) {
qDebug() << "Skipping item " << sourceIdx << " because it doesn't contain QDateTime";
continue;
}
// We need to test for empty strings to
// avoid a stupid Qt warning
if( tmpsv.type() == QVariant::String && qVariantValue<QString>(tmpsv).isEmpty()) continue;
if( tmpev.type() == QVariant::String && qVariantValue<QString>(tmpev).isEmpty()) continue;
QDateTime tmpst = tmpsv.toDateTime();
QDateTime tmpet = tmpev.toDateTime();
if ( st.isNull() || st > tmpst ) st = tmpst;
if ( et.isNull() || et < tmpet ) et = tmpet;
}
QVariant tmpssv = sourceModel->data( mainIdx, StartTimeRole );
QVariant tmpsev = sourceModel->data( mainIdx, EndTimeRole );
if ( qVariantCanConvert<QDateTime>( tmpssv )
&& !( qVariantCanConvert<QString>( tmpssv ) && qVariantValue<QString>( tmpssv ).isEmpty() )
&& qVariantValue<QDateTime>( tmpssv ) != st )
sourceModel->setData( mainIdx, st, StartTimeRole );
if ( qVariantCanConvert<QDateTime>( tmpsev )
&& !( qVariantCanConvert<QString>( tmpsev ) && qVariantValue<QString>( tmpsev ).isEmpty() )
&& qVariantValue<QDateTime>( tmpsev ) != et )
sourceModel->setData( mainIdx, et, EndTimeRole );
cached_summary_items[sourceIdx]=qMakePair( st, et );
}
void SummaryHandlingProxyModel::Private::removeFromCache( const QModelIndex& idx ) const
{
cached_summary_items.remove( idx );
}
void SummaryHandlingProxyModel::Private::clearCache() const
{
cached_summary_items.clear();
}
/*! Constructor. Creates a new SummaryHandlingProxyModel with
* parent \a parent
*/
SummaryHandlingProxyModel::SummaryHandlingProxyModel( QObject* parent )
: BASE( parent ), _d( new Private )
{
init();
}
#define d d_func()
SummaryHandlingProxyModel::~SummaryHandlingProxyModel()
{
}
void SummaryHandlingProxyModel::init()
{
}
namespace {
// Think this is ugly? Well, it's not from me, it comes from QProxyModel
struct KDPrivateModelIndex {
int r, c;
void *p;
const QAbstractItemModel *m;
};
}
/*! Sets the model to be used as the source model for this proxy.
* The proxy does not take ownership of the model.
* \see QAbstractProxyModel::setSourceModel
*/
void SummaryHandlingProxyModel::setSourceModel( QAbstractItemModel* model )
{
BASE::setSourceModel( model );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceModelReset()
{
d->clearCache();
BASE::sourceModelReset();
}
void SummaryHandlingProxyModel::sourceLayoutChanged()
{
d->clearCache();
BASE::sourceLayoutChanged();
}
void SummaryHandlingProxyModel::sourceDataChanged( const QModelIndex& from, const QModelIndex& to )
{
QAbstractItemModel* model = sourceModel();
QModelIndex parentIdx = from;
do {
const QModelIndex& dataIdx = parentIdx;
if ( model->data( dataIdx, ItemTypeRole )==TypeSummary ) {
//qDebug() << "removing " << parentIdx << "from cache";
d->removeFromCache( dataIdx );
QModelIndex proxyDataIdx = mapFromSource( dataIdx );
emit dataChanged( proxyDataIdx, proxyDataIdx );
}
} while ( ( parentIdx=model->parent( parentIdx ) ) != QModelIndex() );
BASE::sourceDataChanged( from, to );
}
void SummaryHandlingProxyModel::sourceColumnsAboutToBeInserted( const QModelIndex& parentIdx,
int start,
int end )
{
BASE::sourceColumnsAboutToBeInserted( parentIdx, start, end );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceColumnsAboutToBeRemoved( const QModelIndex& parentIdx,
int start,
int end )
{
BASE::sourceColumnsAboutToBeRemoved( parentIdx, start, end );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceRowsAboutToBeInserted( const QModelIndex & parentIdx, int start, int end )
{
BASE::sourceRowsAboutToBeInserted( parentIdx, start, end );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceRowsAboutToBeRemoved( const QModelIndex & parentIdx, int start, int end )
{
BASE::sourceRowsAboutToBeRemoved( parentIdx, start, end );
d->clearCache();
}
/*! \see QAbstractItemModel::flags */
Qt::ItemFlags SummaryHandlingProxyModel::flags( const QModelIndex& idx ) const
{
const QModelIndex sidx = mapToSource( idx );
const QAbstractItemModel* model = sourceModel();
Qt::ItemFlags f = model->flags( sidx );
if ( d->isSummary(sidx) ) {
f &= !Qt::ItemIsEditable;
}
return f;
}
/*! \see QAbstractItemModel::data */
QVariant SummaryHandlingProxyModel::data( const QModelIndex& proxyIndex, int role) const
{
//qDebug() << "SummaryHandlingProxyModel::data("<<proxyIndex<<role<<")";
const QModelIndex sidx = mapToSource( proxyIndex );
const QAbstractItemModel* model = sourceModel();
if ( d->isSummary(sidx) && ( role==StartTimeRole || role==EndTimeRole )) {
//qDebug() << "requested summary";
QPair<QDateTime,QDateTime> result;
if ( d->cacheLookup( sidx, &result ) ) {
//qDebug() << "SummaryHandlingProxyModel::data(): Looking up summary for " << proxyIndex << role;
switch( role ) {
case StartTimeRole: return result.first;
case EndTimeRole: return result.second;
default: /* fall thru */;
}
} else {
d->insertInCache( this, sidx );
return data( proxyIndex, role ); /* TODO: Optimise */
}
}
return model->data( sidx, role );
}
/*! \see QAbstractItemModel::setData */
bool SummaryHandlingProxyModel::setData( const QModelIndex& index, const QVariant& value, int role )
{
QAbstractItemModel* model = sourceModel();
if ( role==StartTimeRole || role==EndTimeRole ) {
QModelIndex parentIdx = mapToSource( index );
do {
if ( d->isSummary(parentIdx) ) {
//qDebug() << "removing " << parentIdx << "from cache";
d->removeFromCache( parentIdx );
QModelIndex proxyParentIdx = mapFromSource( parentIdx );
emit dataChanged( proxyParentIdx, proxyParentIdx );
}
} while ( ( parentIdx=model->parent( parentIdx ) ) != QModelIndex() );
}
return BASE::setData( index, value, role );
}
#undef d
#ifndef KDAB_NO_UNIT_TESTS
#include "unittest/test.h"
#include <QStandardItemModel>
namespace {
std::ostream& operator<<( std::ostream& os, const QDateTime& dt )
{
os << dt.toString().toStdString();
return os;
}
}
KDAB_SCOPED_UNITTEST_SIMPLE( KDGantt, SummaryHandlingProxyModel, "test" ) {
SummaryHandlingProxyModel model;
QStandardItemModel sourceModel;
model.setSourceModel( &sourceModel );
QStandardItem* topitem = new QStandardItem( QString::fromLatin1( "Summary" ) );
topitem->setData( KDGantt::TypeSummary, KDGantt::ItemTypeRole );
sourceModel.appendRow( topitem );
QStandardItem* task1 = new QStandardItem( QString::fromLatin1( "Task1" ) );
task1->setData( KDGantt::TypeTask, KDGantt::ItemTypeRole );
QStandardItem* task2 = new QStandardItem( QString::fromLatin1( "Task2" ) );
task2->setData( KDGantt::TypeTask, KDGantt::ItemTypeRole );
topitem->appendRow( task1 );
topitem->appendRow( task2 );
QDateTime startdt = QDateTime::currentDateTime();
QDateTime enddt = startdt.addDays( 1 );
task1->setData( startdt, KDGantt::StartTimeRole );
task1->setData( enddt, KDGantt::EndTimeRole );
task2->setData( startdt, KDGantt::StartTimeRole );
task2->setData( enddt, KDGantt::EndTimeRole );
const QModelIndex topidx = model.index( 0, 0, QModelIndex() );
assertEqual( model.data( topidx, KDGantt::ItemTypeRole ).toInt(), KDGantt::TypeSummary );
assertEqual( model.data( model.index( 0, 0, topidx ), KDGantt::ItemTypeRole ).toInt(), KDGantt::TypeTask );
QDateTime task1startdt = model.data( model.index( 0, 0, topidx ), KDGantt::StartTimeRole ).toDateTime();
assertEqual( task1startdt, startdt );
QDateTime summarystartdt = model.data( topidx, KDGantt::StartTimeRole ).toDateTime();
assertEqual( summarystartdt, startdt );
assertTrue( model.flags( model.index( 0, 0, topidx ) ) & Qt::ItemIsEditable );
assertFalse( model.flags( topidx ) & Qt::ItemIsEditable );
}
#endif /* KDAB_NO_UNIT_TESTS */
#include "moc_kdganttsummaryhandlingproxymodel.cpp"
|
/****************************************************************************
** Copyright (C) 2001-2006 Klarälvdalens Datakonsult AB. All rights reserved.
**
** This file is part of the KD Gantt library.
**
** This file may be used under the terms of the GNU General Public
** License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Alternatively you may (at
** your option) use any later version of the GNU General Public
** License if such license has been publicly approved by
** Klarälvdalens Datakonsult AB (or its successors, if any).
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Klarälvdalens Datakonsult AB reserves all rights
** not expressly granted herein.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
**********************************************************************/
#include "kdganttsummaryhandlingproxymodel.h"
#include "kdganttsummaryhandlingproxymodel_p.h"
#include <QDebug>
#include <cassert>
using namespace KDGantt;
/*!\class KDGantt::SummaryHandlingProxyModel
* \brief Proxy model that supports summary gantt items.
*
* This proxy model provides the functionality of summary items.
* A summary item is an item with type KDGantt::TypeSummary and
* zero or more children in the model that it summarizes.
* GraphicsView itself does not dictate any policy for summary items,
* instead the logic for making the summary items start and end points
* span it's children is provided by this proxy.
*
* The start and end times of a summary is the min/max of the
* start/end times of it's children.
*
* \see GraphicsView::setModel
*/
typedef ForwardingProxyModel BASE;
bool SummaryHandlingProxyModel::Private::cacheLookup( const QModelIndex& idx,
QPair<QDateTime,QDateTime>* result ) const
{
//qDebug() << "cacheLookup("<<idx<<"), cache has " << cached_summary_items.count() << "items";
QHash<QModelIndex,QPair<QDateTime,QDateTime> >::const_iterator it =
cached_summary_items.find( idx );
if ( it != cached_summary_items.constEnd() ) {
*result = *it;
return true;
} else {
return false;
}
}
void SummaryHandlingProxyModel::Private::insertInCache( const SummaryHandlingProxyModel* model,
const QModelIndex& sourceIdx ) const
{
QAbstractItemModel* sourceModel = model->sourceModel();
const QModelIndex& mainIdx = sourceIdx;
QDateTime st;
QDateTime et;
for ( int r = 0; r < sourceModel->rowCount( mainIdx ); ++r ) {
QModelIndex pdIdx = model->mapFromSource( sourceModel->index( r, 0, mainIdx ) );
/* The probably results in recursive calls here */
QVariant tmpsv = model->data( pdIdx, StartTimeRole );
QVariant tmpev = model->data( pdIdx, EndTimeRole );
if( !qVariantCanConvert<QDateTime>(tmpsv) ||
!qVariantCanConvert<QDateTime>(tmpev) ) {
qDebug() << "Skipping item " << sourceIdx << " because it doesn't contain QDateTime";
continue;
}
// check for valid datetimes
if( tmpsv.type() == QVariant::DateTime && !qVariantValue<QDateTime>(tmpsv).isValid()) continue;
if( tmpev.type() == QVariant::DateTime && !qVariantValue<QDateTime>(tmpev).isValid()) continue;
// We need to test for empty strings to
// avoid a stupid Qt warning
if( tmpsv.type() == QVariant::String && qVariantValue<QString>(tmpsv).isEmpty()) continue;
if( tmpev.type() == QVariant::String && qVariantValue<QString>(tmpev).isEmpty()) continue;
QDateTime tmpst = tmpsv.toDateTime();
QDateTime tmpet = tmpev.toDateTime();
if ( st.isNull() || st > tmpst ) st = tmpst;
if ( et.isNull() || et < tmpet ) et = tmpet;
}
QVariant tmpssv = sourceModel->data( mainIdx, StartTimeRole );
QVariant tmpsev = sourceModel->data( mainIdx, EndTimeRole );
if ( qVariantCanConvert<QDateTime>( tmpssv )
&& !( qVariantCanConvert<QString>( tmpssv ) && qVariantValue<QString>( tmpssv ).isEmpty() )
&& qVariantValue<QDateTime>( tmpssv ) != st )
sourceModel->setData( mainIdx, st, StartTimeRole );
if ( qVariantCanConvert<QDateTime>( tmpsev )
&& !( qVariantCanConvert<QString>( tmpsev ) && qVariantValue<QString>( tmpsev ).isEmpty() )
&& qVariantValue<QDateTime>( tmpsev ) != et )
sourceModel->setData( mainIdx, et, EndTimeRole );
cached_summary_items[sourceIdx]=qMakePair( st, et );
}
void SummaryHandlingProxyModel::Private::removeFromCache( const QModelIndex& idx ) const
{
cached_summary_items.remove( idx );
}
void SummaryHandlingProxyModel::Private::clearCache() const
{
cached_summary_items.clear();
}
/*! Constructor. Creates a new SummaryHandlingProxyModel with
* parent \a parent
*/
SummaryHandlingProxyModel::SummaryHandlingProxyModel( QObject* parent )
: BASE( parent ), _d( new Private )
{
init();
}
#define d d_func()
SummaryHandlingProxyModel::~SummaryHandlingProxyModel()
{
}
void SummaryHandlingProxyModel::init()
{
}
namespace {
// Think this is ugly? Well, it's not from me, it comes from QProxyModel
struct KDPrivateModelIndex {
int r, c;
void *p;
const QAbstractItemModel *m;
};
}
/*! Sets the model to be used as the source model for this proxy.
* The proxy does not take ownership of the model.
* \see QAbstractProxyModel::setSourceModel
*/
void SummaryHandlingProxyModel::setSourceModel( QAbstractItemModel* model )
{
BASE::setSourceModel( model );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceModelReset()
{
d->clearCache();
BASE::sourceModelReset();
}
void SummaryHandlingProxyModel::sourceLayoutChanged()
{
d->clearCache();
BASE::sourceLayoutChanged();
}
void SummaryHandlingProxyModel::sourceDataChanged( const QModelIndex& from, const QModelIndex& to )
{
QAbstractItemModel* model = sourceModel();
QModelIndex parentIdx = from;
do {
const QModelIndex& dataIdx = parentIdx;
if ( model->data( dataIdx, ItemTypeRole )==TypeSummary ) {
//qDebug() << "removing " << parentIdx << "from cache";
d->removeFromCache( dataIdx );
QModelIndex proxyDataIdx = mapFromSource( dataIdx );
emit dataChanged( proxyDataIdx, proxyDataIdx );
}
} while ( ( parentIdx=model->parent( parentIdx ) ) != QModelIndex() );
BASE::sourceDataChanged( from, to );
}
void SummaryHandlingProxyModel::sourceColumnsAboutToBeInserted( const QModelIndex& parentIdx,
int start,
int end )
{
BASE::sourceColumnsAboutToBeInserted( parentIdx, start, end );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceColumnsAboutToBeRemoved( const QModelIndex& parentIdx,
int start,
int end )
{
BASE::sourceColumnsAboutToBeRemoved( parentIdx, start, end );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceRowsAboutToBeInserted( const QModelIndex & parentIdx, int start, int end )
{
BASE::sourceRowsAboutToBeInserted( parentIdx, start, end );
d->clearCache();
}
void SummaryHandlingProxyModel::sourceRowsAboutToBeRemoved( const QModelIndex & parentIdx, int start, int end )
{
BASE::sourceRowsAboutToBeRemoved( parentIdx, start, end );
d->clearCache();
}
/*! \see QAbstractItemModel::flags */
Qt::ItemFlags SummaryHandlingProxyModel::flags( const QModelIndex& idx ) const
{
const QModelIndex sidx = mapToSource( idx );
const QAbstractItemModel* model = sourceModel();
Qt::ItemFlags f = model->flags( sidx );
if ( d->isSummary(sidx) ) {
f &= !Qt::ItemIsEditable;
}
return f;
}
/*! \see QAbstractItemModel::data */
QVariant SummaryHandlingProxyModel::data( const QModelIndex& proxyIndex, int role) const
{
//qDebug() << "SummaryHandlingProxyModel::data("<<proxyIndex<<role<<")";
const QModelIndex sidx = mapToSource( proxyIndex );
const QAbstractItemModel* model = sourceModel();
if ( d->isSummary(sidx) && ( role==StartTimeRole || role==EndTimeRole )) {
//qDebug() << "requested summary";
QPair<QDateTime,QDateTime> result;
if ( d->cacheLookup( sidx, &result ) ) {
//qDebug() << "SummaryHandlingProxyModel::data(): Looking up summary for " << proxyIndex << role;
switch( role ) {
case StartTimeRole: return result.first;
case EndTimeRole: return result.second;
default: /* fall thru */;
}
} else {
d->insertInCache( this, sidx );
return data( proxyIndex, role ); /* TODO: Optimise */
}
}
return model->data( sidx, role );
}
/*! \see QAbstractItemModel::setData */
bool SummaryHandlingProxyModel::setData( const QModelIndex& index, const QVariant& value, int role )
{
QAbstractItemModel* model = sourceModel();
if ( role==StartTimeRole || role==EndTimeRole ) {
QModelIndex parentIdx = mapToSource( index );
do {
if ( d->isSummary(parentIdx) ) {
//qDebug() << "removing " << parentIdx << "from cache";
d->removeFromCache( parentIdx );
QModelIndex proxyParentIdx = mapFromSource( parentIdx );
emit dataChanged( proxyParentIdx, proxyParentIdx );
}
} while ( ( parentIdx=model->parent( parentIdx ) ) != QModelIndex() );
}
return BASE::setData( index, value, role );
}
#undef d
#ifndef KDAB_NO_UNIT_TESTS
#include "unittest/test.h"
#include <QStandardItemModel>
namespace {
std::ostream& operator<<( std::ostream& os, const QDateTime& dt )
{
os << dt.toString().toStdString();
return os;
}
}
KDAB_SCOPED_UNITTEST_SIMPLE( KDGantt, SummaryHandlingProxyModel, "test" ) {
SummaryHandlingProxyModel model;
QStandardItemModel sourceModel;
model.setSourceModel( &sourceModel );
QStandardItem* topitem = new QStandardItem( QString::fromLatin1( "Summary" ) );
topitem->setData( KDGantt::TypeSummary, KDGantt::ItemTypeRole );
sourceModel.appendRow( topitem );
QStandardItem* task1 = new QStandardItem( QString::fromLatin1( "Task1" ) );
task1->setData( KDGantt::TypeTask, KDGantt::ItemTypeRole );
QStandardItem* task2 = new QStandardItem( QString::fromLatin1( "Task2" ) );
task2->setData( KDGantt::TypeTask, KDGantt::ItemTypeRole );
topitem->appendRow( task1 );
topitem->appendRow( task2 );
QDateTime startdt = QDateTime::currentDateTime();
QDateTime enddt = startdt.addDays( 1 );
task1->setData( startdt, KDGantt::StartTimeRole );
task1->setData( enddt, KDGantt::EndTimeRole );
task2->setData( startdt, KDGantt::StartTimeRole );
task2->setData( enddt, KDGantt::EndTimeRole );
const QModelIndex topidx = model.index( 0, 0, QModelIndex() );
assertEqual( model.data( topidx, KDGantt::ItemTypeRole ).toInt(), KDGantt::TypeSummary );
assertEqual( model.data( model.index( 0, 0, topidx ), KDGantt::ItemTypeRole ).toInt(), KDGantt::TypeTask );
QDateTime task1startdt = model.data( model.index( 0, 0, topidx ), KDGantt::StartTimeRole ).toDateTime();
assertEqual( task1startdt, startdt );
QDateTime summarystartdt = model.data( topidx, KDGantt::StartTimeRole ).toDateTime();
assertEqual( summarystartdt, startdt );
assertTrue( model.flags( model.index( 0, 0, topidx ) ) & Qt::ItemIsEditable );
assertFalse( model.flags( topidx ) & Qt::ItemIsEditable );
}
#endif /* KDAB_NO_UNIT_TESTS */
#include "moc_kdganttsummaryhandlingproxymodel.cpp"
|
Fix bug: summarytask disapears in chart if it contains an unscheduled task.
|
Fix bug: summarytask disapears in chart if it contains an unscheduled task.
svn path=/trunk/KDE/kdepim/; revision=887117
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
f2720a4a5510ef32f5dd8d2c871172c7a58c9005
|
Rpr/WrapObject/Materials/UberMaterialObject.cpp
|
Rpr/WrapObject/Materials/UberMaterialObject.cpp
|
#include "UberMaterialObject.h"
#include "TextureMaterialObject.h"
#include "ArithmeticMaterialObject.h"
#include "SceneGraph/uberv2material.h"
#include "SceneGraph/inputmaps.h"
#include "WrapObject/Exception.h"
using namespace RadeonRays;
using namespace Baikal;
UberMaterialObject::UberMaterialObject() :
MaterialObject(kUberV2)
{
m_mat = UberV2Material::Create();
}
void UberMaterialObject::SetInputF(const std::string & input_name, const RadeonRays::float4 & val)
{
// Optimization: if we create a new input, it will take additional time for kernel compilation,
// so we try to find existing input and set a new float value
auto& input = m_mat->GetInput(input_name, Baikal::Material::InputType::kInputMap);
if (input.value.input_map_value->m_type == Baikal::InputMap::InputMapType::kConstantFloat3)
{
auto float_map = std::static_pointer_cast<Baikal::InputMap_ConstantFloat3>(input.value.input_map_value);
float_map->SetValue(val);
}
else
{
auto inputMap = Baikal::InputMap_ConstantFloat3::Create(val);
m_mat->SetInputValue(input_name, inputMap);
}
}
void UberMaterialObject::SetInputU(const std::string& input_name, rpr_uint val)
{
// First - check if we set values that are parameters now
if (input_name == "uberv2.layers")
{
m_mat->SetLayers(val);
}
else if (input_name == "uberv2.refraction.ior_mode")
{
m_mat->LinkRefractionIOR(val == RPR_UBER_MATERIAL_REFRACTION_MODE_LINKED);
}
else if (input_name == "uberv2.refraction.thin_surface")
{
m_mat->SetThin(val != 0);
}
else if (input_name == "uberv2.emission.mode")
{
m_mat->SetDoubleSided(val == RPR_UBER_MATERIAL_EMISSION_MODE_DOUBLESIDED);
}
else if (input_name == "uberv2.sss.multiscatter")
{
m_mat->SetMultiscatter(val != 0);
}
else
{
m_mat->SetInputValue(input_name, val);
}
}
Baikal::Material::Ptr UberMaterialObject::GetMaterial()
{
return m_mat;
}
void UberMaterialObject::SetInputMaterial(const std::string & input_name, MaterialObject * input)
{
if (input->IsArithmetic())
{
ArithmeticMaterialObject *arithmetic = static_cast<ArithmeticMaterialObject*>(input);
m_mat->SetInputValue(input_name, arithmetic->GetInputMap());
}
else
{
throw Exception(RPR_ERROR_INTERNAL_ERROR, "Only arithmetic nodes allowed as UberV2 inputs");
}
}
void UberMaterialObject::SetInputTexture(const std::string & input_name, TextureMaterialObject * input)
{
try
{
if (input_name == "uberv2.bump")
{
auto sampler = Baikal::InputMap_SamplerBumpMap::Create(input->GetTexture());
auto remap = Baikal::InputMap_Remap::Create(
Baikal::InputMap_ConstantFloat3::Create(float3(0.0f, 1.0f, 0.0f)),
Baikal::InputMap_ConstantFloat3::Create(float3(-1.0f, 1.0f, 0.0f)),
sampler);
m_mat->SetInputValue("uberv2.shading_normal", remap);
}
else if (input_name == "uberv2.normal")
{
auto sampler = Baikal::InputMap_Sampler::Create(input->GetTexture());
auto remap = Baikal::InputMap_Remap::Create(
Baikal::InputMap_ConstantFloat3::Create(float3(0.0f, 1.0f, 0.0f)),
Baikal::InputMap_ConstantFloat3::Create(float3(-1.0f, 1.0f, 0.0f)),
sampler);
m_mat->SetInputValue("uberv2.shading_normal", remap);
}
else
{
auto sampler = Baikal::InputMap_Sampler::Create(input->GetTexture());
m_mat->SetInputValue(input_name, sampler);
}
}
catch (...)
{
//Ignore
return;
}
}
void UberMaterialObject::GetInput(int i, void* out, size_t* out_size)
{
//We have only int values as parameters for now
uint32_t *int_out = static_cast<uint32_t*>(out);
*out_size = sizeof(uint32_t);
switch (i)
{
case RPR_UBER_MATERIAL_LAYERS:
*int_out = m_mat->GetLayers();
break;
case RPR_UBER_MATERIAL_EMISSION_MODE:
*int_out = m_mat->isDoubleSided() ?
RPR_UBER_MATERIAL_EMISSION_MODE_DOUBLESIDED :
RPR_UBER_MATERIAL_EMISSION_MODE_SINGLESIDED;
break;
case RPR_UBER_MATERIAL_REFRACTION_IOR_MODE:
*int_out = m_mat->IsLinkRefractionIOR() ?
RPR_UBER_MATERIAL_REFRACTION_MODE_LINKED :
RPR_UBER_MATERIAL_REFRACTION_MODE_SEPARATE;
break;
case RPR_UBER_MATERIAL_SSS_MULTISCATTER:
*int_out = m_mat->IsMultiscatter() ? 1 : 0;
break;
case RPR_UBER_MATERIAL_REFRACTION_THIN_SURFACE:
*int_out = m_mat->IsThin() ? 1 : 0;
break;
default:
MaterialObject::GetInput(i, out, out_size);
}
}
|
#include "UberMaterialObject.h"
#include "TextureMaterialObject.h"
#include "ArithmeticMaterialObject.h"
#include "SceneGraph/uberv2material.h"
#include "SceneGraph/inputmaps.h"
#include "WrapObject/Exception.h"
using namespace RadeonRays;
using namespace Baikal;
UberMaterialObject::UberMaterialObject() :
MaterialObject(kUberV2)
{
m_mat = UberV2Material::Create();
}
void UberMaterialObject::SetInputF(const std::string & input_name, const RadeonRays::float4 & val)
{
// Optimization: if we create a new input, it will take additional time for kernel compilation,
// so we try to find existing input and set a new float value
auto& input = m_mat->GetInput(input_name, Baikal::Material::InputType::kInputMap);
if (input.value.input_map_value->m_type == Baikal::InputMap::InputMapType::kConstantFloat3)
{
auto float_map = std::static_pointer_cast<Baikal::InputMap_ConstantFloat3>(input.value.input_map_value);
float_map->SetValue(val);
}
else
{
auto input_map = Baikal::InputMap_ConstantFloat3::Create(val);
m_mat->SetInputValue(input_name, input_map);
}
}
void UberMaterialObject::SetInputU(const std::string& input_name, rpr_uint val)
{
// First - check if we set values that are parameters now
if (input_name == "uberv2.layers")
{
m_mat->SetLayers(val);
}
else if (input_name == "uberv2.refraction.ior_mode")
{
m_mat->LinkRefractionIOR(val == RPR_UBER_MATERIAL_REFRACTION_MODE_LINKED);
}
else if (input_name == "uberv2.refraction.thin_surface")
{
m_mat->SetThin(val != 0);
}
else if (input_name == "uberv2.emission.mode")
{
m_mat->SetDoubleSided(val == RPR_UBER_MATERIAL_EMISSION_MODE_DOUBLESIDED);
}
else if (input_name == "uberv2.sss.multiscatter")
{
m_mat->SetMultiscatter(val != 0);
}
else
{
m_mat->SetInputValue(input_name, val);
}
}
Baikal::Material::Ptr UberMaterialObject::GetMaterial()
{
return m_mat;
}
void UberMaterialObject::SetInputMaterial(const std::string & input_name, MaterialObject * input)
{
if (input->IsArithmetic())
{
ArithmeticMaterialObject *arithmetic = static_cast<ArithmeticMaterialObject*>(input);
m_mat->SetInputValue(input_name, arithmetic->GetInputMap());
}
else
{
throw Exception(RPR_ERROR_INTERNAL_ERROR, "Only arithmetic nodes allowed as UberV2 inputs");
}
}
void UberMaterialObject::SetInputTexture(const std::string & input_name, TextureMaterialObject * input)
{
try
{
if (input_name == "uberv2.bump")
{
auto sampler = Baikal::InputMap_SamplerBumpMap::Create(input->GetTexture());
auto remap = Baikal::InputMap_Remap::Create(
Baikal::InputMap_ConstantFloat3::Create(float3(0.0f, 1.0f, 0.0f)),
Baikal::InputMap_ConstantFloat3::Create(float3(-1.0f, 1.0f, 0.0f)),
sampler);
m_mat->SetInputValue("uberv2.shading_normal", remap);
}
else if (input_name == "uberv2.normal")
{
auto sampler = Baikal::InputMap_Sampler::Create(input->GetTexture());
auto remap = Baikal::InputMap_Remap::Create(
Baikal::InputMap_ConstantFloat3::Create(float3(0.0f, 1.0f, 0.0f)),
Baikal::InputMap_ConstantFloat3::Create(float3(-1.0f, 1.0f, 0.0f)),
sampler);
m_mat->SetInputValue("uberv2.shading_normal", remap);
}
else
{
auto sampler = Baikal::InputMap_Sampler::Create(input->GetTexture());
m_mat->SetInputValue(input_name, sampler);
}
}
catch (...)
{
//Ignore
return;
}
}
void UberMaterialObject::GetInput(int i, void* out, size_t* out_size)
{
//We have only int values as parameters for now
uint32_t *int_out = static_cast<uint32_t*>(out);
*out_size = sizeof(uint32_t);
switch (i)
{
case RPR_UBER_MATERIAL_LAYERS:
*int_out = m_mat->GetLayers();
break;
case RPR_UBER_MATERIAL_EMISSION_MODE:
*int_out = m_mat->isDoubleSided() ?
RPR_UBER_MATERIAL_EMISSION_MODE_DOUBLESIDED :
RPR_UBER_MATERIAL_EMISSION_MODE_SINGLESIDED;
break;
case RPR_UBER_MATERIAL_REFRACTION_IOR_MODE:
*int_out = m_mat->IsLinkRefractionIOR() ?
RPR_UBER_MATERIAL_REFRACTION_MODE_LINKED :
RPR_UBER_MATERIAL_REFRACTION_MODE_SEPARATE;
break;
case RPR_UBER_MATERIAL_SSS_MULTISCATTER:
*int_out = m_mat->IsMultiscatter() ? 1 : 0;
break;
case RPR_UBER_MATERIAL_REFRACTION_THIN_SURFACE:
*int_out = m_mat->IsThin() ? 1 : 0;
break;
default:
MaterialObject::GetInput(i, out, out_size);
}
}
|
Change inputMap -> input_map
|
Change inputMap -> input_map
|
C++
|
mit
|
GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal
|
9730e9acd3d8b13501d9052773c24f82702b752d
|
kernel/src/simulationTools/test/OSNSPTest.cpp
|
kernel/src/simulationTools/test/OSNSPTest.cpp
|
/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* 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 "OSNSPTest.hpp"
#include "EventsManager.hpp"
#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \
if ((alpha) == (omega)) CPPUNIT_FAIL(message);
// test suite registration
CPPUNIT_TEST_SUITE_REGISTRATION(OSNSPTest);
void OSNSPTest::setUp()
{
_A.reset(new SimpleMatrix(_n, _n, 0));
_b.reset(new SiconosVector(_n, 0));
_x0.reset(new SiconosVector(_n, 0));
}
void OSNSPTest::init()
{
_DS.reset(new FirstOrderLinearTIDS(_x0, _A, _b));
_TD.reset(new TimeDiscretisation(_t0, _h));
_nsds.reset(new NonSmoothDynamicalSystem(_t0, _T));
_osi.reset(new EulerMoreauOSI(_theta));
_nsds->insertDynamicalSystem(_DS);
_sim.reset(new TimeStepping(_TD, 0));
_sim->associate(_osi,_DS);
_sim->setNonSmoothDynamicalSystemPtr(_nsds);
}
void OSNSPTest::tearDown()
{}
void OSNSPTest::testAVI()
{
std::cout << "===========================================" <<std::endl;
std::cout << " ===== OSNSP tests start ... ===== " <<std::endl;
std::cout << "===========================================" <<std::endl;
std::cout << "------- implicit Twisting relation -------" <<std::endl;
_h = 1e-1;
_T = 20.0;
double G = 10.0;
double beta = .3;
_A->zero();
(*_A)(0, 1) = 1.0;
_x0->zero();
(*_x0)(0) = 10.0;
(*_x0)(1) = 10.0;
SP::SimpleMatrix B(new SimpleMatrix(_n, _n, 0));
SP::SimpleMatrix C(new SimpleMatrix(_n, _n));
(*B)(1, 0) = G;
(*B)(1, 1) = G*beta;
C->eye();
SP::FirstOrderLinearTIR rel(new FirstOrderLinearTIR(C, B));
SP::SimpleMatrix H(new SimpleMatrix(4, 2));
(*H)(0, 0) = 1.0;
(*H)(1, 0) = -_h/2.0;
(*H)(2, 0) = -1.0;
(*H)(3, 0) = _h/2.0;
(*H)(1, 1) = 1.0;
(*H)(3, 1) = -1.0;
SP::SiconosVector K(new SiconosVector(4));
(*K)(0) = -1.0;
(*K)(1) = -1.0;
(*K)(2) = -1.0;
(*K)(3) = -1.0;
SP::NonSmoothLaw nslaw(new NormalConeNSL(_n, H, K));
_DS.reset(new FirstOrderLinearTIDS(_x0, _A, _b));
_TD.reset(new TimeDiscretisation(_t0, _h));
_nsds.reset(new NonSmoothDynamicalSystem(_t0, _T));
SP::Interaction inter(new Interaction(nslaw, rel));
_osi.reset(new EulerMoreauOSI(_theta));
_nsds->insertDynamicalSystem(_DS);
_nsds->link(inter, _DS);
_sim->setNonSmoothDynamicalSystemPtr(_nsds);
_sim.reset(new TimeStepping(_TD));
_sim->associate(_osi,_DS);
SP::AVI osnspb(new AVI());
_sim->insertNonSmoothProblem(osnspb);
SimpleMatrix dataPlot((unsigned)ceil((_T - _t0) / _h) + 10, 5);
SiconosVector& xProc = *_DS->x();
SiconosVector& lambda = *inter->lambda(0);
unsigned int k = 0;
dataPlot(0, 0) = _t0;
dataPlot(0, 1) = (*_x0)(0);
dataPlot(0, 2) = (*_x0)(1);
dataPlot(0, 3) = -1.0;
dataPlot(0, 4) = -1.0;
while (_sim->hasNextEvent())
{
_sim->computeOneStep();
k++;
dataPlot(k, 0) = _sim->nextTime();
dataPlot(k, 1) = xProc(0);
dataPlot(k, 2) = xProc(1);
dataPlot(k, 3) = lambda(0);
dataPlot(k, 4) = lambda(1);
_sim->nextStep();
}
std::cout <<std::endl <<std::endl;
dataPlot.resize(k, dataPlot.size(1));
ioMatrix::write("testAVI.dat", "ascii", dataPlot, "noDim");
// Reference Matrix
SimpleMatrix dataPlotRef(dataPlot);
dataPlotRef.zero();
ioMatrix::read("testAVI.ref", "ascii", dataPlotRef);
SP::SiconosVector err(new SiconosVector(dataPlot.size(1)));
(dataPlot - dataPlotRef).normInfByColumn(err);
err->display();
double maxErr = err->getValue(0) > err->getValue(1) ? (err->getValue(0) > err->getValue(2) ? err->getValue(0) : err->getValue(2)) : (err->getValue(1) > err->getValue(2) ? err->getValue(1) : err->getValue(2));
std::cout << "------- Integration Ok, error = " << maxErr << " -------" <<std::endl;
if (maxErr > _tol)
{
dataPlot.display();
(dataPlot - dataPlotRef).display();
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("testAVI : ", maxErr < _tol, true);
}
|
/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* 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 "OSNSPTest.hpp"
#include "EventsManager.hpp"
#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \
if ((alpha) == (omega)) CPPUNIT_FAIL(message);
// test suite registration
CPPUNIT_TEST_SUITE_REGISTRATION(OSNSPTest);
void OSNSPTest::setUp()
{
_A.reset(new SimpleMatrix(_n, _n, 0));
_b.reset(new SiconosVector(_n, 0));
_x0.reset(new SiconosVector(_n, 0));
}
void OSNSPTest::init()
{
_DS.reset(new FirstOrderLinearTIDS(_x0, _A, _b));
_TD.reset(new TimeDiscretisation(_t0, _h));
_nsds.reset(new NonSmoothDynamicalSystem(_t0, _T));
_osi.reset(new EulerMoreauOSI(_theta));
_nsds->insertDynamicalSystem(_DS);
_sim.reset(new TimeStepping(_TD, 0));
_sim->associate(_osi,_DS);
_sim->setNonSmoothDynamicalSystemPtr(_nsds);
}
void OSNSPTest::tearDown()
{}
void OSNSPTest::testAVI()
{
std::cout << "===========================================" <<std::endl;
std::cout << " ===== OSNSP tests start ... ===== " <<std::endl;
std::cout << "===========================================" <<std::endl;
std::cout << "------- implicit Twisting relation -------" <<std::endl;
_h = 1e-1;
_T = 20.0;
double G = 10.0;
double beta = .3;
_A->zero();
(*_A)(0, 1) = 1.0;
_x0->zero();
(*_x0)(0) = 10.0;
(*_x0)(1) = 10.0;
SP::SimpleMatrix B(new SimpleMatrix(_n, _n, 0));
SP::SimpleMatrix C(new SimpleMatrix(_n, _n));
(*B)(1, 0) = G;
(*B)(1, 1) = G*beta;
C->eye();
SP::FirstOrderLinearTIR rel(new FirstOrderLinearTIR(C, B));
SP::SimpleMatrix H(new SimpleMatrix(4, 2));
(*H)(0, 0) = 1.0;
(*H)(1, 0) = -_h/2.0;
(*H)(2, 0) = -1.0;
(*H)(3, 0) = _h/2.0;
(*H)(1, 1) = 1.0;
(*H)(3, 1) = -1.0;
SP::SiconosVector K(new SiconosVector(4));
(*K)(0) = -1.0;
(*K)(1) = -1.0;
(*K)(2) = -1.0;
(*K)(3) = -1.0;
SP::NonSmoothLaw nslaw(new NormalConeNSL(_n, H, K));
_DS.reset(new FirstOrderLinearTIDS(_x0, _A, _b));
_TD.reset(new TimeDiscretisation(_t0, _h));
_nsds.reset(new NonSmoothDynamicalSystem(_t0, _T));
SP::Interaction inter(new Interaction(nslaw, rel));
_osi.reset(new EulerMoreauOSI(_theta));
_nsds->insertDynamicalSystem(_DS);
_nsds->link(inter, _DS);
_sim.reset(new TimeStepping(_nsds, _TD));
_sim->associate(_osi,_DS);
SP::AVI osnspb(new AVI());
_sim->insertNonSmoothProblem(osnspb);
SimpleMatrix dataPlot((unsigned)ceil((_T - _t0) / _h) + 10, 5);
SiconosVector& xProc = *_DS->x();
SiconosVector& lambda = *inter->lambda(0);
unsigned int k = 0;
dataPlot(0, 0) = _t0;
dataPlot(0, 1) = (*_x0)(0);
dataPlot(0, 2) = (*_x0)(1);
dataPlot(0, 3) = -1.0;
dataPlot(0, 4) = -1.0;
while (_sim->hasNextEvent())
{
_sim->computeOneStep();
k++;
dataPlot(k, 0) = _sim->nextTime();
dataPlot(k, 1) = xProc(0);
dataPlot(k, 2) = xProc(1);
dataPlot(k, 3) = lambda(0);
dataPlot(k, 4) = lambda(1);
_sim->nextStep();
}
std::cout <<std::endl <<std::endl;
dataPlot.resize(k, dataPlot.size(1));
ioMatrix::write("testAVI.dat", "ascii", dataPlot, "noDim");
// Reference Matrix
SimpleMatrix dataPlotRef(dataPlot);
dataPlotRef.zero();
ioMatrix::read("testAVI.ref", "ascii", dataPlotRef);
SP::SiconosVector err(new SiconosVector(dataPlot.size(1)));
(dataPlot - dataPlotRef).normInfByColumn(err);
err->display();
double maxErr = err->getValue(0) > err->getValue(1) ? (err->getValue(0) > err->getValue(2) ? err->getValue(0) : err->getValue(2)) : (err->getValue(1) > err->getValue(2) ? err->getValue(1) : err->getValue(2));
std::cout << "------- Integration Ok, error = " << maxErr << " -------" <<std::endl;
if (maxErr > _tol)
{
dataPlot.display();
(dataPlot - dataPlotRef).display();
}
CPPUNIT_ASSERT_EQUAL_MESSAGE("testAVI : ", maxErr < _tol, true);
}
|
update constructor in test
|
[kernel] update constructor in test
|
C++
|
apache-2.0
|
fperignon/siconos,siconos/siconos,fperignon/siconos,bremond/siconos,fperignon/siconos,siconos/siconos,bremond/siconos,bremond/siconos,bremond/siconos,radarsat1/siconos,bremond/siconos,radarsat1/siconos,radarsat1/siconos,siconos/siconos,siconos/siconos,radarsat1/siconos,fperignon/siconos,radarsat1/siconos,fperignon/siconos
|
fac212569d704905c24b7ac05bface046952a638
|
framework/src/output/ExodusOutput.C
|
framework/src/output/ExodusOutput.C
|
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ExodusOutput.h"
#include "Moose.h"
#include "MooseApp.h"
#include "ActionWarehouse.h"
#include "Problem.h"
#include "ActionFactory.h"
#include "MooseObjectAction.h"
#include "MooseInit.h"
#include "ExodusFormatter.h"
// libMesh
#include "libmesh/exodusII.h"
#include "libmesh/exodusII_io.h"
#include <sstream>
#include <iomanip>
ExodusOutput::ExodusOutput(MooseApp & app, EquationSystems & es, bool output_input, SubProblem & sub_problem, std::string name) :
Outputter(es, sub_problem, name),
_app(app),
_out(NULL),
_seq(declareRecoverableData<bool>("seq", false)),
_file_num(declareRecoverableData<int>("file_num", 0)),
_num(declareRecoverableData<int>("num", 0)),
_output_input(output_input),
_first(declareRecoverableData<bool>("first",true)),
_mesh_just_changed(declareRecoverableData<bool>("mesh_just_changed",false))
{
}
ExodusOutput::~ExodusOutput()
{
delete _out;
}
std::string
ExodusOutput::getFileName(const std::string & file_base)
{
std::ostringstream exodus_stream_file_base;
exodus_stream_file_base << file_base << ".e";
if (_seq)
{
/** Legacy output format
* exodus_stream_file_base << "_";
* OSSRealzeroright(exodus_stream_file_base, 4, 0, _file_num);
* return exodus_stream_file_base.str() + ".e";
*/
if (_file_num > 1)
{
exodus_stream_file_base << "-s"
<< std::setw(3)
<< std::setprecision(0)
<< std::setfill('0')
<< std::right
<< _file_num;
}
}
return exodus_stream_file_base.str();
}
void
ExodusOutput::output(const std::string & file_base, Real time, unsigned int /*t_step*/)
{
if (_out == NULL)
allocateExodusObject();
_num++;
_out->write_timestep(getFileName(file_base), _es, _num, time + _app.getGlobalTimeOffset());
_out->write_element_data(_es);
}
void
ExodusOutput::outputPps(const std::string & /*file_base*/, const FormattedTable & table, Real time)
{
if (_out == NULL)
return; // do nothing and safely return - we can write global vars (i.e. PPS only when output() occured)
// Check to see if the FormattedTable is empty, if so, return
if (table.getData().empty())
return;
// Search through the map, find a time in the table which matches the input time.
// Note: search in reverse, since the input time is most likely to be the most recent time.
const Real time_tol = 1.e-12;
std::map<Real, std::map<std::string, Real> >::const_reverse_iterator
rit = table.getData().rbegin(),
rend = table.getData().rend();
for (; rit != rend; ++rit)
{
// Difference between input time and the time stored in the table
Real time_diff = std::abs((time - (*rit).first));
// Get relative difference, but don't divide by zero!
if ( std::abs(time) > 0.)
time_diff /= std::abs(time);
// Break out of the loop if we found the right time
if (time_diff < time_tol)
break;
}
// If we didn't find anything, print an error message
if ( rit == rend )
{
Moose::err << "Input time: " << time
<< "\nLatest Table time: " << (*(table.getData().rbegin())).first << std::endl;
mooseError("Time mismatch in outputting Nemesis global variables\n"
"Have the postprocessor values been computed with the correct time?");
}
// Otherwise, fill local vectors with name/value information and write to file.
const std::map<std::string, Real> & tmp = (*rit).second;
std::vector<Real> global_vars;
std::vector<std::string> global_var_names;
global_vars.reserve(tmp.size());
global_var_names.reserve(tmp.size());
for (std::map<std::string, Real>::const_iterator ii = tmp.begin();
ii != tmp.end(); ++ii)
{
// Push back even though we know the exact size, saves us keeping
// track of one more index.
global_var_names.push_back( (*ii).first );
global_vars.push_back( (*ii).second );
}
_out->write_global_data( global_vars, global_var_names );
}
void
ExodusOutput::meshChanged()
{
_mesh_just_changed = true;
_append = false;
_num = 0;
delete _out;
_out = NULL;
}
void
ExodusOutput::outputInput()
{
// parser/action system are not mandatory subsystems to use, thus empty action system -> no input output
if (_app.actionWarehouse().empty())
return;
if (_out == NULL)
allocateExodusObject();
ExodusFormatter syntax_formatter;
syntax_formatter.printInputFile(_app.actionWarehouse());
syntax_formatter.format();
_out->write_information_records(syntax_formatter.getInputFileRecord());
}
void
ExodusOutput::setOutputPosition(const Point & /* p */)
{
if(_file_num == 0) // This might happen in the case of a MultiApp reset
_file_num = 1;
sequence(true);
meshChanged();
}
void
ExodusOutput::allocateExodusObject()
{
_out = new ExodusII_IO(_es.get_mesh());
_out->set_output_variables(_output_variables);
// Skip output of z coordinates for 2D meshes, but still
// write 1D meshes as 3D, otherwise Paraview has trouble
// viewing them for some reason.
if (_es.get_mesh().mesh_dimension() != 1)
_out->use_mesh_dimension_instead_of_spatial_dimension(true);
if(_app.hasOutputPosition())
_out->set_coordinate_offset(_app.getOutputPosition());
if(_first || _mesh_just_changed)
_file_num++;
_first = false;
_mesh_just_changed = false;
// Set the append flag on the underlying ExodusII_IO object
if(!_mesh_just_changed)
_out->append(_append);
}
|
/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "ExodusOutput.h"
#include "Moose.h"
#include "MooseApp.h"
#include "ActionWarehouse.h"
#include "Problem.h"
#include "ActionFactory.h"
#include "MooseObjectAction.h"
#include "MooseInit.h"
#include "ExodusFormatter.h"
// libMesh
#include "libmesh/exodusII.h"
#include "libmesh/exodusII_io.h"
#include <sstream>
#include <iomanip>
ExodusOutput::ExodusOutput(MooseApp & app, EquationSystems & es, bool output_input, SubProblem & sub_problem, std::string name) :
Outputter(es, sub_problem, name),
_app(app),
_out(NULL),
_seq(declareRecoverableData<bool>("seq", false)),
_file_num(declareRecoverableData<int>("file_num", 0)),
_num(declareRecoverableData<int>("num", 0)),
_output_input(output_input),
_first(declareRecoverableData<bool>("first",true)),
_mesh_just_changed(declareRecoverableData<bool>("mesh_just_changed",false))
{
}
ExodusOutput::~ExodusOutput()
{
delete _out;
}
std::string
ExodusOutput::getFileName(const std::string & file_base)
{
std::ostringstream exodus_stream_file_base;
exodus_stream_file_base << file_base << ".e";
if (_seq)
{
/** Legacy output format
* exodus_stream_file_base << "_";
* OSSRealzeroright(exodus_stream_file_base, 4, 0, _file_num);
* return exodus_stream_file_base.str() + ".e";
*/
if (_file_num > 1)
{
exodus_stream_file_base << "-s"
<< std::setw(3)
<< std::setprecision(0)
<< std::setfill('0')
<< std::right
<< _file_num;
}
}
return exodus_stream_file_base.str();
}
void
ExodusOutput::output(const std::string & file_base, Real time, unsigned int /*t_step*/)
{
if (_out == NULL)
allocateExodusObject();
_num++;
_out->write_timestep(getFileName(file_base), _es, _num, time + _app.getGlobalTimeOffset());
_out->write_element_data(_es);
}
void
ExodusOutput::outputPps(const std::string & /*file_base*/, const FormattedTable & table, Real time)
{
if (_out == NULL)
return; // do nothing and safely return - we can write global vars (i.e. PPS only when output() occured)
// Check to see if the FormattedTable is empty, if so, return
if (table.getData().empty())
return;
// Search through the map, find a time in the table which matches the input time.
// Note: search in reverse, since the input time is most likely to be the most recent time.
const Real time_tol = 1.e-12;
std::map<Real, std::map<std::string, Real> >::const_reverse_iterator
rit = table.getData().rbegin(),
rend = table.getData().rend();
for (; rit != rend; ++rit)
{
// Difference between input time and the time stored in the table
Real time_diff = std::abs((time - (*rit).first));
// Get relative difference, but don't divide by zero!
if ( std::abs(time) > 0.)
time_diff /= std::abs(time);
// Break out of the loop if we found the right time
if (time_diff < time_tol)
break;
}
// If we didn't find anything, print an error message
if ( rit == rend )
{
Moose::err << "Input time: " << time
<< "\nLatest Table time: " << (*(table.getData().rbegin())).first << std::endl;
mooseError("Time mismatch in outputting Nemesis global variables\n"
"Have the postprocessor values been computed with the correct time?");
}
// Otherwise, fill local vectors with name/value information and write to file.
const std::map<std::string, Real> & tmp = (*rit).second;
std::vector<Real> global_vars;
std::vector<std::string> global_var_names;
global_vars.reserve(tmp.size());
global_var_names.reserve(tmp.size());
for (std::map<std::string, Real>::const_iterator ii = tmp.begin();
ii != tmp.end(); ++ii)
{
// Push back even though we know the exact size, saves us keeping
// track of one more index.
global_var_names.push_back( (*ii).first );
global_vars.push_back( (*ii).second );
}
_out->write_global_data( global_vars, global_var_names );
}
void
ExodusOutput::meshChanged()
{
_mesh_just_changed = true;
_append = false;
_num = 0;
delete _out;
_out = NULL;
}
void
ExodusOutput::outputInput()
{
// parser/action system are not mandatory subsystems to use, thus empty action system -> no input output
if (_app.actionWarehouse().empty())
return;
if (_out == NULL)
allocateExodusObject();
ExodusFormatter syntax_formatter;
syntax_formatter.printInputFile(_app.actionWarehouse());
syntax_formatter.format();
_out->write_information_records(syntax_formatter.getInputFileRecord());
}
void
ExodusOutput::setOutputPosition(const Point & /* p */)
{
if(_file_num == 0) // This might happen in the case of a MultiApp reset
_file_num = 1;
sequence(true);
meshChanged();
}
void
ExodusOutput::allocateExodusObject()
{
_out = new ExodusII_IO(_es.get_mesh());
_out->set_output_variables(_output_variables, /*allow_empty=*/false);
// Skip output of z coordinates for 2D meshes, but still
// write 1D meshes as 3D, otherwise Paraview has trouble
// viewing them for some reason.
if (_es.get_mesh().mesh_dimension() != 1)
_out->use_mesh_dimension_instead_of_spatial_dimension(true);
if(_app.hasOutputPosition())
_out->set_coordinate_offset(_app.getOutputPosition());
if(_first || _mesh_just_changed)
_file_num++;
_first = false;
_mesh_just_changed = false;
// Set the append flag on the underlying ExodusII_IO object
if(!_mesh_just_changed)
_out->append(_append);
}
|
Patch from Andrew Slaughter for Output system - refs #1927
|
Patch from Andrew Slaughter for Output system - refs #1927
r24068
|
C++
|
lgpl-2.1
|
sapitts/moose,cpritam/moose,dschwen/moose,tonkmr/moose,jbair34/moose,jiangwen84/moose,SudiptaBiswas/moose,tonkmr/moose,shanestafford/moose,roystgnr/moose,andrsd/moose,yipenggao/moose,waxmanr/moose,zzyfisherman/moose,wgapl/moose,jbair34/moose,harterj/moose,jinmm1992/moose,jessecarterMOOSE/moose,tonkmr/moose,liuwenf/moose,bwspenc/moose,wgapl/moose,katyhuff/moose,nuclear-wizard/moose,adamLange/moose,jasondhales/moose,jasondhales/moose,jasondhales/moose,zzyfisherman/moose,jhbradley/moose,idaholab/moose,joshua-cogliati-inl/moose,tonkmr/moose,jhbradley/moose,jbair34/moose,milljm/moose,tonkmr/moose,andrsd/moose,apc-llc/moose,jessecarterMOOSE/moose,raghavaggarwal/moose,capitalaslash/moose,dschwen/moose,waxmanr/moose,bwspenc/moose,jinmm1992/moose,yipenggao/moose,markr622/moose,roystgnr/moose,mellis13/moose,permcody/moose,YaqiWang/moose,WilkAndy/moose,sapitts/moose,liuwenf/moose,dschwen/moose,wgapl/moose,jhbradley/moose,SudiptaBiswas/moose,cpritam/moose,permcody/moose,WilkAndy/moose,kasra83/moose,laagesen/moose,giopastor/moose,kasra83/moose,nuclear-wizard/moose,giopastor/moose,WilkAndy/moose,katyhuff/moose,Chuban/moose,YaqiWang/moose,adamLange/moose,shanestafford/moose,backmari/moose,jiangwen84/moose,sapitts/moose,xy515258/moose,cpritam/moose,friedmud/moose,zzyfisherman/moose,Chuban/moose,YaqiWang/moose,markr622/moose,SudiptaBiswas/moose,nuclear-wizard/moose,milljm/moose,Chuban/moose,xy515258/moose,raghavaggarwal/moose,cpritam/moose,nuclear-wizard/moose,stimpsonsg/moose,adamLange/moose,shanestafford/moose,stimpsonsg/moose,waxmanr/moose,shanestafford/moose,bwspenc/moose,jinmm1992/moose,tonkmr/moose,jbair34/moose,liuwenf/moose,markr622/moose,jasondhales/moose,WilkAndy/moose,kasra83/moose,giopastor/moose,idaholab/moose,roystgnr/moose,raghavaggarwal/moose,Chuban/moose,waxmanr/moose,backmari/moose,wgapl/moose,bwspenc/moose,jessecarterMOOSE/moose,bwspenc/moose,laagesen/moose,katyhuff/moose,apc-llc/moose,roystgnr/moose,yipenggao/moose,sapitts/moose,raghavaggarwal/moose,harterj/moose,idaholab/moose,cpritam/moose,danielru/moose,SudiptaBiswas/moose,WilkAndy/moose,roystgnr/moose,lindsayad/moose,liuwenf/moose,yipenggao/moose,dschwen/moose,lindsayad/moose,roystgnr/moose,joshua-cogliati-inl/moose,joshua-cogliati-inl/moose,milljm/moose,katyhuff/moose,cpritam/moose,laagesen/moose,danielru/moose,markr622/moose,roystgnr/moose,kasra83/moose,mellis13/moose,zzyfisherman/moose,harterj/moose,backmari/moose,andrsd/moose,xy515258/moose,adamLange/moose,lindsayad/moose,YaqiWang/moose,jiangwen84/moose,laagesen/moose,mellis13/moose,capitalaslash/moose,shanestafford/moose,zzyfisherman/moose,laagesen/moose,harterj/moose,andrsd/moose,jessecarterMOOSE/moose,apc-llc/moose,friedmud/moose,danielru/moose,milljm/moose,lindsayad/moose,mellis13/moose,milljm/moose,xy515258/moose,apc-llc/moose,permcody/moose,zzyfisherman/moose,WilkAndy/moose,jinmm1992/moose,backmari/moose,lindsayad/moose,idaholab/moose,idaholab/moose,shanestafford/moose,SudiptaBiswas/moose,jhbradley/moose,danielru/moose,capitalaslash/moose,stimpsonsg/moose,friedmud/moose,jessecarterMOOSE/moose,capitalaslash/moose,joshua-cogliati-inl/moose,liuwenf/moose,stimpsonsg/moose,sapitts/moose,liuwenf/moose,harterj/moose,giopastor/moose,andrsd/moose,friedmud/moose,dschwen/moose,permcody/moose,jiangwen84/moose
|
7a65fed9189a81a95ed31e7d0e649c40508e6cc6
|
trunk/extension/src/vcs.cpp
|
trunk/extension/src/vcs.cpp
|
/******************************************************************************\
* File: vcs.cpp
* Purpose: Implementation of wxExVCS class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/extension/vcs.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/frame.h>
#include <wx/extension/log.h>
#include <wx/extension/stcdlg.h>
#include <wx/extension/util.h>
wxExVCS* wxExVCS::m_Self = NULL;
#if wxUSE_GUI
wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;
#endif
wxExVCS::wxExVCS()
: m_Command(VCS_NO_COMMAND)
, m_FullPath(wxEmptyString)
{
Initialize();
}
wxExVCS::wxExVCS(int command_id, const wxString& fullpath)
: m_Command(GetType(command_id))
, m_FullPath(fullpath)
{
Initialize();
}
wxExVCS::wxExVCS(wxExVCSCommand type, const wxString& fullpath)
: m_Command(type)
, m_FullPath(fullpath)
{
Initialize();
}
#if wxUSE_GUI
int wxExVCS::ConfigDialog(
wxWindow* parent,
const wxString& title) const
{
std::vector<wxExConfigItem> v;
v.push_back(wxExConfigItem()); // a spacer item
std::map<long, const wxString> choices;
choices.insert(std::make_pair(VCS_NONE, _("None")));
choices.insert(std::make_pair(VCS_GIT, "GIT"));
choices.insert(std::make_pair(VCS_SVN, "SVN"));
v.push_back(wxExConfigItem("VCS", choices));
v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL));
v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL));
v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL));
return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif
bool wxExVCS::DirExists(const wxFileName& filename) const
{
if (!Use())
{
return false;
}
switch (GetVCS())
{
case VCS_GIT:
{
// The .git dir only exists in the root, so check all components.
wxFileName root(filename.GetPath());
while (root.DirExists() && root.GetDirCount() > 0)
{
wxFileName path(root);
path.AppendDir(".git");
if (path.DirExists())
{
return true;
}
root.RemoveLastDir();
}
}
break;
case VCS_SVN:
{
wxFileName path(filename);
path.AppendDir(".svn");
return path.DirExists();
}
break;
default: wxFAIL;
}
return false;
}
long wxExVCS::Execute()
{
wxASSERT(m_Command != VCS_NO_COMMAND);
wxString cwd;
wxString file;
if (m_FullPath.empty() && !cwd.empty())
{
cwd = wxGetCwd();
if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))))
{
m_Output = _("Cannot set working directory");
return -1;
}
if (m_Command == VCS_ADD)
{
file = " " + wxExConfigFirstOf(_("Path"));
}
}
else if (!m_FullPath.empty())
{
if (GetVCS() == VCS_GIT)
{
cwd = wxGetCwd();
wxSetWorkingDirectory(wxFileName(m_FullPath).GetPath());
file = " \"" + wxFileName(m_FullPath).GetFullName() + "\"";
}
else
{
file = " \"" + m_FullPath + "\"";
}
}
wxString comment;
if (m_Command == VCS_COMMIT)
{
comment =
" -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
}
wxString subcommand;
if (UseSubcommand())
{
subcommand = wxConfigBase::Get()->Read(_("Subcommand"));
if (!subcommand.empty())
{
subcommand = " " + subcommand;
}
}
wxString flags;
if (UseFlags())
{
flags = wxConfigBase::Get()->Read(_("Flags"));
if (!flags.empty())
{
flags = " " + flags;
}
}
m_CommandWithFlags = m_CommandString + flags;
wxString vcs_bin;
switch (GetVCS())
{
case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT"); break;
case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN"); break;
default: wxFAIL;
}
if (vcs_bin.empty())
{
wxLogError(GetVCSName() + " " + _("path is empty"));
return -1;
}
const wxString commandline =
vcs_bin + " " + m_CommandString + subcommand + flags + comment + file;
#if wxUSE_STATUSBAR
wxExFrame::StatusText(commandline);
#endif
wxArrayString output;
wxArrayString errors;
long retValue;
if ((retValue = wxExecute(
commandline,
output,
errors)) == -1)
{
// See also process, same log is shown.
wxLogError(_("Cannot execute") + ": " + commandline);
}
else
{
wxExLog::Get()->Log(commandline);
}
if (!cwd.empty())
{
wxSetWorkingDirectory(cwd);
}
m_Output.clear();
// First output the errors.
for (
size_t i = 0;
i < errors.GetCount();
i++)
{
m_Output += errors[i] + "\n";
}
// Then the normal output, will be empty if there are errors.
for (
size_t j = 0;
j < output.GetCount();
j++)
{
m_Output += output[j] + "\n";
}
return retValue;
}
#if wxUSE_GUI
wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)
{
if (ShowDialog(parent) == wxID_CANCEL)
{
return wxID_CANCEL;
}
if (UseFlags())
{
wxConfigBase::Get()->Write(m_FlagsKey,
wxConfigBase::Get()->Read(_("Flags")));
}
const long retValue = Execute();
return (retValue != -1 ? wxID_OK: wxID_CANCEL);
}
#endif
wxExVCS* wxExVCS::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
m_Self = new wxExVCS;
if (!wxConfigBase::Get()->Exists("VCS"))
{
wxConfigBase::Get()->Write("VCS", (long)VCS_NONE);
}
}
return m_Self;
}
wxExVCS::wxExVCSCommand wxExVCS::GetType(int command_id) const
{
switch (command_id)
{
case ID_EDIT_VCS_ADD:
case ID_VCS_ADD:
return VCS_ADD; break;
case ID_EDIT_VCS_BLAME:
case ID_VCS_BLAME:
return VCS_BLAME; break;
case ID_EDIT_VCS_CAT:
return VCS_CAT; break;
case ID_EDIT_VCS_COMMIT:
case ID_VCS_COMMIT:
return VCS_COMMIT; break;
case ID_EDIT_VCS_DIFF:
case ID_VCS_DIFF:
return VCS_DIFF; break;
case ID_EDIT_VCS_HELP:
case ID_VCS_HELP:
return VCS_HELP; break;
case ID_EDIT_VCS_INFO:
case ID_VCS_INFO:
return VCS_INFO; break;
case ID_EDIT_VCS_LOG:
case ID_VCS_LOG:
return VCS_LOG; break;
case ID_EDIT_VCS_LS:
case ID_VCS_LS:
return VCS_LS; break;
case ID_EDIT_VCS_PROPLIST:
case ID_VCS_PROPLIST:
return VCS_PROPLIST; break;
case ID_EDIT_VCS_PROPSET:
case ID_VCS_PROPSET:
return VCS_PROPSET; break;
case ID_EDIT_VCS_REVERT:
case ID_VCS_REVERT:
return VCS_REVERT; break;
case ID_EDIT_VCS_SHOW:
case ID_VCS_SHOW:
return VCS_SHOW; break;
case ID_EDIT_VCS_STAT:
case ID_VCS_STAT:
return VCS_STAT; break;
case ID_EDIT_VCS_UPDATE:
case ID_VCS_UPDATE:
return VCS_UPDATE; break;
default:
wxFAIL;
return VCS_NO_COMMAND;
break;
}
}
long wxExVCS::GetVCS() const
{
return wxConfigBase::Get()->ReadLong("VCS", VCS_SVN);
}
const wxString wxExVCS::GetVCSName() const
{
wxString text;
switch (GetVCS())
{
case VCS_GIT: text = "GIT"; break;
case VCS_SVN: text = "SVN"; break;
default: wxFAIL;
}
return text;
}
void wxExVCS::Initialize()
{
if (Use() && m_Command != VCS_NO_COMMAND)
{
switch (GetVCS())
{
case VCS_GIT:
switch (m_Command)
{
case VCS_ADD: m_CommandString = "add"; break;
case VCS_BLAME: m_CommandString = "blame"; break;
case VCS_CAT: break;
case VCS_COMMIT: m_CommandString = "push"; break;
case VCS_DIFF: m_CommandString = "diff"; break;
case VCS_HELP: m_CommandString = "help"; break;
case VCS_INFO: break;
case VCS_LOG: m_CommandString = "log"; break;
case VCS_LS: break;
case VCS_PROPLIST: break;
case VCS_PROPSET: break;
case VCS_REVERT: m_CommandString = "revert"; break;
case VCS_SHOW: m_CommandString = "show"; break;
case VCS_STAT: m_CommandString = "status"; break;
case VCS_UPDATE: m_CommandString = "update"; break;
default:
wxFAIL;
break;
}
break;
case VCS_SVN:
switch (m_Command)
{
case VCS_ADD: m_CommandString = "add"; break;
case VCS_BLAME: m_CommandString = "blame"; break;
case VCS_CAT: m_CommandString = "cat"; break;
case VCS_COMMIT: m_CommandString = "commit"; break;
case VCS_DIFF: m_CommandString = "diff"; break;
case VCS_HELP: m_CommandString = "help"; break;
case VCS_INFO: m_CommandString = "info"; break;
case VCS_LOG: m_CommandString = "log"; break;
case VCS_LS: m_CommandString = "ls"; break;
case VCS_PROPLIST: m_CommandString = "proplist"; break;
case VCS_PROPSET: m_CommandString = "propset"; break;
case VCS_REVERT: m_CommandString = "revert"; break;
case VCS_SHOW: break;
case VCS_STAT: m_CommandString = "stat"; break;
case VCS_UPDATE: m_CommandString = "update"; break;
default:
wxFAIL;
break;
}
break;
default: wxFAIL;
}
m_Caption = GetVCSName() + " " + m_CommandString;
// Currently no flags, as no command was executed.
m_CommandWithFlags = m_CommandString;
// Use general key.
m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command);
}
m_Output.clear();
}
#if wxUSE_GUI
wxStandardID wxExVCS::Request(wxWindow* parent)
{
wxStandardID retValue;
if ((retValue = ExecuteDialog(parent)) == wxID_OK)
{
ShowOutput(parent);
}
return retValue;
}
#endif
wxExVCS* wxExVCS::Set(wxExVCS* vcs)
{
wxExVCS* old = m_Self;
m_Self = vcs;
return old;
}
#if wxUSE_GUI
int wxExVCS::ShowDialog(wxWindow* parent)
{
std::vector<wxExConfigItem> v;
if (m_Command == VCS_COMMIT)
{
v.push_back(wxExConfigItem(
_("Revision comment"),
CONFIG_COMBOBOX,
wxEmptyString,
true)); // required
}
if (m_FullPath.empty() && m_Command != VCS_HELP)
{
v.push_back(wxExConfigItem(
_("Base folder"),
CONFIG_COMBOBOXDIR,
wxEmptyString,
true,
1000)); // TODO: fix
if (m_Command == VCS_ADD)
{
v.push_back(wxExConfigItem(
_("Path"),
CONFIG_COMBOBOX,
wxEmptyString,
true)); // required
}
}
if (UseFlags())
{
wxConfigBase::Get()->Write(
_("Flags"),
wxConfigBase::Get()->Read(m_FlagsKey));
v.push_back(wxExConfigItem(_("Flags")));
}
if (UseSubcommand())
{
v.push_back(wxExConfigItem(_("Subcommand")));
}
return wxExConfigDialog(parent,
v,
m_Caption).ShowModal();
}
#endif
#if wxUSE_GUI
void wxExVCS::ShowOutput(wxWindow* parent) const
{
wxString caption = m_Caption;
if (m_Command != VCS_HELP)
{
caption += " " + (!m_FullPath.empty() ?
wxFileName(m_FullPath).GetFullName():
wxExConfigFirstOf(_("Base folder")));
}
// Create a dialog for contents.
if (m_STCEntryDialog == NULL)
{
m_STCEntryDialog = new wxExSTCEntryDialog(
parent,
caption,
m_Output,
wxEmptyString,
wxOK);
}
else
{
m_STCEntryDialog->SetText(m_Output);
m_STCEntryDialog->SetTitle(caption);
}
// Add a lexer if we specified a path, asked for cat or blame
// and there is a lexer.
if (
!m_FullPath.empty() &&
(m_Command == VCS_CAT || m_Command == VCS_BLAME))
{
const wxExFileName fn(m_FullPath);
if (!fn.GetLexer().GetScintillaLexer().empty())
{
m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
}
}
m_STCEntryDialog->Show();
}
#endif
bool wxExVCS::Use() const
{
return GetVCS() != VCS_NONE;
}
bool wxExVCS::UseFlags() const
{
return m_Command != VCS_UPDATE && m_Command != VCS_HELP;
}
bool wxExVCS::UseSubcommand() const
{
return m_Command == VCS_HELP;
}
|
/******************************************************************************\
* File: vcs.cpp
* Purpose: Implementation of wxExVCS class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/extension/vcs.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/frame.h>
#include <wx/extension/log.h>
#include <wx/extension/stcdlg.h>
#include <wx/extension/util.h>
wxExVCS* wxExVCS::m_Self = NULL;
#if wxUSE_GUI
wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;
#endif
wxExVCS::wxExVCS()
: m_Command(VCS_NO_COMMAND)
, m_FullPath(wxEmptyString)
{
Initialize();
}
wxExVCS::wxExVCS(int command_id, const wxString& fullpath)
: m_Command(GetType(command_id))
, m_FullPath(fullpath)
{
Initialize();
}
wxExVCS::wxExVCS(wxExVCSCommand type, const wxString& fullpath)
: m_Command(type)
, m_FullPath(fullpath)
{
Initialize();
}
#if wxUSE_GUI
int wxExVCS::ConfigDialog(
wxWindow* parent,
const wxString& title) const
{
std::vector<wxExConfigItem> v;
v.push_back(wxExConfigItem()); // a spacer item
std::map<long, const wxString> choices;
choices.insert(std::make_pair(VCS_NONE, _("None")));
choices.insert(std::make_pair(VCS_GIT, "GIT"));
choices.insert(std::make_pair(VCS_SVN, "SVN"));
v.push_back(wxExConfigItem("VCS", choices));
v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL));
v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL));
v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL));
return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif
bool wxExVCS::DirExists(const wxFileName& filename) const
{
if (!Use())
{
return false;
}
switch (GetVCS())
{
case VCS_GIT:
{
// The .git dir only exists in the root, so check all components.
wxFileName root(filename.GetPath());
while (root.DirExists() && root.GetDirCount() > 0)
{
wxFileName path(root);
path.AppendDir(".git");
if (path.DirExists())
{
return true;
}
root.RemoveLastDir();
}
}
break;
case VCS_SVN:
{
wxFileName path(filename);
path.AppendDir(".svn");
return path.DirExists();
}
break;
default: wxFAIL;
}
return false;
}
long wxExVCS::Execute()
{
wxASSERT(m_Command != VCS_NO_COMMAND);
wxString cwd;
wxString file;
if (m_FullPath.empty() && !cwd.empty())
{
cwd = wxGetCwd();
if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))))
{
m_Output = _("Cannot set working directory");
return -1;
}
if (m_Command == VCS_ADD)
{
file = " " + wxExConfigFirstOf(_("Path"));
}
}
else if (!m_FullPath.empty())
{
if (GetVCS() == VCS_GIT)
{
cwd = wxGetCwd();
wxSetWorkingDirectory(wxFileName(m_FullPath).GetPath());
file = " \"" + wxFileName(m_FullPath).GetFullName() + "\"";
}
else
{
file = " \"" + m_FullPath + "\"";
}
}
wxString comment;
if (m_Command == VCS_COMMIT)
{
comment =
" -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
}
wxString subcommand;
if (UseSubcommand())
{
subcommand = wxConfigBase::Get()->Read(_("Subcommand"));
if (!subcommand.empty())
{
subcommand = " " + subcommand;
}
}
wxString flags;
if (UseFlags())
{
flags = wxConfigBase::Get()->Read(_("Flags"));
if (!flags.empty())
{
flags = " " + flags;
}
}
m_CommandWithFlags = m_CommandString + flags;
wxString vcs_bin;
switch (GetVCS())
{
case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT"); break;
case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN"); break;
default: wxFAIL;
}
if (vcs_bin.empty())
{
wxLogError(GetVCSName() + " " + _("path is empty"));
return -1;
}
const wxString commandline =
vcs_bin + " " + m_CommandString + subcommand + flags + comment + file;
#if wxUSE_STATUSBAR
wxExFrame::StatusText(commandline);
#endif
wxArrayString output;
wxArrayString errors;
long retValue;
if ((retValue = wxExecute(
commandline,
output,
errors)) == -1)
{
// See also process, same log is shown.
wxLogError(_("Cannot execute") + ": " + commandline);
}
else
{
wxExLog::Get()->Log(commandline);
}
if (!cwd.empty())
{
wxSetWorkingDirectory(cwd);
}
m_Output.clear();
// First output the errors.
for (
size_t i = 0;
i < errors.GetCount();
i++)
{
m_Output += errors[i] + "\n";
}
// Then the normal output, will be empty if there are errors.
for (
size_t j = 0;
j < output.GetCount();
j++)
{
m_Output += output[j] + "\n";
}
return retValue;
}
#if wxUSE_GUI
wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)
{
if (ShowDialog(parent) == wxID_CANCEL)
{
return wxID_CANCEL;
}
if (UseFlags())
{
wxConfigBase::Get()->Write(m_FlagsKey,
wxConfigBase::Get()->Read(_("Flags")));
}
const long retValue = Execute();
return (retValue != -1 ? wxID_OK: wxID_CANCEL);
}
#endif
wxExVCS* wxExVCS::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
m_Self = new wxExVCS;
if (!wxConfigBase::Get()->Exists("VCS"))
{
wxConfigBase::Get()->Write("VCS", (long)VCS_NONE);
}
}
return m_Self;
}
wxExVCS::wxExVCSCommand wxExVCS::GetType(int command_id) const
{
switch (command_id)
{
case ID_EDIT_VCS_ADD:
case ID_VCS_ADD:
return VCS_ADD; break;
case ID_EDIT_VCS_BLAME:
case ID_VCS_BLAME:
return VCS_BLAME; break;
case ID_EDIT_VCS_CAT:
return VCS_CAT; break;
case ID_EDIT_VCS_COMMIT:
case ID_VCS_COMMIT:
return VCS_COMMIT; break;
case ID_EDIT_VCS_DIFF:
case ID_VCS_DIFF:
return VCS_DIFF; break;
case ID_EDIT_VCS_HELP:
case ID_VCS_HELP:
return VCS_HELP; break;
case ID_EDIT_VCS_INFO:
case ID_VCS_INFO:
return VCS_INFO; break;
case ID_EDIT_VCS_LOG:
case ID_VCS_LOG:
return VCS_LOG; break;
case ID_EDIT_VCS_LS:
case ID_VCS_LS:
return VCS_LS; break;
case ID_EDIT_VCS_PROPLIST:
case ID_VCS_PROPLIST:
return VCS_PROPLIST; break;
case ID_EDIT_VCS_PROPSET:
case ID_VCS_PROPSET:
return VCS_PROPSET; break;
case ID_EDIT_VCS_REVERT:
case ID_VCS_REVERT:
return VCS_REVERT; break;
case ID_EDIT_VCS_SHOW:
case ID_VCS_SHOW:
return VCS_SHOW; break;
case ID_EDIT_VCS_STAT:
case ID_VCS_STAT:
return VCS_STAT; break;
case ID_EDIT_VCS_UPDATE:
case ID_VCS_UPDATE:
return VCS_UPDATE; break;
default:
wxFAIL;
return VCS_NO_COMMAND;
break;
}
}
long wxExVCS::GetVCS() const
{
return wxConfigBase::Get()->ReadLong("VCS", VCS_SVN);
}
const wxString wxExVCS::GetVCSName() const
{
wxString text;
switch (GetVCS())
{
case VCS_GIT: text = "GIT"; break;
case VCS_SVN: text = "SVN"; break;
default: wxFAIL;
}
return text;
}
void wxExVCS::Initialize()
{
if (Use() && m_Command != VCS_NO_COMMAND)
{
switch (GetVCS())
{
case VCS_GIT:
switch (m_Command)
{
case VCS_ADD: m_CommandString = "add"; break;
case VCS_BLAME: m_CommandString = "blame"; break;
case VCS_CAT: break;
case VCS_COMMIT: m_CommandString = "push"; break;
case VCS_DIFF: m_CommandString = "diff"; break;
case VCS_HELP: m_CommandString = "help"; break;
case VCS_INFO: break;
case VCS_LOG: m_CommandString = "log"; break;
case VCS_LS: break;
case VCS_PROPLIST: break;
case VCS_PROPSET: break;
case VCS_REVERT: m_CommandString = "revert"; break;
case VCS_SHOW: m_CommandString = "show"; break;
case VCS_STAT: m_CommandString = "status"; break;
case VCS_UPDATE: m_CommandString = "update"; break;
default:
wxFAIL;
break;
}
break;
case VCS_SVN:
switch (m_Command)
{
case VCS_ADD: m_CommandString = "add"; break;
case VCS_BLAME: m_CommandString = "blame"; break;
case VCS_CAT: m_CommandString = "cat"; break;
case VCS_COMMIT: m_CommandString = "commit"; break;
case VCS_DIFF: m_CommandString = "diff"; break;
case VCS_HELP: m_CommandString = "help"; break;
case VCS_INFO: m_CommandString = "info"; break;
case VCS_LOG: m_CommandString = "log"; break;
case VCS_LS: m_CommandString = "ls"; break;
case VCS_PROPLIST: m_CommandString = "proplist"; break;
case VCS_PROPSET: m_CommandString = "propset"; break;
case VCS_REVERT: m_CommandString = "revert"; break;
case VCS_SHOW: break;
case VCS_STAT: m_CommandString = "stat"; break;
case VCS_UPDATE: m_CommandString = "update"; break;
default:
wxFAIL;
break;
}
break;
default: wxFAIL;
}
m_Caption = GetVCSName() + " " + m_CommandString;
// Currently no flags, as no command was executed.
m_CommandWithFlags = m_CommandString;
// Use general key.
m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command);
}
m_Output.clear();
}
#if wxUSE_GUI
wxStandardID wxExVCS::Request(wxWindow* parent)
{
wxStandardID retValue;
if ((retValue = ExecuteDialog(parent)) == wxID_OK)
{
ShowOutput(parent);
}
return retValue;
}
#endif
wxExVCS* wxExVCS::Set(wxExVCS* vcs)
{
wxExVCS* old = m_Self;
m_Self = vcs;
return old;
}
#if wxUSE_GUI
int wxExVCS::ShowDialog(wxWindow* parent)
{
std::vector<wxExConfigItem> v;
if (m_Command == VCS_COMMIT)
{
v.push_back(wxExConfigItem(
_("Revision comment"),
CONFIG_COMBOBOX,
wxEmptyString,
true)); // required
}
if (m_FullPath.empty() && m_Command != VCS_HELP)
{
v.push_back(wxExConfigItem(
_("Base folder"),
CONFIG_COMBOBOXDIR,
wxEmptyString,
true,
1000)); // TODO: fix
if (m_Command == VCS_ADD)
{
v.push_back(wxExConfigItem(
_("Path"),
CONFIG_COMBOBOX,
wxEmptyString,
true)); // required
}
}
if (UseFlags())
{
wxConfigBase::Get()->Write(
_("Flags"),
wxConfigBase::Get()->Read(m_FlagsKey));
v.push_back(wxExConfigItem(_("Flags")));
}
if (UseSubcommand())
{
v.push_back(wxExConfigItem(_("Subcommand")));
}
return wxExConfigDialog(parent,
v,
m_Caption).ShowModal();
}
#endif
#if wxUSE_GUI
void wxExVCS::ShowOutput(wxWindow* parent) const
{
wxString caption = m_Caption;
if (m_Command != VCS_HELP)
{
caption += " " + (!m_FullPath.empty() ?
wxFileName(m_FullPath).GetFullName():
wxExConfigFirstOf(_("Base folder")));
}
// Create a dialog for contents.
if (m_STCEntryDialog == NULL)
{
m_STCEntryDialog = new wxExSTCEntryDialog(
parent,
caption,
m_Output,
wxEmptyString,
wxOK);
}
else
{
m_STCEntryDialog->SetText(m_Output);
m_STCEntryDialog->SetTitle(caption);
}
// Add a lexer if we specified a path, asked for cat or blame
// and there is a lexer.
if (
!m_FullPath.empty() &&
(m_Command == VCS_CAT || m_Command == VCS_BLAME))
{
const wxExFileName fn(m_FullPath);
if (!fn.GetLexer().GetScintillaLexer().empty())
{
m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
}
}
else
{
m_STCEntryDialog->SetLexer(wxEmptyString);
}
m_STCEntryDialog->Show();
}
#endif
bool wxExVCS::Use() const
{
return GetVCS() != VCS_NONE;
}
bool wxExVCS::UseFlags() const
{
return m_Command != VCS_UPDATE && m_Command != VCS_HELP;
}
bool wxExVCS::UseSubcommand() const
{
return m_Command == VCS_HELP;
}
|
set empty lexer in case we do not set a specific lexer
|
set empty lexer in case we do not set a specific lexer
git-svn-id: e171abefef93db0a74257c7d87d5b6400fe00c1f@3207 f22100f3-aa73-48fe-a4fb-fd497bb32605
|
C++
|
mit
|
antonvw/wxExtension,antonvw/wxExtension,antonvw/wxExtension
|
067d8915d6b7f85454cd61d034abe1e0094f9b94
|
inc/ow_oclsolver.cpp
|
inc/ow_oclsolver.cpp
|
#ifndef OW_OCLSOLVER
#define OW_OCLSOLVER
#include "ow_isolver.h"
namespace sibernetic {
namespace solver {
class ocl_solver : public i_solver {
public:
ocl_solver();
private:
};
}
}
#endif
|
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2011, 2017 OpenWorm.
* http://openworm.org
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://opensource.org/licenses/MIT
*
* Contributors:
* OpenWorm - http://openworm.org/people.html
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
#ifndef OW_OCLSOLVER
#define OW_OCLSOLVER
#include "ow_isolver.h"
namespace sibernetic {
namespace solver {
class ocl_solver : public i_solver {
public:
ocl_solver();
private:
};
}
}
#endif
|
add license to ow_oclsolver.cpp
|
add license to ow_oclsolver.cpp
|
C++
|
mit
|
skhayrulin/x_engine,skhayrulin/x_engine,skhayrulin/x_engine
|
ca6c6e1e9dff124ef758f60ac5bf5f2833872ea1
|
connection.cpp
|
connection.cpp
|
#include <sys/socket.h>
#include <sys/time.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include "connection.h"
using namespace std;
// Internal function to inmplement a more precise usleep on FreeBSD
void internal_usleep(unsigned udelay) {
// FIXME: Check whether this method is appropriate
#ifndef linux
if (udelay < 1000) {
struct timeval current_time;
struct timeval till_time;
gettimeofday(&till_time, NULL);
till_time.tv_usec += udelay;
till_time.tv_sec += till_time.tv_usec / 1000000;
till_time.tv_usec = till_time.tv_usec % 1000000;
do {
if (udelay > 66) {
sched_yield();
}
gettimeofday(¤t_time, NULL);
} while (current_time.tv_sec < till_time.tv_sec ||
current_time.tv_sec == till_time.tv_sec &&
current_time.tv_usec < till_time.tv_usec);
} else {
usleep(udelay);
}
#else
usleep(udelay);
#endif
}
// Receive 'size' bytes from 'sock' and places them to 'data'
void recvn(int sock, void *data, size_t size)
{
do {
register int bytes_recvd = recv(sock, data, size, 0);
if (bytes_recvd <= 0) {
throw ConnectionException(errno);
} else {
size -= bytes_recvd;
data = (uint8_t *)data + bytes_recvd;
}
} while(size > 0);
}
// Send 'size' bytes from 'data' to 'sock'
void sendn(int sock, const void *data, size_t size, int flags)
{
do {
register int bytes_sent = send(sock, data, size, flags);
if (bytes_sent < 0) {
if (errno == ENOBUFS) {
SDEBUG("ENOBUFS error occurred\n");
continue;
}
throw ConnectionException(errno);
} else {
size -= bytes_sent;
data = (uint8_t *)data + bytes_sent;
}
} while(size > 0);
}
void send_normal_conformation(int sock, uint32_t addr)
{
ReplyHeader rh(STATUS_OK, addr, 0);
sendn(sock, &rh, sizeof(rh), 0);
}
void send_incorrect_checksum(int sock, uint32_t addr)
{
ReplyHeader rh(STATUS_INCORRECT_CHECKSUM, addr, 0);
sendn(sock, &rh, sizeof(rh), 0);
}
void send_server_is_busy(int sock, uint32_t addr)
{
ReplyHeader rh(STATUS_SERVER_IS_BUSY, addr, 0);
sendn(sock, &rh, sizeof(rh), 0);
}
// Receives reply from 'sock'. Returns 0 if some reply has been received
// and -1 otherwise
int ReplyHeader::recv_reply(int sock, char **message, int flags)
{
register int recv_result;
recv_result = recv(sock, this, sizeof(ReplyHeader), flags);
if (recv_result > 0) {
// Something received
if ((unsigned)recv_result < sizeof(ReplyHeader)) {
// Receive remaining part of the header
recvn(sock, (uint8_t *)this + recv_result,
sizeof(ReplyHeader) - recv_result);
}
if (get_msg_length() > MAX_ERROR_LENGTH) {
throw ConnectionException(ConnectionException::corrupted_data_received);
} else if (get_msg_length() > 0) {
*message = (char *)malloc(get_msg_length() + 1);
(*message)[get_msg_length()] = '\0';
recvn(sock, *message, get_msg_length());
DEBUG("Received error message: %u, %x, %u, %s\n", get_status(),
get_address(), get_msg_length(), *message);
}
return 0;
} else {
if ((flags & MSG_DONTWAIT) == 0 || errno != EAGAIN) {
throw ConnectionException(errno);
}
return -1;
}
}
// Returns internet addresses, which the host has
// The returned value should be futher explicitly deleted.
int get_local_addresses(int sock, vector<uint32_t> *addresses,
vector<uint32_t> *masks) {
struct ifconf ifc;
// Get the available interfaces
int lastlen = 0;
ifc.ifc_len = sizeof(struct ifreq) * 28;
ifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len);
while(1) {
if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
ERROR("ioctl(SIOCGIFCONF) call returned the error: %s", strerror(errno));
return -1;
}
if (ifc.ifc_len != lastlen || lastlen == 0) {
lastlen = ifc.ifc_len;
ifc.ifc_len += sizeof(struct ifreq) * 12;
ifc.ifc_req = (struct ifreq *)realloc(ifc.ifc_req, ifc.ifc_len);
} else {
break;
}
}
DEBUG("Number of interfaces: %d(%zu)\n", ifc.ifc_len, sizeof(struct ifreq));
for (uint8_t *ptr = (uint8_t *)ifc.ifc_req;
ptr < (uint8_t *)ifc.ifc_req + ifc.ifc_len;) {
struct ifreq *ifr = (struct ifreq *)ptr;
#ifdef _SIZEOF_ADDR_IFREQ
/*
ptr += sizeof(ifr->ifr_name) +
max(sizeof(struct sockaddr), (unsigned)ifr->ifr_addr.sa_len);
*/
ptr += _SIZEOF_ADDR_IFREQ((*ifr));
#else
// For linux compartability
ptr = (uint8_t *)(ifr + 1);
#endif
if (ifr->ifr_addr.sa_family == AF_INET) {
uint32_t addr = ((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_addr;
// Get flags for the interface
if (ioctl(sock, SIOCGIFFLAGS, ifr) < 0) {
ERROR("ioctl(SIOCGIFFLAGS) call returned the error: %s",
strerror(errno));
return -1;
}
if ((ifr->ifr_flags & IFF_UP) == 0 ||
(ifr->ifr_flags & IFF_LOOPBACK) != 0) {
continue;
}
#ifndef NDEBUG
char iaddr[INET_ADDRSTRLEN];
DEBUG("Interface %s, address %s\n", ifr->ifr_name,
inet_ntop(AF_INET, &addr, iaddr, sizeof(iaddr)));
#endif
addresses->push_back(ntohl(addr));
if (masks != NULL) {
// Get network mask for the interface
if (ioctl(sock, SIOCGIFNETMASK, ifr) < 0) {
ERROR("Can't get network mask for the interface %s: %s",
ifr->ifr_name, strerror(errno));
return -1;
}
uint32_t addr = ((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_addr;
DEBUG("Network mask: %s\n",
inet_ntop(AF_INET, &addr, iaddr, sizeof(iaddr)));
masks->push_back(ntohl(addr));
}
}
}
free(ifc.ifc_req);
return 0;
}
|
#include <sys/socket.h>
#include <sys/time.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include "connection.h"
using namespace std;
// Internal function to inmplement a more precise usleep on FreeBSD
void internal_usleep(unsigned udelay) {
// FIXME: Check whether this method is appropriate
#ifndef linux
if (udelay < 1000) {
struct timeval current_time;
struct timeval till_time;
gettimeofday(&till_time, NULL);
till_time.tv_usec += udelay;
till_time.tv_sec += till_time.tv_usec / 1000000;
till_time.tv_usec = till_time.tv_usec % 1000000;
do {
if (udelay > 66) {
sched_yield();
}
gettimeofday(¤t_time, NULL);
} while (current_time.tv_sec < till_time.tv_sec ||
current_time.tv_sec == till_time.tv_sec &&
current_time.tv_usec < till_time.tv_usec);
} else {
usleep(udelay);
}
#else
usleep(udelay);
#endif
}
// Receive 'size' bytes from 'sock' and places them to 'data'
void recvn(int sock, void *data, size_t size)
{
do {
register int bytes_recvd = recv(sock, data, size, 0);
if (bytes_recvd <= 0) {
throw ConnectionException(errno);
} else {
size -= bytes_recvd;
data = (uint8_t *)data + bytes_recvd;
}
} while(size > 0);
}
// Send 'size' bytes from 'data' to 'sock'
void sendn(int sock, const void *data, size_t size, int flags)
{
do {
register int bytes_sent = send(sock, data, size, flags);
if (bytes_sent < 0) {
if (errno == ENOBUFS) {
SDEBUG("ENOBUFS error occurred\n");
continue;
}
throw ConnectionException(errno);
} else {
size -= bytes_sent;
data = (uint8_t *)data + bytes_sent;
}
} while(size > 0);
}
void send_normal_conformation(int sock, uint32_t addr)
{
ReplyHeader rh(STATUS_OK, addr, 0);
sendn(sock, &rh, sizeof(rh), 0);
}
void send_incorrect_checksum(int sock, uint32_t addr)
{
ReplyHeader rh(STATUS_INCORRECT_CHECKSUM, addr, 0);
sendn(sock, &rh, sizeof(rh), 0);
}
void send_server_is_busy(int sock, uint32_t addr)
{
ReplyHeader rh(STATUS_SERVER_IS_BUSY, addr, 0);
sendn(sock, &rh, sizeof(rh), 0);
}
// Receives reply from 'sock'. Returns 0 if some reply has been received
// and -1 otherwise
int ReplyHeader::recv_reply(int sock, char **message, int flags)
{
register int recv_result;
recv_result = recv(sock, this, sizeof(ReplyHeader), flags);
if (recv_result > 0) {
// Something received
if ((unsigned)recv_result < sizeof(ReplyHeader)) {
// Receive remaining part of the header
recvn(sock, (uint8_t *)this + recv_result,
sizeof(ReplyHeader) - recv_result);
}
if (get_msg_length() > MAX_ERROR_LENGTH) {
throw ConnectionException(ConnectionException::corrupted_data_received);
} else if (get_msg_length() > 0) {
*message = (char *)malloc(get_msg_length() + 1);
(*message)[get_msg_length()] = '\0';
recvn(sock, *message, get_msg_length());
DEBUG("Received error message: %u, %x, %u, %s\n", get_status(),
get_address(), get_msg_length(), *message);
}
return 0;
} else {
if ((flags & MSG_DONTWAIT) == 0 || errno != EAGAIN) {
throw ConnectionException(errno);
}
return -1;
}
}
// Returns internet addresses, which the host has
// The returned value should be futher explicitly deleted.
int get_local_addresses(int sock, vector<uint32_t> *addresses,
vector<uint32_t> *masks) {
struct ifconf ifc;
// Get the available interfaces
int lastlen = 0;
ifc.ifc_len = sizeof(struct ifreq) * 28;
ifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len);
while(1) {
if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
ERROR("ioctl(SIOCGIFCONF) call returned the error: %s", strerror(errno));
return -1;
}
if (ifc.ifc_len != lastlen || lastlen == 0) {
lastlen = ifc.ifc_len;
ifc.ifc_len += sizeof(struct ifreq) * 12;
ifc.ifc_req = (struct ifreq *)realloc(ifc.ifc_req, ifc.ifc_len);
} else {
break;
}
}
#ifndef linux
DEBUG("Number of interfaces: %d(%zu)\n", ifc.ifc_len, sizeof(struct ifreq));
#else
DEBUG("Number of interfaces: %d(%zu)\n",
ifc.ifc_len / sizeof(struct ifreq), sizeof(struct ifreq));
#endif
for (uint8_t *ptr = (uint8_t *)ifc.ifc_req;
ptr < (uint8_t *)ifc.ifc_req + ifc.ifc_len;) {
struct ifreq *ifr = (struct ifreq *)ptr;
#ifdef _SIZEOF_ADDR_IFREQ
/*
ptr += sizeof(ifr->ifr_name) +
max(sizeof(struct sockaddr), (unsigned)ifr->ifr_addr.sa_len);
*/
ptr += _SIZEOF_ADDR_IFREQ((*ifr));
#else
// For linux compartability
ptr = (uint8_t *)(ifr + 1);
#endif
if (ifr->ifr_addr.sa_family == AF_INET) {
uint32_t addr = ((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_addr;
// Get flags for the interface
if (ioctl(sock, SIOCGIFFLAGS, ifr) < 0) {
ERROR("ioctl(SIOCGIFFLAGS) call returned the error: %s",
strerror(errno));
return -1;
}
if ((ifr->ifr_flags & IFF_UP) == 0 ||
(ifr->ifr_flags & IFF_LOOPBACK) != 0) {
continue;
}
#ifndef NDEBUG
char iaddr[INET_ADDRSTRLEN];
DEBUG("Interface %s, address %s\n", ifr->ifr_name,
inet_ntop(AF_INET, &addr, iaddr, sizeof(iaddr)));
#endif
addresses->push_back(ntohl(addr));
if (masks != NULL) {
// Get network mask for the interface
if (ioctl(sock, SIOCGIFNETMASK, ifr) < 0) {
ERROR("Can't get network mask for the interface %s: %s",
ifr->ifr_name, strerror(errno));
return -1;
}
uint32_t addr = ((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr.s_addr;
DEBUG("Network mask: %s\n",
inet_ntop(AF_INET, &addr, iaddr, sizeof(iaddr)));
masks->push_back(ntohl(addr));
}
}
}
free(ifc.ifc_req);
return 0;
}
|
debug message fixed
|
debug message fixed
|
C++
|
bsd-3-clause
|
dzats/mcp,dzats/mcp
|
e96bdcb5b31e8cd212334f8665c81943aec82fe3
|
kythe/cxx/indexer/proto/kythe_indexer_main.cc
|
kythe/cxx/indexer/proto/kythe_indexer_main.cc
|
/*
* Copyright 2018 The Kythe 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.
*/
// Allows the Kythe Proto indexer to be invoked from the command line. By
// default, this program reads a single Proto compilation unit from stdin and
// emits binary Kythe artifacts to stdout as a sequence of Entity protos.
//
// eg: indexer foo.proto -o foo.bin
// indexer foo.proto | verifier foo.proto
// indexer -index_file some/file.kzip
// cat foo.proto | indexer | verifier foo.proto
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/gzip_stream.h"
#include "google/protobuf/io/zero_copy_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "kythe/cxx/common/file_vname_generator.h"
#include "kythe/cxx/common/indexing/KytheCachingOutput.h"
#include "kythe/cxx/common/indexing/KytheGraphRecorder.h"
#include "kythe/cxx/common/json_proto.h"
#include "kythe/cxx/common/kzip_reader.h"
#include "kythe/cxx/common/path_utils.h"
#include "kythe/cxx/indexer/proto/indexer_frontend.h"
#include "kythe/proto/analysis.pb.h"
DEFINE_string(o, "-", "Output filename.");
DEFINE_bool(flush_after_each_entry, false,
"Flush output after writing each entry.");
DEFINE_string(index_file, "", ".kzip file containing compilation unit.");
namespace kythe {
namespace {
/// Callback function to process a single compilation unit.
using CompilationVisitCallback = std::function<void(
const proto::CompilationUnit&, std::vector<proto::FileData> file_data)>;
/// \brief Reads all compilations from a .kzip file into memory.
/// \param path The path from which the file should be read.
/// \param visit Callback function called for each compiliation unit within the
/// kzip.
// TODO(justbuchanan): Refactor so that this function is shared with the cxx
// indexer. It was initially copied from cxx/indexer/frontend.cc.
void DecodeKzipFile(const std::string& path,
const CompilationVisitCallback& visit) {
StatusOr<IndexReader> reader = kythe::KzipReader::Open(path);
CHECK(reader) << "Couldn't open kzip from " << path;
bool compilation_read = false;
auto status = reader->Scan([&](absl::string_view digest) {
std::vector<proto::FileData> virtual_files;
auto compilation = reader->ReadUnit(digest);
for (const auto& file : compilation->unit().required_input()) {
auto content = reader->ReadFile(file.info().digest());
CHECK(content) << "Unable to read file with digest: "
<< file.info().digest() << ": " << content.status();
proto::FileData file_data;
file_data.set_content(*content);
file_data.mutable_info()->set_path(file.info().path());
file_data.mutable_info()->set_digest(file.info().digest());
virtual_files.push_back(std::move(file_data));
}
visit(compilation->unit(), std::move(virtual_files));
compilation_read = true;
return true;
});
CHECK(status.ok()) << status.ToString();
CHECK(compilation_read) << "Missing compilation in " << path;
}
bool ReadProtoFile(int fd, const std::string& relative_path,
const proto::VName& file_vname,
std::vector<proto::FileData>* files,
proto::CompilationUnit* unit) {
char buf[1024];
std::string source_data;
ssize_t amount_read;
while ((amount_read = ::read(fd, buf, sizeof buf)) > 0) {
absl::StrAppend(&source_data, absl::string_view(buf, amount_read));
}
if (amount_read < 0) {
LOG(ERROR) << "Error reading input file";
return false;
}
proto::FileData file_data;
file_data.set_content(source_data);
file_data.mutable_info()->set_path(CleanPath(relative_path));
proto::CompilationUnit::FileInput* file_input = unit->add_required_input();
*file_input->mutable_v_name() = file_vname;
*file_input->mutable_info() = file_data.info();
// keep the filename as entered on the command line in the argument list
unit->add_argument(relative_path);
unit->add_source_file(file_data.info().path());
files->push_back(std::move(file_data));
return true;
}
// TODO(justbuchanan): Get this from a library. Maybe abseil?
bool GetCurrentDirectory(std::string* dir) {
size_t len = 128;
auto buffer = absl::make_unique<char[]>(len);
for (;;) {
char* p = getcwd(buffer.get(), len);
if (p != nullptr) {
*dir = p;
return true;
} else if (errno == ERANGE) {
len += len;
buffer = absl::make_unique<char[]>(len);
} else {
return false;
}
}
}
} // anonymous namespace
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
gflags::SetUsageMessage(R"(Command-line frontend for the Kythe Proto indexer.
Invokes the Kythe Proto indexer on compilation unit(s). By default writes binary
Kythe artifacts to STDOUT as a sequence of Entity protos; this destination can
be overridden with the argument of -o.
If -index_file is specified, input will be read from its argument (which will
typically end in .kzip). No other positional parameters may be specified, nor
may an additional input parameter be specified.
If -index_file is not specified, all positional parameters (and any flags
following "--") are taken as arguments to the Proto compiler. Those ending in
.proto are taken as the filenames of the compilation unit to be analyzed; all
arguments are added to the compilation unit's "arguments" field. If no .proto
filenames are among these arguments, or if "-" is supplied, then source text
will be read from STDIN (and named "stdin.proto").
Examples:
indexer -index_file index.kzip
indexer -o foo.bin -- -Isome/path -Isome/other/path foo.proto
indexer foo.proto bar.proto | verifier foo.proto bar.proto")");
gflags::ParseCommandLineFlags(&argc, &argv, true);
std::vector<std::string> final_args(argv + 1, argv + argc);
std::string kzip_file;
if (!FLAGS_index_file.empty()) {
CHECK(final_args.empty())
<< "No positional arguments are allowed when reading "
<< "from an index file.";
kzip_file = FLAGS_index_file;
}
int write_fd = STDOUT_FILENO;
if (FLAGS_o != "-") {
write_fd = ::open(FLAGS_o.c_str(), O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
CHECK(write_fd != -1) << "Can't open output file";
}
bool had_error = false;
{
google::protobuf::io::FileOutputStream raw_output(write_fd);
kythe::FileOutputStream kythe_output(&raw_output);
kythe_output.set_flush_after_each_entry(FLAGS_flush_after_each_entry);
if (!kzip_file.empty()) {
DecodeKzipFile(kzip_file, [&](const proto::CompilationUnit& unit,
std::vector<proto::FileData> file_data) {
std::string err =
IndexProtoCompilationUnit(unit, file_data, &kythe_output);
if (!err.empty()) {
had_error = true;
LOG(ERROR) << "Error: " << err;
}
});
} else {
std::vector<proto::FileData> files;
proto::CompilationUnit unit;
GetCurrentDirectory(unit.mutable_working_directory());
FileVNameGenerator file_vnames;
bool stdin_requested = false;
for (const std::string& arg : final_args) {
if (arg == "-") {
stdin_requested = true;
} else if (absl::EndsWith(arg, ".proto")) {
int read_fd = ::open(arg.c_str(), O_RDONLY);
proto::VName file_vname = file_vnames.LookupVName(arg);
file_vname.set_path(CleanPath(file_vname.path()));
CHECK(ReadProtoFile(read_fd, arg, file_vname, &files, &unit))
<< "Read error for " << arg;
::close(read_fd);
} else {
LOG(ERROR) << "Adding protoc argument: " << arg;
unit.add_argument(arg);
}
}
if (stdin_requested || files.empty()) {
proto::VName stdin_vname;
stdin_vname.set_corpus(unit.v_name().corpus());
stdin_vname.set_root(unit.v_name().root());
stdin_vname.set_path("stdin.proto");
CHECK(ReadProtoFile(STDIN_FILENO, "stdin.proto", stdin_vname, &files,
&unit))
<< "Read error for protobuf on STDIN";
}
std::string err = IndexProtoCompilationUnit(unit, files, &kythe_output);
if (!err.empty()) {
had_error = true;
LOG(ERROR) << "Error: " << err;
}
}
}
CHECK(::close(write_fd) == 0) << "Error closing output file";
return had_error ? 1 : 0;
}
} // namespace kythe
int main(int argc, char* argv[]) { return kythe::main(argc, argv); }
|
/*
* Copyright 2018 The Kythe 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.
*/
// Allows the Kythe Proto indexer to be invoked from the command line. By
// default, this program reads a single Proto compilation unit from stdin and
// emits binary Kythe artifacts to stdout as a sequence of Entity protos.
//
// eg: indexer foo.proto -o foo.bin
// indexer foo.proto | verifier foo.proto
// indexer -index_file some/file.kzip
// cat foo.proto | indexer | verifier foo.proto
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/gzip_stream.h"
#include "google/protobuf/io/zero_copy_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "kythe/cxx/common/file_vname_generator.h"
#include "kythe/cxx/common/indexing/KytheCachingOutput.h"
#include "kythe/cxx/common/indexing/KytheGraphRecorder.h"
#include "kythe/cxx/common/json_proto.h"
#include "kythe/cxx/common/kzip_reader.h"
#include "kythe/cxx/common/path_utils.h"
#include "kythe/cxx/indexer/proto/indexer_frontend.h"
#include "kythe/proto/analysis.pb.h"
DEFINE_string(o, "-", "Output filename.");
DEFINE_bool(flush_after_each_entry, false,
"Flush output after writing each entry.");
DEFINE_string(index_file, "", ".kzip file containing compilation unit.");
namespace kythe {
namespace {
/// Callback function to process a single compilation unit.
using CompilationVisitCallback = std::function<void(
const proto::CompilationUnit&, std::vector<proto::FileData> file_data)>;
/// \brief Reads all compilations from a .kzip file into memory.
/// \param path The path from which the file should be read.
/// \param visit Callback function called for each compiliation unit within the
/// kzip.
// TODO(justbuchanan): Refactor so that this function is shared with the cxx
// indexer. It was initially copied from cxx/indexer/frontend.cc.
void DecodeKzipFile(const std::string& path,
const CompilationVisitCallback& visit) {
StatusOr<IndexReader> reader = kythe::KzipReader::Open(path);
CHECK(reader) << "Couldn't open kzip from " << path;
bool compilation_read = false;
auto status = reader->Scan([&](absl::string_view digest) {
std::vector<proto::FileData> virtual_files;
auto compilation = reader->ReadUnit(digest);
for (const auto& file : compilation->unit().required_input()) {
auto content = reader->ReadFile(file.info().digest());
CHECK(content) << "Unable to read file with digest: "
<< file.info().digest() << ": " << content.status();
proto::FileData file_data;
file_data.set_content(*content);
file_data.mutable_info()->set_path(file.info().path());
file_data.mutable_info()->set_digest(file.info().digest());
virtual_files.push_back(std::move(file_data));
}
visit(compilation->unit(), std::move(virtual_files));
compilation_read = true;
return true;
});
CHECK(status.ok()) << status.ToString();
CHECK(compilation_read) << "Missing compilation in " << path;
}
bool ReadProtoFile(int fd, const std::string& relative_path,
const proto::VName& file_vname,
std::vector<proto::FileData>* files,
proto::CompilationUnit* unit) {
char buf[1024];
std::string source_data;
ssize_t amount_read;
while ((amount_read = ::read(fd, buf, sizeof buf)) > 0) {
absl::StrAppend(&source_data, absl::string_view(buf, amount_read));
}
if (amount_read < 0) {
LOG(ERROR) << "Error reading input file";
return false;
}
proto::FileData file_data;
file_data.set_content(source_data);
file_data.mutable_info()->set_path(CleanPath(relative_path));
proto::CompilationUnit::FileInput* file_input = unit->add_required_input();
*file_input->mutable_v_name() = file_vname;
*file_input->mutable_info() = file_data.info();
// keep the filename as entered on the command line in the argument list
unit->add_argument(relative_path);
unit->add_source_file(file_data.info().path());
files->push_back(std::move(file_data));
return true;
}
// TODO(justbuchanan): Delete this and use the one from kythe's path_utils
// library
bool _GetCurrentDirectory(std::string* dir) {
size_t len = 128;
auto buffer = absl::make_unique<char[]>(len);
for (;;) {
char* p = getcwd(buffer.get(), len);
if (p != nullptr) {
*dir = p;
return true;
} else if (errno == ERANGE) {
len += len;
buffer = absl::make_unique<char[]>(len);
} else {
return false;
}
}
}
} // anonymous namespace
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
gflags::SetUsageMessage(R"(Command-line frontend for the Kythe Proto indexer.
Invokes the Kythe Proto indexer on compilation unit(s). By default writes binary
Kythe artifacts to STDOUT as a sequence of Entity protos; this destination can
be overridden with the argument of -o.
If -index_file is specified, input will be read from its argument (which will
typically end in .kzip). No other positional parameters may be specified, nor
may an additional input parameter be specified.
If -index_file is not specified, all positional parameters (and any flags
following "--") are taken as arguments to the Proto compiler. Those ending in
.proto are taken as the filenames of the compilation unit to be analyzed; all
arguments are added to the compilation unit's "arguments" field. If no .proto
filenames are among these arguments, or if "-" is supplied, then source text
will be read from STDIN (and named "stdin.proto").
Examples:
indexer -index_file index.kzip
indexer -o foo.bin -- -Isome/path -Isome/other/path foo.proto
indexer foo.proto bar.proto | verifier foo.proto bar.proto")");
gflags::ParseCommandLineFlags(&argc, &argv, true);
std::vector<std::string> final_args(argv + 1, argv + argc);
std::string kzip_file;
if (!FLAGS_index_file.empty()) {
CHECK(final_args.empty())
<< "No positional arguments are allowed when reading "
<< "from an index file.";
kzip_file = FLAGS_index_file;
}
int write_fd = STDOUT_FILENO;
if (FLAGS_o != "-") {
write_fd = ::open(FLAGS_o.c_str(), O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
CHECK(write_fd != -1) << "Can't open output file";
}
bool had_error = false;
{
google::protobuf::io::FileOutputStream raw_output(write_fd);
kythe::FileOutputStream kythe_output(&raw_output);
kythe_output.set_flush_after_each_entry(FLAGS_flush_after_each_entry);
if (!kzip_file.empty()) {
DecodeKzipFile(kzip_file, [&](const proto::CompilationUnit& unit,
std::vector<proto::FileData> file_data) {
std::string err =
IndexProtoCompilationUnit(unit, file_data, &kythe_output);
if (!err.empty()) {
had_error = true;
LOG(ERROR) << "Error: " << err;
}
});
} else {
std::vector<proto::FileData> files;
proto::CompilationUnit unit;
_GetCurrentDirectory(unit.mutable_working_directory());
FileVNameGenerator file_vnames;
bool stdin_requested = false;
for (const std::string& arg : final_args) {
if (arg == "-") {
stdin_requested = true;
} else if (absl::EndsWith(arg, ".proto")) {
int read_fd = ::open(arg.c_str(), O_RDONLY);
proto::VName file_vname = file_vnames.LookupVName(arg);
file_vname.set_path(CleanPath(file_vname.path()));
CHECK(ReadProtoFile(read_fd, arg, file_vname, &files, &unit))
<< "Read error for " << arg;
::close(read_fd);
} else {
LOG(ERROR) << "Adding protoc argument: " << arg;
unit.add_argument(arg);
}
}
if (stdin_requested || files.empty()) {
proto::VName stdin_vname;
stdin_vname.set_corpus(unit.v_name().corpus());
stdin_vname.set_root(unit.v_name().root());
stdin_vname.set_path("stdin.proto");
CHECK(ReadProtoFile(STDIN_FILENO, "stdin.proto", stdin_vname, &files,
&unit))
<< "Read error for protobuf on STDIN";
}
std::string err = IndexProtoCompilationUnit(unit, files, &kythe_output);
if (!err.empty()) {
had_error = true;
LOG(ERROR) << "Error: " << err;
}
}
}
CHECK(::close(write_fd) == 0) << "Error closing output file";
return had_error ? 1 : 0;
}
} // namespace kythe
int main(int argc, char* argv[]) { return kythe::main(argc, argv); }
|
rename GetCurrentDirectory() to avoid collisions (#23)
|
hack: rename GetCurrentDirectory() to avoid collisions (#23)
GetCurrentDirectory() is being added to the main kythe repo's path_utils
library. Once it's submitted, well delete the function from lang-proto.
In the meantime, they need to have different names to avoid issues.
|
C++
|
apache-2.0
|
kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe
|
7823dd6ecfeaaffd8af28d5da476799cf6c12a9b
|
C++Tutorials/Step_4/S4_ConditionalOperator.cpp
|
C++Tutorials/Step_4/S4_ConditionalOperator.cpp
|
//
// Program Name - S4_ConditionalOperator.cpp
// Series: GetOnToC++ Step: 4
//
// Purpose: This program illustrates how to use the Conditional operator
//
// Compile: g++ S4_ConditionalOperator.cpp -o S4_ConditionalOperator
// Execute: ./S4_ConditionalOperator
//
// Created by Narayan Mahadevan on 18/08/13.
//
#include <iostream>
using namespace std;
int main(){
int temp;
cin >> temp;
cout << "The temperature is "
<< temp
<< (temp == 1 ? " degree" : " degrees") //Boolean expression ? if-true expression : if false expression
<< endl;
}
|
//
// Program Name - S4_ConditionalOperator.cpp
// Series: GetOnToC++ Step: 4
//
// Purpose: This program illustrates how to use the Conditional operator
//
// Compile: g++ S4_ConditionalOperator.cpp -o S4_ConditionalOperator
// Execute: ./S4_ConditionalOperator
//
// Created by Narayan Mahadevan on 18/08/13.
//
#include <iostream>
using namespace std;
int main(){
int temp;
//Getting user input for temperature
cin >> temp;
//Printing the temperature
cout << "The temperature is "
<< temp
//Using the conditional operator so that if "degree" has right pluralization
<< (temp == 1 ? " degree" : " degrees") //Boolean expression ? if-true expression : if false expression
<< endl;
}
|
Update S4_ConditionalOperator.cpp
|
Update S4_ConditionalOperator.cpp
|
C++
|
apache-2.0
|
NarayanMahadevan/MakeTechEz
|
d098fb4f48c036e3d04d91e36242ab679b583b57
|
ndhs.cpp
|
ndhs.cpp
|
/* ndhs.c - DHCPv4/DHCPv6 and IPv6 router advertisement server
*
* Copyright 2014-2020 Nicholas J. Kain <njkain at gmail dot 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:
*
* - 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#define NDHS_VERSION "2.0"
#define LEASEFILE_PATH "/store/dynlease.txt"
#include <memory>
#include <string>
#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <signal.h>
#include <poll.h>
#include <errno.h>
#include <nk/from_string.hpp>
extern "C" {
#include "nk/log.h"
#include "nk/privs.h"
}
#include "nlsocket.hpp"
#include "dhcp6.hpp"
#include "dhcp4.hpp"
#include "dhcp_state.hpp"
#include "dynlease.hpp"
#include "duid.hpp"
enum class pfd_type
{
netlink,
dhcp6,
dhcp4,
radv6,
};
struct pfd_meta
{
pfd_meta(pfd_type p, void *d) : pfdt(p), data(d) {}
pfd_type pfdt;
void *data;
};
static std::string configfile{"/etc/ndhs.conf"};
static std::string chroot_path;
static uid_t ndhs_uid;
static gid_t ndhs_gid;
std::unique_ptr<NLSocket> nl_socket;
static std::vector<std::unique_ptr<D6Listener>> v6_listeners;
static std::vector<std::unique_ptr<D4Listener>> v4_listeners;
static std::vector<std::unique_ptr<RA6Listener>> r6_listeners;
static std::vector<struct pollfd> poll_vector;
static std::vector<pfd_meta> poll_meta;
extern void parse_config(const std::string &path);
static void init_listeners()
{
nl_socket = std::make_unique<NLSocket>(bound_interfaces_names());
struct pollfd pt;
pt.fd = nl_socket->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::netlink, nl_socket.get());
auto v6l = &v6_listeners;
auto vr6l = &r6_listeners;
auto v4l = &v4_listeners;
bound_interfaces_foreach([v6l, vr6l, v4l](const std::string &i, bool use_v4, bool use_v6,
uint8_t preference) {
if (use_v6) {
v6l->emplace_back(std::make_unique<D6Listener>());
if (!v6l->back()->init(i, preference)) {
v6l->pop_back();
log_line("Can't bind to dhcpv6 interface: %s", i.c_str());
} else {
vr6l->emplace_back(std::make_unique<RA6Listener>());
if (!vr6l->back()->init(i)) {
v6l->pop_back();
vr6l->pop_back();
log_line("Can't bind to rav6 interface: %s", i.c_str());
} else {
struct pollfd pt;
pt.fd = v6l->back()->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::dhcp6, v6l->back().get());
pt.fd = vr6l->back()->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::radv6, vr6l->back().get());
}
}
}
if (use_v4) {
v4l->emplace_back(std::make_unique<D4Listener>());
if (!v4l->back()->init(i)) {
v4l->pop_back();
log_line("Can't bind to dhcpv4 interface: %s", i.c_str());
} else {
struct pollfd pt;
pt.fd = v4l->back()->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::dhcp4, v4l->back().get());
}
}
});
}
int64_t get_current_ts()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
suicide("clock_gettime failed");
return ts.tv_sec;
}
void set_user_runas(size_t /* linenum */, std::string &&username)
{
if (nk_uidgidbyname(username.c_str(), &ndhs_uid, &ndhs_gid))
suicide("invalid user '%s' specified", username.c_str());
}
void set_chroot_path(size_t /* linenum */, std::string &&path)
{
chroot_path = std::move(path);
}
static volatile sig_atomic_t l_signal_exit;
static void signal_handler(int signo)
{
switch (signo) {
case SIGCHLD: {
while (waitpid(-1, nullptr, WNOHANG) > -1);
break;
}
case SIGINT:
case SIGTERM: l_signal_exit = 1; break;
default: break;
}
}
static void setup_signals_ndhs()
{
static const int ss[] = {
SIGCHLD, SIGINT, SIGTERM, SIGKILL
};
sigset_t mask;
if (sigprocmask(0, 0, &mask) < 0)
suicide("sigprocmask failed");
for (int i = 0; ss[i] != SIGKILL; ++i)
if (sigdelset(&mask, ss[i]))
suicide("sigdelset failed");
if (sigaddset(&mask, SIGPIPE))
suicide("sigaddset failed");
if (sigprocmask(SIG_SETMASK, &mask, static_cast<sigset_t *>(nullptr)) < 0)
suicide("sigprocmask failed");
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = signal_handler;
sa.sa_flags = SA_RESTART;
if (sigemptyset(&sa.sa_mask))
suicide("sigemptyset failed");
for (int i = 0; ss[i] != SIGKILL; ++i)
if (sigaction(ss[i], &sa, NULL))
suicide("sigaction failed");
}
static void usage()
{
printf("ndhs " NDHS_VERSION ", DHCPv4/DHCPv6 and IPv6 Router Advertisement server.\n");
printf("Copyright 2014-2020 Nicholas J. Kain\n");
printf("ndhs [options] [configfile]...\n\nOptions:");
printf("--config -c [] Path to configuration file.\n");
printf("--version -v Print version and exit.\n");
printf("--help -h Print this help and exit.\n");
}
static void print_version()
{
log_line("ndhs " NDHS_VERSION ", ipv6 router advertisment and dhcp server.\n"
"Copyright 2014-2020 Nicholas J. Kain\n"
"All rights reserved.\n\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are met:\n\n"
"- Redistributions of source code must retain the above copyright notice,\n"
" this list of conditions and the following disclaimer.\n"
"- Redistributions in binary form must reproduce the above copyright notice,\n"
" this list of conditions and the following disclaimer in the documentation\n"
" and/or other materials provided with the distribution.\n\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n"
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n"
"ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n"
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n"
"INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n"
"CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n"
"ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n"
"POSSIBILITY OF SUCH DAMAGE.\n");
}
static void process_options(int ac, char *av[])
{
static struct option long_options[] = {
{"config", 1, (int *)0, 'c'},
{"version", 0, (int *)0, 'v'},
{"help", 0, (int *)0, 'h'},
{(const char *)0, 0, (int *)0, 0 }
};
for (;;) {
auto c = getopt_long(ac, av, "qc:vh", long_options, (int *)0);
if (c == -1) break;
switch (c) {
case 'c': configfile = optarg; break;
case 'v': print_version(); std::exit(EXIT_SUCCESS); break;
case 'h': usage(); std::exit(EXIT_SUCCESS); break;
default: break;
}
}
if (configfile.size())
parse_config(configfile);
if (!bound_interfaces_count())
suicide("No interfaces have been bound");
if (!ndhs_uid || !ndhs_gid)
suicide("No non-root user account is specified.");
if (chroot_path.empty())
suicide("No chroot path is specified.");
init_listeners();
umask(077);
setup_signals_ndhs();
nk_set_chroot(chroot_path.c_str());
duid_load_from_file();
dynlease_deserialize(LEASEFILE_PATH);
nk_set_uidgid(ndhs_uid, ndhs_gid, nullptr, 0);
}
int main(int ac, char *av[])
{
process_options(ac, av);
for (;;) {
int timeout = INT_MAX;
for (auto &i: r6_listeners) {
auto t = i->send_periodic_advert();
timeout = std::min(timeout, t);
}
if (poll(poll_vector.data(), poll_vector.size(), timeout > 0 ? timeout : 0) < 0) {
if (errno != EINTR) suicide("poll failed");
}
if (l_signal_exit) break;
for (size_t i = 0, iend = poll_vector.size(); i < iend; ++i) {
switch (poll_meta[i].pfdt) {
case pfd_type::netlink: {
auto nl = static_cast<NLSocket *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("nlfd closed unexpectedly");
}
if (poll_vector[i].revents & POLLIN) {
nl->process_input();
}
} break;
case pfd_type::dhcp6: {
auto d6 = static_cast<D6Listener *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("%s: dhcp6 socket closed unexpectedly", d6->ifname().c_str());
}
if (poll_vector[i].revents & POLLIN) {
d6->process_input();
}
} break;
case pfd_type::dhcp4: {
auto d4 = static_cast<D4Listener *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("%s: dhcp4 socket closed unexpectedly", d4->ifname().c_str());
}
if (poll_vector[i].revents & POLLIN) {
d4->process_input();
}
} break;
case pfd_type::radv6: {
auto r6 = static_cast<RA6Listener *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("%s: ra6 socket closed unexpectedly", r6->ifname().c_str());
}
if (poll_vector[i].revents & POLLIN) {
r6->process_input();
}
} break;
}
}
}
dynlease_serialize(LEASEFILE_PATH);
std::exit(EXIT_SUCCESS);
}
|
/* ndhs.c - DHCPv4/DHCPv6 and IPv6 router advertisement server
*
* Copyright 2014-2020 Nicholas J. Kain <njkain at gmail dot 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:
*
* - 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#define NDHS_VERSION "2.0"
#define LEASEFILE_PATH "/store/dynlease.txt"
#include <memory>
#include <string>
#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <signal.h>
#include <poll.h>
#include <errno.h>
#include <nk/from_string.hpp>
extern "C" {
#include "nk/log.h"
#include "nk/privs.h"
}
#include "nlsocket.hpp"
#include "dhcp6.hpp"
#include "dhcp4.hpp"
#include "dhcp_state.hpp"
#include "dynlease.hpp"
#include "duid.hpp"
enum class pfd_type
{
netlink,
dhcp6,
dhcp4,
radv6,
};
struct pfd_meta
{
pfd_meta(pfd_type p, void *d) : pfdt(p), data(d) {}
pfd_type pfdt;
void *data;
};
static std::string configfile{"/etc/ndhs.conf"};
static std::string chroot_path;
static uid_t ndhs_uid;
static gid_t ndhs_gid;
std::unique_ptr<NLSocket> nl_socket;
static std::vector<std::unique_ptr<D6Listener>> v6_listeners;
static std::vector<std::unique_ptr<D4Listener>> v4_listeners;
static std::vector<std::unique_ptr<RA6Listener>> r6_listeners;
static std::vector<struct pollfd> poll_vector;
static std::vector<pfd_meta> poll_meta;
extern void parse_config(const std::string &path);
static void init_listeners()
{
nl_socket = std::make_unique<NLSocket>(bound_interfaces_names());
struct pollfd pt;
pt.fd = nl_socket->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::netlink, nl_socket.get());
{
auto bin = bound_interfaces_names();
for (const auto &i: bin)
log_line("Detected %s broadcast: %s subnet: %s", i.c_str(), query_broadcast(i)->to_string().c_str(),
query_subnet(i)->to_string().c_str());
}
auto v6l = &v6_listeners;
auto vr6l = &r6_listeners;
auto v4l = &v4_listeners;
bound_interfaces_foreach([v6l, vr6l, v4l](const std::string &i, bool use_v4, bool use_v6,
uint8_t preference) {
if (use_v6) {
v6l->emplace_back(std::make_unique<D6Listener>());
if (!v6l->back()->init(i, preference)) {
v6l->pop_back();
log_line("Can't bind to dhcpv6 interface: %s", i.c_str());
} else {
vr6l->emplace_back(std::make_unique<RA6Listener>());
if (!vr6l->back()->init(i)) {
v6l->pop_back();
vr6l->pop_back();
log_line("Can't bind to rav6 interface: %s", i.c_str());
} else {
struct pollfd pt;
pt.fd = v6l->back()->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::dhcp6, v6l->back().get());
pt.fd = vr6l->back()->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::radv6, vr6l->back().get());
}
}
}
if (use_v4) {
v4l->emplace_back(std::make_unique<D4Listener>());
if (!v4l->back()->init(i)) {
v4l->pop_back();
log_line("Can't bind to dhcpv4 interface: %s", i.c_str());
} else {
struct pollfd pt;
pt.fd = v4l->back()->fd();
pt.events = POLLIN|POLLHUP|POLLERR|POLLRDHUP;
pt.revents = 0;
poll_vector.push_back(pt);
poll_meta.emplace_back(pfd_type::dhcp4, v4l->back().get());
}
}
});
}
int64_t get_current_ts()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
suicide("clock_gettime failed");
return ts.tv_sec;
}
void set_user_runas(size_t /* linenum */, std::string &&username)
{
if (nk_uidgidbyname(username.c_str(), &ndhs_uid, &ndhs_gid))
suicide("invalid user '%s' specified", username.c_str());
}
void set_chroot_path(size_t /* linenum */, std::string &&path)
{
chroot_path = std::move(path);
}
static volatile sig_atomic_t l_signal_exit;
static void signal_handler(int signo)
{
switch (signo) {
case SIGCHLD: {
while (waitpid(-1, nullptr, WNOHANG) > -1);
break;
}
case SIGINT:
case SIGTERM: l_signal_exit = 1; break;
default: break;
}
}
static void setup_signals_ndhs()
{
static const int ss[] = {
SIGCHLD, SIGINT, SIGTERM, SIGKILL
};
sigset_t mask;
if (sigprocmask(0, 0, &mask) < 0)
suicide("sigprocmask failed");
for (int i = 0; ss[i] != SIGKILL; ++i)
if (sigdelset(&mask, ss[i]))
suicide("sigdelset failed");
if (sigaddset(&mask, SIGPIPE))
suicide("sigaddset failed");
if (sigprocmask(SIG_SETMASK, &mask, static_cast<sigset_t *>(nullptr)) < 0)
suicide("sigprocmask failed");
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = signal_handler;
sa.sa_flags = SA_RESTART;
if (sigemptyset(&sa.sa_mask))
suicide("sigemptyset failed");
for (int i = 0; ss[i] != SIGKILL; ++i)
if (sigaction(ss[i], &sa, NULL))
suicide("sigaction failed");
}
static void usage()
{
printf("ndhs " NDHS_VERSION ", DHCPv4/DHCPv6 and IPv6 Router Advertisement server.\n");
printf("Copyright 2014-2020 Nicholas J. Kain\n");
printf("ndhs [options] [configfile]...\n\nOptions:");
printf("--config -c [] Path to configuration file.\n");
printf("--version -v Print version and exit.\n");
printf("--help -h Print this help and exit.\n");
}
static void print_version()
{
log_line("ndhs " NDHS_VERSION ", ipv6 router advertisment and dhcp server.\n"
"Copyright 2014-2020 Nicholas J. Kain\n"
"All rights reserved.\n\n"
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are met:\n\n"
"- Redistributions of source code must retain the above copyright notice,\n"
" this list of conditions and the following disclaimer.\n"
"- Redistributions in binary form must reproduce the above copyright notice,\n"
" this list of conditions and the following disclaimer in the documentation\n"
" and/or other materials provided with the distribution.\n\n"
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n"
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n"
"ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n"
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n"
"INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n"
"CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n"
"ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n"
"POSSIBILITY OF SUCH DAMAGE.\n");
}
static void process_options(int ac, char *av[])
{
static struct option long_options[] = {
{"config", 1, (int *)0, 'c'},
{"version", 0, (int *)0, 'v'},
{"help", 0, (int *)0, 'h'},
{(const char *)0, 0, (int *)0, 0 }
};
for (;;) {
auto c = getopt_long(ac, av, "qc:vh", long_options, (int *)0);
if (c == -1) break;
switch (c) {
case 'c': configfile = optarg; break;
case 'v': print_version(); std::exit(EXIT_SUCCESS); break;
case 'h': usage(); std::exit(EXIT_SUCCESS); break;
default: break;
}
}
if (configfile.size())
parse_config(configfile);
if (!bound_interfaces_count())
suicide("No interfaces have been bound");
if (!ndhs_uid || !ndhs_gid)
suicide("No non-root user account is specified.");
if (chroot_path.empty())
suicide("No chroot path is specified.");
init_listeners();
umask(077);
setup_signals_ndhs();
nk_set_chroot(chroot_path.c_str());
duid_load_from_file();
dynlease_deserialize(LEASEFILE_PATH);
nk_set_uidgid(ndhs_uid, ndhs_gid, nullptr, 0);
}
int main(int ac, char *av[])
{
process_options(ac, av);
for (;;) {
int timeout = INT_MAX;
for (auto &i: r6_listeners) {
auto t = i->send_periodic_advert();
timeout = std::min(timeout, t);
}
if (poll(poll_vector.data(), poll_vector.size(), timeout > 0 ? timeout : 0) < 0) {
if (errno != EINTR) suicide("poll failed");
}
if (l_signal_exit) break;
for (size_t i = 0, iend = poll_vector.size(); i < iend; ++i) {
switch (poll_meta[i].pfdt) {
case pfd_type::netlink: {
auto nl = static_cast<NLSocket *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("nlfd closed unexpectedly");
}
if (poll_vector[i].revents & POLLIN) {
nl->process_input();
}
} break;
case pfd_type::dhcp6: {
auto d6 = static_cast<D6Listener *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("%s: dhcp6 socket closed unexpectedly", d6->ifname().c_str());
}
if (poll_vector[i].revents & POLLIN) {
d6->process_input();
}
} break;
case pfd_type::dhcp4: {
auto d4 = static_cast<D4Listener *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("%s: dhcp4 socket closed unexpectedly", d4->ifname().c_str());
}
if (poll_vector[i].revents & POLLIN) {
d4->process_input();
}
} break;
case pfd_type::radv6: {
auto r6 = static_cast<RA6Listener *>(poll_meta[i].data);
if (poll_vector[i].revents & (POLLHUP|POLLERR|POLLRDHUP)) {
suicide("%s: ra6 socket closed unexpectedly", r6->ifname().c_str());
}
if (poll_vector[i].revents & POLLIN) {
r6->process_input();
}
} break;
}
}
}
dynlease_serialize(LEASEFILE_PATH);
std::exit(EXIT_SUCCESS);
}
|
Print the detected broadcast/subnet for interfaces of interest.
|
ndhs: Print the detected broadcast/subnet for interfaces of interest.
|
C++
|
mit
|
niklata/ndhs,niklata/ndhs
|
a6376da990344e22d17b31cc958454b1fd1227ad
|
source/marchingcubes/MarchingCubesPainter.cpp
|
source/marchingcubes/MarchingCubesPainter.cpp
|
#include "MarchingCubesPainter.h"
#include <vector>
#include <glm/gtc/matrix_transform.hpp>
#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>
#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/Texture.h>
#include <widgetzeug/make_unique.hpp>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/resources/ResourceManager.h>
#include <gloperate/primitives/AdaptiveGrid.h>
#include "Chunk.h"
#include "ChunkRenderer.h"
using namespace gl;
using namespace glm;
using namespace globjects;
using widgetzeug::make_unique;
MarchingCubes::MarchingCubes(gloperate::ResourceManager & resourceManager)
: Painter(resourceManager)
, m_targetFramebufferCapability{ addCapability(new gloperate::TargetFramebufferCapability()) }
, m_viewportCapability{addCapability(new gloperate::ViewportCapability())}
, m_projectionCapability{addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability))}
, m_cameraCapability{addCapability(new gloperate::CameraCapability())}
, m_chunks()
, m_chunkRenderer()
{
}
MarchingCubes::~MarchingCubes() = default;
void MarchingCubes::setupProjection()
{
static const auto zNear = 0.3f, zFar = 100.f, fovy = 50.f;
m_projectionCapability->setZNear(zNear);
m_projectionCapability->setZFar(zFar);
m_projectionCapability->setFovy(radians(fovy));
m_grid->setNearFar(zNear, zFar);
}
void MarchingCubes::setupGrid()
{
m_grid = new gloperate::AdaptiveGrid{};
m_grid->setColor({ 0.6f, 0.6f, 0.6f });
}
void MarchingCubes::setupOpenGLState()
{
glClearColor(0.85f, 0.87f, 0.91f, 1.0f);
}
void MarchingCubes::onInitialize()
{
// create program
globjects::init();
#ifdef __APPLE__
Shader::clearGlobalReplacements();
Shader::globalReplace("#version 140", "#version 150");
debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif
setupGrid();
setupProjection();
setupOpenGLState();
auto groundTexture = m_resourceManager.load<Texture>("data/marchingcubes/ground.png");
groundTexture->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
groundTexture->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
m_chunkRenderer = new ChunkRenderer(groundTexture);
m_chunks = {};
int size = 7;
for (int z = 0; z < size; ++z)
{
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x)
{
auto newChunk = new Chunk(vec3(x, y, z));
m_chunkRenderer->generateDensities(newChunk);
m_chunkRenderer->generateMesh(newChunk);
m_chunks.push_back(newChunk);
}
}
}
}
void MarchingCubes::onPaint()
{
if (m_viewportCapability->hasChanged())
{
glViewport(
m_viewportCapability->x(),
m_viewportCapability->y(),
m_viewportCapability->width(),
m_viewportCapability->height());
m_viewportCapability->setChanged(false);
}
auto fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
fbo = globjects::Framebuffer::defaultFBO();
fbo->bind(GL_FRAMEBUFFER);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const auto transform = m_projectionCapability->projection() * m_cameraCapability->view();
const auto eye = m_cameraCapability->eye();
m_grid->update(eye, transform);
m_grid->draw();
m_chunkRenderer->setTransform(transform);
m_chunkRenderer->render(m_chunks);
Framebuffer::unbind(GL_FRAMEBUFFER);
}
|
#include "MarchingCubesPainter.h"
#include <vector>
#include <glm/gtc/matrix_transform.hpp>
#include <glbinding/gl/enum.h>
#include <glbinding/gl/bitfield.h>
#include <globjects/globjects.h>
#include <globjects/logging.h>
#include <globjects/DebugMessage.h>
#include <globjects/Texture.h>
#include <widgetzeug/make_unique.hpp>
#include <gloperate/painter/TargetFramebufferCapability.h>
#include <gloperate/painter/ViewportCapability.h>
#include <gloperate/painter/PerspectiveProjectionCapability.h>
#include <gloperate/painter/CameraCapability.h>
#include <gloperate/resources/ResourceManager.h>
#include <gloperate/primitives/AdaptiveGrid.h>
#include "Chunk.h"
#include "ChunkRenderer.h"
using namespace gl;
using namespace glm;
using namespace globjects;
using widgetzeug::make_unique;
MarchingCubes::MarchingCubes(gloperate::ResourceManager & resourceManager)
: Painter(resourceManager)
, m_targetFramebufferCapability{ addCapability(new gloperate::TargetFramebufferCapability()) }
, m_viewportCapability{addCapability(new gloperate::ViewportCapability())}
, m_projectionCapability{addCapability(new gloperate::PerspectiveProjectionCapability(m_viewportCapability))}
, m_cameraCapability{addCapability(new gloperate::CameraCapability())}
, m_chunks()
, m_chunkRenderer()
{
}
MarchingCubes::~MarchingCubes() = default;
void MarchingCubes::setupProjection()
{
static const auto zNear = 0.3f, zFar = 100.f, fovy = 50.f;
m_projectionCapability->setZNear(zNear);
m_projectionCapability->setZFar(zFar);
m_projectionCapability->setFovy(radians(fovy));
m_grid->setNearFar(zNear, zFar);
}
void MarchingCubes::setupGrid()
{
m_grid = new gloperate::AdaptiveGrid{};
m_grid->setColor({ 0.6f, 0.6f, 0.6f });
}
void MarchingCubes::setupOpenGLState()
{
glClearColor(0.85f, 0.87f, 0.91f, 1.0f);
}
void MarchingCubes::onInitialize()
{
// create program
globjects::init();
#ifdef __APPLE__
Shader::clearGlobalReplacements();
Shader::globalReplace("#version 140", "#version 150");
debug() << "Using global OS X shader replacement '#version 140' -> '#version 150'" << std::endl;
#endif
setupGrid();
setupProjection();
setupOpenGLState();
auto groundTexture = m_resourceManager.load<Texture>("data/marchingcubes/ground.png");
groundTexture->generateMipmap();
groundTexture->setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);
groundTexture->setParameter(GL_TEXTURE_WRAP_T, GL_REPEAT);
groundTexture->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
groundTexture->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
m_chunkRenderer = new ChunkRenderer(groundTexture);
m_chunks = {};
int size = 3;
for (int z = 0; z < size; ++z)
{
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x)
{
auto newChunk = new Chunk(vec3(x, y, z));
m_chunkRenderer->generateDensities(newChunk);
m_chunkRenderer->generateMesh(newChunk);
m_chunks.push_back(newChunk);
}
}
}
}
void MarchingCubes::onPaint()
{
if (m_viewportCapability->hasChanged())
{
glViewport(
m_viewportCapability->x(),
m_viewportCapability->y(),
m_viewportCapability->width(),
m_viewportCapability->height());
m_viewportCapability->setChanged(false);
}
auto fbo = m_targetFramebufferCapability->framebuffer();
if (!fbo)
fbo = globjects::Framebuffer::defaultFBO();
fbo->bind(GL_FRAMEBUFFER);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const auto transform = m_projectionCapability->projection() * m_cameraCapability->view();
const auto eye = m_cameraCapability->eye();
m_grid->update(eye, transform);
m_grid->draw();
m_chunkRenderer->setTransform(transform);
m_chunkRenderer->render(m_chunks);
Framebuffer::unbind(GL_FRAMEBUFFER);
}
|
Add mipmapping
|
Add mipmapping
|
C++
|
mit
|
JenniferStamm/glexamples
|
d57e55ec0dcf0974857e9c1823e84c2777dd82d7
|
lib/Analysis/DataStructure/TopDownClosure.cpp
|
lib/Analysis/DataStructure/TopDownClosure.cpp
|
//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TDDataStructures class, which represents the
// Top-down Interprocedural closure of the data structure graph over the
// program. This is useful (but not strictly necessary?) for applications
// like pointer analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure/DataStructure.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/DataStructure/DSGraph.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
namespace {
RegisterAnalysis<TDDataStructures> // Register the pass
Y("tddatastructure", "Top-down Data Structure Analysis");
Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
}
void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
hash_set<DSNode*> &Visited) {
if (!N || Visited.count(N)) return;
Visited.insert(N);
for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
if (DSNode *NN = NH.getNode()) {
std::vector<Function*> Functions;
NN->addFullFunctionList(Functions);
ArgsRemainIncomplete.insert(Functions.begin(), Functions.end());
markReachableFunctionsExternallyAccessible(NN, Visited);
}
}
}
// run - Calculate the top down data structure graphs for each function in the
// program.
//
bool TDDataStructures::runOnModule(Module &M) {
BUDataStructures &BU = getAnalysis<BUDataStructures>();
GlobalECs = BU.getGlobalECs();
GlobalsGraph = new DSGraph(BU.getGlobalsGraph(), GlobalECs);
GlobalsGraph->setPrintAuxCalls();
// Figure out which functions must not mark their arguments complete because
// they are accessible outside this compilation unit. Currently, these
// arguments are functions which are reachable by global variables in the
// globals graph.
const DSScalarMap &GGSM = GlobalsGraph->getScalarMap();
hash_set<DSNode*> Visited;
for (DSScalarMap::global_iterator I=GGSM.global_begin(), E=GGSM.global_end();
I != E; ++I)
markReachableFunctionsExternallyAccessible(GGSM.find(*I)->second.getNode(),
Visited);
// Loop over unresolved call nodes. Any functions passed into (but not
// returned!) from unresolvable call nodes may be invoked outside of the
// current module.
for (DSGraph::afc_iterator I = GlobalsGraph->afc_begin(),
E = GlobalsGraph->afc_end(); I != E; ++I)
for (unsigned arg = 0, e = I->getNumPtrArgs(); arg != e; ++arg)
markReachableFunctionsExternallyAccessible(I->getPtrArg(arg).getNode(),
Visited);
Visited.clear();
// Functions without internal linkage also have unknown incoming arguments!
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal() && !I->hasInternalLinkage())
ArgsRemainIncomplete.insert(I);
// We want to traverse the call graph in reverse post-order. To do this, we
// calculate a post-order traversal, then reverse it.
hash_set<DSGraph*> VisitedGraph;
std::vector<DSGraph*> PostOrder;
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Calculate top-down from main...
if (Function *F = M.getMainFunction())
ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
// Next calculate the graphs for each unreachable function...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
VisitedGraph.clear(); // Release memory!
// Visit each of the graphs in reverse post-order now!
while (!PostOrder.empty()) {
inlineGraphIntoCallees(*PostOrder.back());
PostOrder.pop_back();
}
ArgsRemainIncomplete.clear();
GlobalsGraph->removeTriviallyDeadNodes();
return false;
}
DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
DSGraph *&G = DSInfo[&F];
if (G == 0) { // Not created yet? Clone BU graph...
G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F), GlobalECs);
G->getAuxFunctionCalls().clear();
G->setPrintAuxCalls();
G->setGlobalsGraph(GlobalsGraph);
}
return *G;
}
void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
std::vector<DSGraph*> &PostOrder,
const BUDataStructures::ActualCalleesTy &ActualCallees) {
if (F.isExternal()) return;
DSGraph &G = getOrCreateDSGraph(F);
if (Visited.count(&G)) return;
Visited.insert(&G);
// Recursively traverse all of the callee graphs.
for (DSGraph::fc_iterator CI = G.fc_begin(), E = G.fc_end(); CI != E; ++CI) {
Instruction *CallI = CI->getCallSite().getInstruction();
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I)
ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
}
PostOrder.push_back(&G);
}
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
// FIXME: This should be releaseMemory and will work fine, except that LoadVN
// has no way to extend the lifetime of the pass, which screws up ds-aa.
//
void TDDataStructures::releaseMyMemory() {
for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I) {
I->second->getReturnNodes().erase(I->first);
if (I->second->getReturnNodes().empty())
delete I->second;
}
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
delete GlobalsGraph;
GlobalsGraph = 0;
}
void TDDataStructures::inlineGraphIntoCallees(DSGraph &Graph) {
// Recompute the Incomplete markers and eliminate unreachable nodes.
Graph.maskIncompleteMarkers();
// If any of the functions has incomplete incoming arguments, don't mark any
// of them as complete.
bool HasIncompleteArgs = false;
for (DSGraph::retnodes_iterator I = Graph.retnodes_begin(),
E = Graph.retnodes_end(); I != E; ++I)
if (ArgsRemainIncomplete.count(I->first)) {
HasIncompleteArgs = true;
break;
}
// Recompute the Incomplete markers. Depends on whether args are complete
unsigned Flags
= HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
Graph.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
// Delete dead nodes. Treat globals that are unreachable as dead also.
Graph.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
// We are done with computing the current TD Graph! Now move on to
// inlining the current graph into the graphs for its callees, if any.
//
if (Graph.fc_begin() == Graph.fc_end()) {
DEBUG(std::cerr << " [TD] No callees for: " << Graph.getFunctionNames()
<< "\n");
return;
}
// Now that we have information about all of the callees, propagate the
// current graph into the callees. Clone only the reachable subgraph at
// each call-site, not the entire graph (even though the entire graph
// would be cloned only once, this should still be better on average).
//
DEBUG(std::cerr << " [TD] Inlining '" << Graph.getFunctionNames() <<"' into "
<< Graph.getFunctionCalls().size() << " call nodes.\n");
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Loop over all the call sites and all the callees at each call site. Build
// a mapping from called DSGraph's to the call sites in this function that
// invoke them. This is useful because we can be more efficient if there are
// multiple call sites to the callees in the graph from this caller.
std::multimap<DSGraph*, std::pair<Function*, const DSCallSite*> > CallSites;
for (DSGraph::fc_iterator CI = Graph.fc_begin(), E = Graph.fc_end();
CI != E; ++CI) {
Instruction *CallI = CI->getCallSite().getInstruction();
// For each function in the invoked function list at this call site...
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
// Loop over each actual callee at this call site
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I) {
DSGraph& CalleeGraph = getDSGraph(*I->second);
if (&CalleeGraph != &Graph)
CallSites.insert(std::make_pair(&CalleeGraph,
std::make_pair(I->second, &*CI)));
}
}
// Now that we built the mapping, actually perform the inlining a callee graph
// at a time.
std::multimap<DSGraph*,std::pair<Function*,const DSCallSite*> >::iterator CSI;
for (CSI = CallSites.begin(); CSI != CallSites.end(); ) {
DSGraph &CalleeGraph = *CSI->first;
// Iterate through all of the call sites of this graph, cloning and merging
// any nodes required by the call.
ReachabilityCloner RC(CalleeGraph, Graph, 0);
// Clone over any global nodes that appear in both graphs.
for (DSScalarMap::global_iterator
SI = CalleeGraph.getScalarMap().global_begin(),
SE = CalleeGraph.getScalarMap().global_end(); SI != SE; ++SI) {
DSScalarMap::const_iterator GI = Graph.getScalarMap().find(*SI);
if (GI != Graph.getScalarMap().end())
RC.merge(CalleeGraph.getNodeForValue(*SI), GI->second);
}
// Loop over all of the distinct call sites in the caller of the callee.
for (; CSI != CallSites.end() && CSI->first == &CalleeGraph; ++CSI) {
Function &CF = *CSI->second.first;
const DSCallSite &CS = *CSI->second.second;
DEBUG(std::cerr << " [TD] Resolving arguments for callee graph '"
<< CalleeGraph.getFunctionNames()
<< "': " << CF.getFunctionType()->getNumParams()
<< " args\n at call site (DSCallSite*) 0x" << &CS << "\n");
// Get the formal argument and return nodes for the called function and
// merge them with the cloned subgraph.
RC.mergeCallSite(CalleeGraph.getCallSiteForArguments(CF), CS);
++NumTDInlines;
}
}
DEBUG(std::cerr << " [TD] Done inlining into callees for: "
<< Graph.getFunctionNames() << " [" << Graph.getGraphSize() << "+"
<< Graph.getFunctionCalls().size() << "]\n");
}
static const Function *getFnForValue(const Value *V) {
if (const Instruction *I = dyn_cast<Instruction>(V))
return I->getParent()->getParent();
else if (const Argument *A = dyn_cast<Argument>(V))
return A->getParent();
else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
return BB->getParent();
return 0;
}
void TDDataStructures::deleteValue(Value *V) {
if (const Function *F = getFnForValue(V)) { // Function local value?
// If this is a function local value, just delete it from the scalar map!
getDSGraph(*F).getScalarMap().eraseIfExists(V);
return;
}
if (Function *F = dyn_cast<Function>(V)) {
assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
"cannot handle scc's");
delete DSInfo[F];
DSInfo.erase(F);
return;
}
assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
}
void TDDataStructures::copyValue(Value *From, Value *To) {
if (From == To) return;
if (const Function *F = getFnForValue(From)) { // Function local value?
// If this is a function local value, just delete it from the scalar map!
getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
return;
}
if (Function *FromF = dyn_cast<Function>(From)) {
Function *ToF = cast<Function>(To);
assert(!DSInfo.count(ToF) && "New Function already exists!");
DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
DSInfo[ToF] = NG;
assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
// Change the Function* is the returnnodes map to the ToF.
DSNodeHandle Ret = NG->retnodes_begin()->second;
NG->getReturnNodes().clear();
NG->getReturnNodes()[ToF] = Ret;
return;
}
assert(!isa<GlobalVariable>(From) && "Do not know how to copy GV's yet!");
}
|
//===- TopDownClosure.cpp - Compute the top-down interprocedure closure ---===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TDDataStructures class, which represents the
// Top-down Interprocedural closure of the data structure graph over the
// program. This is useful (but not strictly necessary?) for applications
// like pointer analysis.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure/DataStructure.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/DataStructure/DSGraph.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
namespace {
RegisterAnalysis<TDDataStructures> // Register the pass
Y("tddatastructure", "Top-down Data Structure Analysis");
Statistic<> NumTDInlines("tddatastructures", "Number of graphs inlined");
}
void TDDataStructures::markReachableFunctionsExternallyAccessible(DSNode *N,
hash_set<DSNode*> &Visited) {
if (!N || Visited.count(N)) return;
Visited.insert(N);
for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i) {
DSNodeHandle &NH = N->getLink(i*N->getPointerSize());
if (DSNode *NN = NH.getNode()) {
std::vector<Function*> Functions;
NN->addFullFunctionList(Functions);
ArgsRemainIncomplete.insert(Functions.begin(), Functions.end());
markReachableFunctionsExternallyAccessible(NN, Visited);
}
}
}
// run - Calculate the top down data structure graphs for each function in the
// program.
//
bool TDDataStructures::runOnModule(Module &M) {
BUDataStructures &BU = getAnalysis<BUDataStructures>();
GlobalECs = BU.getGlobalECs();
GlobalsGraph = new DSGraph(BU.getGlobalsGraph(), GlobalECs);
GlobalsGraph->setPrintAuxCalls();
// Figure out which functions must not mark their arguments complete because
// they are accessible outside this compilation unit. Currently, these
// arguments are functions which are reachable by global variables in the
// globals graph.
const DSScalarMap &GGSM = GlobalsGraph->getScalarMap();
hash_set<DSNode*> Visited;
for (DSScalarMap::global_iterator I=GGSM.global_begin(), E=GGSM.global_end();
I != E; ++I)
markReachableFunctionsExternallyAccessible(GGSM.find(*I)->second.getNode(),
Visited);
// Loop over unresolved call nodes. Any functions passed into (but not
// returned!) from unresolvable call nodes may be invoked outside of the
// current module.
for (DSGraph::afc_iterator I = GlobalsGraph->afc_begin(),
E = GlobalsGraph->afc_end(); I != E; ++I)
for (unsigned arg = 0, e = I->getNumPtrArgs(); arg != e; ++arg)
markReachableFunctionsExternallyAccessible(I->getPtrArg(arg).getNode(),
Visited);
Visited.clear();
// Functions without internal linkage also have unknown incoming arguments!
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal() && !I->hasInternalLinkage())
ArgsRemainIncomplete.insert(I);
// We want to traverse the call graph in reverse post-order. To do this, we
// calculate a post-order traversal, then reverse it.
hash_set<DSGraph*> VisitedGraph;
std::vector<DSGraph*> PostOrder;
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Calculate top-down from main...
if (Function *F = M.getMainFunction())
ComputePostOrder(*F, VisitedGraph, PostOrder, ActualCallees);
// Next calculate the graphs for each unreachable function...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
ComputePostOrder(*I, VisitedGraph, PostOrder, ActualCallees);
VisitedGraph.clear(); // Release memory!
// Visit each of the graphs in reverse post-order now!
while (!PostOrder.empty()) {
InlineCallersIntoGraph(*PostOrder.back());
PostOrder.pop_back();
}
ArgsRemainIncomplete.clear();
GlobalsGraph->removeTriviallyDeadNodes();
return false;
}
DSGraph &TDDataStructures::getOrCreateDSGraph(Function &F) {
DSGraph *&G = DSInfo[&F];
if (G == 0) { // Not created yet? Clone BU graph...
G = new DSGraph(getAnalysis<BUDataStructures>().getDSGraph(F), GlobalECs);
G->getAuxFunctionCalls().clear();
G->setPrintAuxCalls();
G->setGlobalsGraph(GlobalsGraph);
}
return *G;
}
void TDDataStructures::ComputePostOrder(Function &F,hash_set<DSGraph*> &Visited,
std::vector<DSGraph*> &PostOrder,
const BUDataStructures::ActualCalleesTy &ActualCallees) {
if (F.isExternal()) return;
DSGraph &G = getOrCreateDSGraph(F);
if (Visited.count(&G)) return;
Visited.insert(&G);
// Recursively traverse all of the callee graphs.
for (DSGraph::fc_iterator CI = G.fc_begin(), E = G.fc_end(); CI != E; ++CI) {
Instruction *CallI = CI->getCallSite().getInstruction();
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I)
ComputePostOrder(*I->second, Visited, PostOrder, ActualCallees);
}
PostOrder.push_back(&G);
}
// releaseMemory - If the pass pipeline is done with this pass, we can release
// our memory... here...
//
// FIXME: This should be releaseMemory and will work fine, except that LoadVN
// has no way to extend the lifetime of the pass, which screws up ds-aa.
//
void TDDataStructures::releaseMyMemory() {
for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
E = DSInfo.end(); I != E; ++I) {
I->second->getReturnNodes().erase(I->first);
if (I->second->getReturnNodes().empty())
delete I->second;
}
// Empty map so next time memory is released, data structures are not
// re-deleted.
DSInfo.clear();
delete GlobalsGraph;
GlobalsGraph = 0;
}
/// InlineCallersIntoGraph - Inline all of the callers of the specified DS graph
/// into it, then recompute completeness of nodes in the resultant graph.
void TDDataStructures::InlineCallersIntoGraph(DSGraph &DSG) {
// Inline caller graphs into this graph. First step, get the list of call
// sites that call into this graph.
std::vector<CallerCallEdge> EdgesFromCaller;
std::map<DSGraph*, std::vector<CallerCallEdge> >::iterator
CEI = CallerEdges.find(&DSG);
if (CEI != CallerEdges.end()) {
std::swap(CEI->second, EdgesFromCaller);
CallerEdges.erase(CEI);
}
// Sort the caller sites to provide a by-caller-graph ordering.
std::sort(EdgesFromCaller.begin(), EdgesFromCaller.end());
// Merge information from the globals graph into this graph.
// FIXME: is this necessary?
{
DSGraph &GG = *DSG.getGlobalsGraph();
ReachabilityCloner RC(DSG, GG,
DSGraph::DontCloneCallNodes |
DSGraph::DontCloneAuxCallNodes);
for (DSScalarMap::global_iterator
GI = DSG.getScalarMap().global_begin(),
E = DSG.getScalarMap().global_end(); GI != E; ++GI)
RC.getClonedNH(GG.getNodeForValue(*GI));
}
DEBUG(std::cerr << "[TD] Inlining callers into '" << DSG.getFunctionNames()
<< "'\n");
// Iteratively inline caller graphs into this graph.
while (!EdgesFromCaller.empty()) {
DSGraph &CallerGraph = *EdgesFromCaller.back().CallerGraph;
// Iterate through all of the call sites of this graph, cloning and merging
// any nodes required by the call.
ReachabilityCloner RC(DSG, CallerGraph,
DSGraph::DontCloneCallNodes |
DSGraph::DontCloneAuxCallNodes);
// Inline all call sites from this caller graph.
do {
const DSCallSite &CS = *EdgesFromCaller.back().CS;
Function &CF = *EdgesFromCaller.back().CalledFunction;
DEBUG(std::cerr << " [TD] Inlining graph for call to Fn '"
<< CF.getName() << "' from Fn '"
<< CS.getCallSite().getInstruction()->
getParent()->getParent()->getName()
<< "': " << CF.getFunctionType()->getNumParams()
<< " args\n");
// Get the formal argument and return nodes for the called function and
// merge them with the cloned subgraph.
RC.mergeCallSite(DSG.getCallSiteForArguments(CF), CS);
++NumTDInlines;
EdgesFromCaller.pop_back();
} while (!EdgesFromCaller.empty() &&
EdgesFromCaller.back().CallerGraph == &CallerGraph);
}
// Next, now that this graph is finalized, we need to recompute the
// incompleteness markers for this graph and remove unreachable nodes.
DSG.maskIncompleteMarkers();
// If any of the functions has incomplete incoming arguments, don't mark any
// of them as complete.
bool HasIncompleteArgs = false;
for (DSGraph::retnodes_iterator I = DSG.retnodes_begin(),
E = DSG.retnodes_end(); I != E; ++I)
if (ArgsRemainIncomplete.count(I->first)) {
HasIncompleteArgs = true;
break;
}
// Recompute the Incomplete markers. Depends on whether args are complete
unsigned Flags
= HasIncompleteArgs ? DSGraph::MarkFormalArgs : DSGraph::IgnoreFormalArgs;
DSG.markIncompleteNodes(Flags | DSGraph::IgnoreGlobals);
// Delete dead nodes. Treat globals that are unreachable as dead also.
DSG.removeDeadNodes(DSGraph::RemoveUnreachableGlobals);
// We are done with computing the current TD Graph! Finally, before we can
// finish processing this function, we figure out which functions it calls and
// records these call graph edges, so that we have them when we process the
// callee graphs.
if (DSG.fc_begin() == DSG.fc_end()) return;
const BUDataStructures::ActualCalleesTy &ActualCallees =
getAnalysis<BUDataStructures>().getActualCallees();
// Loop over all the call sites and all the callees at each call site, and add
// edges to the CallerEdges structure for each callee.
for (DSGraph::fc_iterator CI = DSG.fc_begin(), E = DSG.fc_end();
CI != E; ++CI) {
Instruction *CallI = CI->getCallSite().getInstruction();
// For each function in the invoked function list at this call site...
std::pair<BUDataStructures::ActualCalleesTy::const_iterator,
BUDataStructures::ActualCalleesTy::const_iterator>
IP = ActualCallees.equal_range(CallI);
// Loop over each actual callee at this call site
for (BUDataStructures::ActualCalleesTy::const_iterator I = IP.first;
I != IP.second; ++I) {
DSGraph& CalleeGraph = getDSGraph(*I->second);
if (&CalleeGraph != &DSG)
CallerEdges[&CalleeGraph].push_back(CallerCallEdge(&DSG, &*CI,
I->second));
}
}
}
static const Function *getFnForValue(const Value *V) {
if (const Instruction *I = dyn_cast<Instruction>(V))
return I->getParent()->getParent();
else if (const Argument *A = dyn_cast<Argument>(V))
return A->getParent();
else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
return BB->getParent();
return 0;
}
void TDDataStructures::deleteValue(Value *V) {
if (const Function *F = getFnForValue(V)) { // Function local value?
// If this is a function local value, just delete it from the scalar map!
getDSGraph(*F).getScalarMap().eraseIfExists(V);
return;
}
if (Function *F = dyn_cast<Function>(V)) {
assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
"cannot handle scc's");
delete DSInfo[F];
DSInfo.erase(F);
return;
}
assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
}
void TDDataStructures::copyValue(Value *From, Value *To) {
if (From == To) return;
if (const Function *F = getFnForValue(From)) { // Function local value?
// If this is a function local value, just delete it from the scalar map!
getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
return;
}
if (Function *FromF = dyn_cast<Function>(From)) {
Function *ToF = cast<Function>(To);
assert(!DSInfo.count(ToF) && "New Function already exists!");
DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
DSInfo[ToF] = NG;
assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
// Change the Function* is the returnnodes map to the ToF.
DSNodeHandle Ret = NG->retnodes_begin()->second;
NG->getReturnNodes().clear();
NG->getReturnNodes()[ToF] = Ret;
return;
}
assert(!isa<GlobalVariable>(From) && "Do not know how to copy GV's yet!");
}
|
Change the way that the TD pass inlines graphs. Instead of inlining each graph into all of the functions it calls when we visit a graph, change it so that the graph visitor inlines all of the callers of a graph into the current graph when it visits it.
|
Change the way that the TD pass inlines graphs. Instead of inlining each
graph into all of the functions it calls when we visit a graph, change it so
that the graph visitor inlines all of the callers of a graph into the current
graph when it visits it.
While we're at it, inline global information from the GG instead of from each
of the callers. The GG contains a superset of the info that the callers do
anyway, and this way we only need to do it one time (not one for each caller).
This speeds up the TD pass substantially on several programs, and there is
still room for improvement. For example, the TD pass used to take 147s
on perlbmk, it now takes 36s. On povray, we went from about 5s to 1.97s.
134.perl is down from ~1s for Loc+BU+TD to .6s.
The TD pass needs a lot of improvement though, which will occur with later
patches.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@20723 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm
|
414576e3e79c83a2e61bc439574ab03d65ae1717
|
src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.H
|
src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_freq.H
/// @brief Calculate and save off DIMM frequencies
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef MSS_FREQ_H_
#define MSS_FREQ_H_
#include <fapi2.H>
#include <lib/freq/cas_latency.H>
#include <lib/freq/cycle_time.H>
#include <lib/shared/mss_const.H>
#include <lib/utils/conversions.H>
namespace mss
{
///
/// @brief Checks for frequency override and sets dimm frequency and timing values
/// @param[in] i_target mcbist fapi2 target
/// @param[out] o_tCK new cycle time if there is a freq override
/// @return FAPI2_RC_SUCCESS iff ok
///
inline fapi2::ReturnCode check_for_freq_override(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target,
uint64_t& o_tCK)
{
uint64_t l_freq_override = 0;
FAPI_TRY(freq_override(i_target, l_freq_override),
"Failed to override frequency!");
// If there is no override, don't change anything
if ( l_freq_override != fapi2::ENUM_ATTR_MSS_FREQ_OVERRIDE_AUTO)
{
o_tCK = mss::freq_to_ps(l_freq_override);
FAPI_DBG( "Override Frequency Detected: %d", l_freq_override);
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Sets DRAM CAS latency attributes
/// @param[in] i_target the controller target
/// @param[in] i_cas_latency final selected CAS ltency
/// @return FAPI2_RC_SUCCESS iff ok
///
inline fapi2::ReturnCode set_CL_attr(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target,
uint64_t i_cas_latency)
{
// Declaration of the vector correctly initializes it to the right size
// in the case the enum for PORTS_PER_MCS changes
std::vector<uint8_t> l_cls_vect(PORTS_PER_MCS, uint8_t(i_cas_latency) );
// set CAS latency attribute
// casts vector into the type FAPI_ATTR_SET is expecting by deduction
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_EFF_DRAM_CL,
i_target,
UINT8_VECTOR_TO_1D_ARRAY(l_cls_vect, PORTS_PER_MCS)) ,
"Failed to set CAS latency attribute");
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Sets frequency attributes
/// @param[in] i_target the controller target
/// @param[in] i_dimm_freq final selected dimm freq in MT/s
/// @return FAPI2_RC_SUCCESS iff ok
/// @note P9 Nimbus will support DMI speeds 16GB and 9.6GB
///
inline fapi2::ReturnCode set_freq_attrs(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target,
uint64_t i_dimm_freq)
{
// TK - RIT, needsto be corrected
uint64_t l_nest_freq = 2;
const auto l_mcbist = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
FAPI_INF("Setting freq attrs for %s", mss::c_str(i_target));
// TK
//Update for P9, what do we do w/setting nest freq? - AAM
// how do we select nest freq if we even have to??
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_NEST_CAPABLE_FREQUENCIES, l_mcbist, l_nest_freq),
"Failed to set nest capable frequencies attribute" );
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_MSS_FREQ, l_mcbist, i_dimm_freq),
"Failed to set mss freq attribute");
fapi_try_exit:
return fapi2::current_err;
}
}// mss namespace
typedef fapi2::ReturnCode (*p9_mss_freq_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);
extern "C"
{
///
/// @brief Calculate and save off DIMM frequencies
/// @param[in] i_target the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_freq( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target);
}
#endif
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_freq.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_freq.H
/// @brief Calculate and save off DIMM frequencies
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef MSS_FREQ_H_
#define MSS_FREQ_H_
#include <fapi2.H>
#include <lib/freq/cas_latency.H>
#include <lib/freq/cycle_time.H>
#include <lib/shared/mss_const.H>
#include <lib/utils/conversions.H>
namespace mss
{
///
/// @brief Checks for frequency override and sets dimm frequency and timing values
/// @param[in] i_target mcbist fapi2 target
/// @param[out] o_tCK new cycle time if there is a freq override
/// @return FAPI2_RC_SUCCESS iff ok
///
inline fapi2::ReturnCode check_for_freq_override(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target,
uint64_t& o_tCK)
{
uint64_t l_freq_override = 0;
FAPI_TRY(freq_override(i_target, l_freq_override),
"Failed to override frequency!");
// If there is no override, don't change anything
if ( l_freq_override != fapi2::ENUM_ATTR_MSS_FREQ_OVERRIDE_AUTO)
{
FAPI_TRY( mss::freq_to_ps(l_freq_override, o_tCK), "Failed freq_to_ps()");
FAPI_DBG( "Override Frequency Detected: %d", l_freq_override);
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Sets DRAM CAS latency attributes
/// @param[in] i_target the controller target
/// @param[in] i_cas_latency final selected CAS ltency
/// @return FAPI2_RC_SUCCESS iff ok
///
inline fapi2::ReturnCode set_CL_attr(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target,
uint64_t i_cas_latency)
{
// Declaration of the vector correctly initializes it to the right size
// in the case the enum for PORTS_PER_MCS changes
std::vector<uint8_t> l_cls_vect(PORTS_PER_MCS, uint8_t(i_cas_latency) );
// set CAS latency attribute
// casts vector into the type FAPI_ATTR_SET is expecting by deduction
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_EFF_DRAM_CL,
i_target,
UINT8_VECTOR_TO_1D_ARRAY(l_cls_vect, PORTS_PER_MCS)) ,
"Failed to set CAS latency attribute");
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Sets frequency attributes
/// @param[in] i_target the controller target
/// @param[in] i_dimm_freq final selected dimm freq in MT/s
/// @return FAPI2_RC_SUCCESS iff ok
/// @note P9 Nimbus will support DMI speeds 16GB and 9.6GB
///
inline fapi2::ReturnCode set_freq_attrs(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target,
uint64_t i_dimm_freq)
{
// TK - RIT, needsto be corrected
uint64_t l_nest_freq = 2;
const auto l_mcbist = mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
FAPI_INF("Setting freq attrs for %s", mss::c_str(i_target));
// TK
//Update for P9, what do we do w/setting nest freq? - AAM
// how do we select nest freq if we even have to??
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_NEST_CAPABLE_FREQUENCIES, l_mcbist, l_nest_freq),
"Failed to set nest capable frequencies attribute" );
FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_MSS_FREQ, l_mcbist, i_dimm_freq),
"Failed to set mss freq attribute");
fapi_try_exit:
return fapi2::current_err;
}
}// mss namespace
typedef fapi2::ReturnCode (*p9_mss_freq_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);
extern "C"
{
///
/// @brief Calculate and save off DIMM frequencies
/// @param[in] i_target the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_freq( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target);
}
#endif
|
Fix tREFI bug for eff_config, add and fix existing unit tests
|
Fix tREFI bug for eff_config, add and fix existing unit tests
Change-Id: I44cc0d4b75972180f9cdd3ae332e4d364aa75f8d
Original-Change-Id: I839315f414525102c4b7af7f3c57b2d6861199d7
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/27413
Reviewed-by: JACOB L. HARVEY <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Reviewed-by: Brian R. Silver <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
442d0f56e524bcced23e74325823a27ac0e381cf
|
FilePersistence/src/version_control/Commit.cpp
|
FilePersistence/src/version_control/Commit.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 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 "Commit.h"
namespace FilePersistence {
Signature::Signature()
{
dateTime_ = QDateTime::currentDateTimeUtc();
timeZone_ = QTimeZone{QTimeZone::systemTimeZoneId()};
}
CommitFile::CommitFile(){}
CommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)
: relativePath_{relativePath}, size_{size}, content_{std::move(content)}
{}
CommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)
: relativePath_{relativePath}, size_{size}, contentWithDeleter_{std::move(content)}
{}
const char* CommitFile::content() const
{
Q_ASSERT((content_ && !contentWithDeleter_) || (!content_ && contentWithDeleter_));
if (content_)
return content_.get();
else
return contentWithDeleter_.get();
}
Commit::Commit() {}
Commit::~Commit()
{
for (auto file : files_.values())
SAFE_DELETE(file);
}
void Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)
{
files_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});
}
void Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)
{
files_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});
}
bool Commit::getFileContent(QString fileName, const char*& content, int& contentSize, bool exactFileNameMatching) const
{
QHash<QString, CommitFile*>::const_iterator iter;
// name of file must match fileName exactly
if (exactFileNameMatching)
iter = files_.find(fileName);
// name of file must contain fileName
else
{
iter = files_.constBegin();
while (iter != files_.constEnd())
{
QFileInfo fileInfo{iter.key()};
if (!fileInfo.isDir() &&
((fileName.startsWith("{") && fileInfo.fileName().contains(fileName))
|| fileInfo.fileName() == fileName))
break;
iter++;
}
}
if (iter != files_.constEnd())
{
contentSize = iter.value()->size_;
content = iter.value()->content();
return true;
}
else
return false;
}
QStringList Commit::nodeLinesFromId(Model::NodeIdType id, bool findChildrenByParentId) const
{
auto idtext = id.toString();
QStringList matches;
for (auto file : files())
{
int indexOfId = 0;
auto content = QString::fromUtf8(file->content());
indexOfId = content.indexOf(idtext, indexOfId);
if (indexOfId != -1)
{
bool invalid = false;
auto start = indexOfId;
auto end = indexOfId;
// start is the first character of the line containing id
while (start >= 0 && content[start] != '\n')
{
// String is of the form {.*} {id}
if (!findChildrenByParentId)
if (content[start] == '}')
{
invalid = true;
break;
}
start--;
}
if (invalid == true) continue;
start++;
// end is the character after the line containing id
while (end <= content.size() && content[end] != '\n')
{
// String is of the form {id} {*.}
if (findChildrenByParentId)
if (content[end] == '{')
{
invalid = true;
break;
}
end++;
}
if (invalid == true) continue;
QString match = file->relativePath_ + ":" + content.mid(start, end-start);
matches << match;
// Find the next match
indexOfId = indexOfId + 1;
}
}
return matches;
}
}
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 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 "Commit.h"
namespace FilePersistence {
Signature::Signature()
{
dateTime_ = QDateTime::currentDateTimeUtc();
timeZone_ = QTimeZone{QTimeZone::systemTimeZoneId()};
}
CommitFile::CommitFile(){}
CommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)
: relativePath_{relativePath}, size_{size}, content_{std::move(content)}
{}
CommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)
: relativePath_{relativePath}, size_{size}, contentWithDeleter_{std::move(content)}
{}
const char* CommitFile::content() const
{
Q_ASSERT((content_ && !contentWithDeleter_) || (!content_ && contentWithDeleter_));
if (content_)
return content_.get();
else
return contentWithDeleter_.get();
}
Commit::Commit() {}
Commit::~Commit()
{
for (auto file : files_.values())
SAFE_DELETE(file);
}
void Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)
{
files_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});
}
void Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)
{
files_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});
}
bool Commit::getFileContent(QString fileName, const char*& content, int& contentSize, bool exactFileNameMatching) const
{
QHash<QString, CommitFile*>::const_iterator iter;
// name of file must match fileName exactly
if (exactFileNameMatching)
iter = files_.find(fileName);
// name of file must contain fileName
else
{
iter = files_.constBegin();
while (iter != files_.constEnd())
{
QFileInfo fileInfo{iter.key()};
if (!fileInfo.isDir() &&
((fileName.startsWith("{") && fileInfo.fileName().contains(fileName))
|| fileInfo.fileName() == fileName))
break;
iter++;
}
}
if (iter != files_.constEnd())
{
contentSize = iter.value()->size_;
content = iter.value()->content();
return true;
}
else
return false;
}
QStringList Commit::nodeLinesFromId(Model::NodeIdType id, bool findChildrenByParentId) const
{
auto idText = id.toString();
QStringList matches;
for (auto file : files())
{
int indexOfId = 0;
auto content = QString::fromUtf8(file->content());
indexOfId = content.indexOf(idText, indexOfId);
if (indexOfId != -1)
{
bool invalid = false;
auto start = indexOfId;
auto end = indexOfId;
// start is the first character of the line containing id
while (start >= 0 && content[start] != '\n')
{
// String is of the form {.*} {id}
if (!findChildrenByParentId)
if (content[start] == '}')
{
invalid = true;
break;
}
start--;
}
if (invalid) continue;
start++;
// end is the character after the line containing id
while (end <= content.size() && content[end] != '\n')
{
// String is of the form {id} {*.}
if (findChildrenByParentId)
if (content[end] == '{')
{
invalid = true;
break;
}
end++;
}
if (invalid) continue;
QString match = file->relativePath_ + ":" + content.mid(start, end-start);
matches << match;
// Find the next match
indexOfId = indexOfId + 1;
}
}
return matches;
}
}
|
Update Commit.cpp
|
Update Commit.cpp
|
C++
|
bsd-3-clause
|
mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,mgalbier/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,mgalbier/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,mgalbier/Envision,mgalbier/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,mgalbier/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision
|
c951d9523a4ef519011015154140a471921aee85
|
src/app/platforms/probe.cpp
|
src/app/platforms/probe.cpp
|
/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/
#include <QtCore/QCoreApplication>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <tools/platform.h>
#include "msvcprobe.h"
using namespace qbs;
static QString searchPath(const QString &path, const QString &me)
{
//TODO: use native seperator
foreach (const QString &ppath, path.split(":")) {
if (QFileInfo(ppath + "/" + me).exists()) {
return QDir::cleanPath(ppath + "/" + me);
}
}
return QString();
}
static QString qsystem(const QString &exe, const QStringList &args = QStringList())
{
QProcess p;
p.setProcessChannelMode(QProcess::MergedChannels);
p.start(exe, args);
p.waitForStarted();
p.waitForFinished();
return QString::fromLocal8Bit(p.readAll());
}
static int specific_probe(const QString &settingsPath,
QHash<QString, Platform::Ptr> &platforms,
QString cc,
bool printComfortingMessage = false)
{
QTextStream qstdout(stdout);
QString toolchainType;
if(cc.contains("clang"))
toolchainType = "clang";
else if (cc.contains("gcc"))
toolchainType = "gcc";
QString path = QString::fromLocal8Bit(qgetenv("PATH"));
QString cxx = QString::fromLocal8Bit(qgetenv("CXX"));
QString ld = QString::fromLocal8Bit(qgetenv("LD"));
QString cflags = QString::fromLocal8Bit(qgetenv("CFLAGS"));
QString cxxflags = QString::fromLocal8Bit(qgetenv("CXXFLAGS"));
QString ldflags = QString::fromLocal8Bit(qgetenv("LDFLAGS"));
QString cross = QString::fromLocal8Bit(qgetenv("CROSS_COMPILE"));
QString arch = QString::fromLocal8Bit(qgetenv("ARCH"));
QString pathToGcc;
QString architecture;
QString endianness;
QString name;
QString sysroot;
QString uname = qsystem("uname", QStringList() << "-m").simplified();
if (arch.isEmpty())
arch = uname;
#ifdef Q_OS_MAC
// HACK: "uname -m" reports "i386" but "gcc -dumpmachine" reports "i686" on MacOS.
if (arch == "i386")
arch = "i686";
#endif
if (ld.isEmpty())
ld = "ld";
if (cxx.isEmpty()) {
if (toolchainType == "gcc")
cxx = "g++";
else if(toolchainType == "clang")
cxx = "clang++";
}
if(!cross.isEmpty() && !cc.startsWith("/")) {
pathToGcc = searchPath(path, cross + cc);
if (QFileInfo(pathToGcc).exists()) {
if (!cc.contains(cross))
cc.prepend(cross);
if (!cxx.contains(cross))
cxx.prepend(cross);
if (!ld.contains(cross))
ld.prepend(cross);
}
}
if (cc.startsWith("/"))
pathToGcc = cc;
else
pathToGcc = searchPath(path, cc);
if (!QFileInfo(pathToGcc).exists()) {
fprintf(stderr, "Cannot find %s.", qPrintable(cc));
if (printComfortingMessage)
fprintf(stderr, " But that's not a problem. I've already found other platforms.\n");
else
fprintf(stderr, "\n");
return 1;
}
Platform::Ptr s;
foreach (Platform::Ptr p, platforms.values()) {
QString path = p->settings.value(Platform::internalKey() + "/completeccpath").toString();
if (path == pathToGcc) {
name = p->name;
s = p;
name = s->name;
break;
}
}
QString compilerTriplet = qsystem(pathToGcc, QStringList() << "-dumpmachine").simplified();
QStringList compilerTripletl = compilerTriplet.split('-');
if (compilerTripletl.count() < 2 ||
!(compilerTripletl.at(0).contains(QRegExp(".86")) ||
compilerTripletl.at(0).contains("arm") )
) {
qDebug("detected %s , but i don't understand it's architecture: %s",
qPrintable(pathToGcc), qPrintable(compilerTriplet));
return 12;
}
architecture = compilerTripletl.at(0);
if (architecture.contains("arm")) {
endianness = "big-endian";
} else {
endianness = "little-endian";
}
QStringList pathToGccL = pathToGcc.split('/');
QString compilerName = pathToGccL.takeLast().replace(cc, cxx);
if (cflags.contains("--sysroot")) {
QStringList flagl = cflags.split(' ');
bool nextitis = false;
foreach (const QString &flag, flagl) {
if (nextitis) {
sysroot = flag;
break;
}
if (flag == "--sysroot") {
nextitis = true;
}
}
}
qstdout << "==> " << (s?"reconfiguring " + name :"detected")
<< " " << pathToGcc << "\n"
<< " triplet: " << compilerTriplet << "\n"
<< " arch: " << architecture << "\n"
<< " bin: " << pathToGccL.join("/") << "\n"
<< " cc: " << cc << "\n"
;
if (!cxx.isEmpty())
qstdout << " cxx: " << cxx << "\n";
if (!ld.isEmpty())
qstdout << " ld: " << ld << "\n";
if (!sysroot.isEmpty())
qstdout << " sysroot: " << sysroot << "\n";
if (!cflags.isEmpty())
qstdout << " CFLAGS: " << cflags << "\n";
if (!cxxflags.isEmpty())
qstdout << " CXXFLAGS: " << cxxflags << "\n";
if (!ldflags.isEmpty())
qstdout << " CXXFLAGS: " << ldflags << "\n";
qstdout << flush;
if (!s) {
if (name.isEmpty())
name = toolchainType;
s = Platform::Ptr(new Platform(name, settingsPath + "/" + name));
}
// fixme should be cpp.toolchain
// also there is no toolchain:clang
s->settings.setValue("toolchain", "gcc");
s->settings.setValue(Platform::internalKey() + "/completeccpath", pathToGcc);
s->settings.setValue(Platform::internalKey() + "/target-triplet", compilerTriplet);
s->settings.setValue("architecture", architecture);
s->settings.setValue("endianness", endianness);
#if defined(Q_OS_MAC)
s->settings.setValue("targetOS", "mac");
#elif defined(Q_OS_LINUX)
s->settings.setValue("targetOS", "linux");
#else
s->settings.setValue("targetOS", "unknown"); //fixme
#endif
if (compilerName.contains('-')) {
QStringList nl = compilerName.split('-');
s->settings.setValue("cpp/compilerName", nl.takeLast());
s->settings.setValue("cpp/toolchainPrefix", nl.join("-") + '-');
} else {
s->settings.setValue("cpp/compilerName", compilerName);
}
s->settings.setValue("cpp/toolchainInstallPath", pathToGccL.join("/"));
if (!cross.isEmpty())
s->settings.setValue("environment/CROSS_COMPILE", cross);
if (!cflags.isEmpty())
s->settings.setValue("environment/CFLAGS", cflags);
if (!cxxflags.isEmpty())
s->settings.setValue("environment/CXXFLAGS", cxxflags);
if (!ldflags.isEmpty())
s->settings.setValue("environment/LDFLAGS", ldflags);
platforms.insert(s->name, s);
return 0;
}
#ifdef Q_OS_WIN
static void mingwProbe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms)
{
QString mingwPath;
QString mingwBinPath;
QString gccPath;
QByteArray envPath = qgetenv("PATH");
foreach (const QByteArray &dir, envPath.split(';')) {
QFileInfo fi(dir + "/gcc.exe");
if (fi.exists()) {
mingwPath = QFileInfo(dir + "/..").canonicalFilePath();
gccPath = fi.absoluteFilePath();
mingwBinPath = fi.absolutePath();
break;
}
}
if (gccPath.isEmpty())
return;
QProcess process;
process.start(gccPath, QStringList() << "-dumpmachine");
if (!process.waitForStarted()) {
fprintf(stderr, "Could not start \"gcc -dumpmachine\".\n");
return;
}
process.waitForFinished(-1);
QByteArray gccMachineName = process.readAll().trimmed();
if (gccMachineName != "mingw32" && gccMachineName != "mingw64") {
fprintf(stderr, "Detected gcc platform '%s' is not supported.\n", gccMachineName.data());
return;
}
Platform::Ptr platform = platforms.value(gccMachineName);
printf("Platform '%s' detected in '%s'.", gccMachineName.data(), qPrintable(QDir::toNativeSeparators(mingwPath)));
if (!platform) {
platform = Platform::Ptr(new Platform(gccMachineName, settingsPath + "/" + gccMachineName));
platforms.insert(platform->name, platform);
}
platform->settings.setValue("targetOS", "windows");
platform->settings.setValue("cpp/toolchainInstallPath", QDir::toNativeSeparators(mingwBinPath));
platform->settings.setValue("toolchain", "mingw");
}
#endif
int probe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms)
{
#ifdef Q_OS_WIN
msvcProbe(settingsPath, platforms);
mingwProbe(settingsPath, platforms);
#else
bool somethingFound = false;
if (specific_probe(settingsPath, platforms, "gcc") == 0)
somethingFound = true;
specific_probe(settingsPath, platforms, "clang", somethingFound);
#endif
if (platforms.isEmpty())
fprintf(stderr, "Could not detect any platforms.\n");
return 0;
}
|
/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/
#include <QtCore/QCoreApplication>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <tools/platform.h>
#include <tools/platformglobals.h>
#include "msvcprobe.h"
using namespace qbs;
static QString searchPath(const QString &path, const QString &me)
{
foreach (const QString &ppath, path.split(QLatin1Char(nativePathVariableSeparator))) {
const QString fullPath = ppath + QLatin1Char('/') + me;
if (QFileInfo(fullPath).exists())
return QDir::cleanPath(fullPath);
}
return QString();
}
static QString qsystem(const QString &exe, const QStringList &args = QStringList())
{
QProcess p;
p.setProcessChannelMode(QProcess::MergedChannels);
p.start(exe, args);
p.waitForStarted();
p.waitForFinished();
return QString::fromLocal8Bit(p.readAll());
}
static int specific_probe(const QString &settingsPath,
QHash<QString, Platform::Ptr> &platforms,
QString cc,
bool printComfortingMessage = false)
{
QTextStream qstdout(stdout);
QString toolchainType;
if(cc.contains("clang"))
toolchainType = "clang";
else if (cc.contains("gcc"))
toolchainType = "gcc";
QString path = QString::fromLocal8Bit(qgetenv("PATH"));
QString cxx = QString::fromLocal8Bit(qgetenv("CXX"));
QString ld = QString::fromLocal8Bit(qgetenv("LD"));
QString cflags = QString::fromLocal8Bit(qgetenv("CFLAGS"));
QString cxxflags = QString::fromLocal8Bit(qgetenv("CXXFLAGS"));
QString ldflags = QString::fromLocal8Bit(qgetenv("LDFLAGS"));
QString cross = QString::fromLocal8Bit(qgetenv("CROSS_COMPILE"));
QString arch = QString::fromLocal8Bit(qgetenv("ARCH"));
QString pathToGcc;
QString architecture;
QString endianness;
QString name;
QString sysroot;
QString uname = qsystem("uname", QStringList() << "-m").simplified();
if (arch.isEmpty())
arch = uname;
#ifdef Q_OS_MAC
// HACK: "uname -m" reports "i386" but "gcc -dumpmachine" reports "i686" on MacOS.
if (arch == "i386")
arch = "i686";
#endif
if (ld.isEmpty())
ld = "ld";
if (cxx.isEmpty()) {
if (toolchainType == "gcc")
cxx = "g++";
else if(toolchainType == "clang")
cxx = "clang++";
}
if(!cross.isEmpty() && !cc.startsWith("/")) {
pathToGcc = searchPath(path, cross + cc);
if (QFileInfo(pathToGcc).exists()) {
if (!cc.contains(cross))
cc.prepend(cross);
if (!cxx.contains(cross))
cxx.prepend(cross);
if (!ld.contains(cross))
ld.prepend(cross);
}
}
if (cc.startsWith("/"))
pathToGcc = cc;
else
pathToGcc = searchPath(path, cc);
if (!QFileInfo(pathToGcc).exists()) {
fprintf(stderr, "Cannot find %s.", qPrintable(cc));
if (printComfortingMessage)
fprintf(stderr, " But that's not a problem. I've already found other platforms.\n");
else
fprintf(stderr, "\n");
return 1;
}
Platform::Ptr s;
foreach (Platform::Ptr p, platforms.values()) {
QString path = p->settings.value(Platform::internalKey() + "/completeccpath").toString();
if (path == pathToGcc) {
name = p->name;
s = p;
name = s->name;
break;
}
}
QString compilerTriplet = qsystem(pathToGcc, QStringList() << "-dumpmachine").simplified();
QStringList compilerTripletl = compilerTriplet.split('-');
if (compilerTripletl.count() < 2 ||
!(compilerTripletl.at(0).contains(QRegExp(".86")) ||
compilerTripletl.at(0).contains("arm") )
) {
qDebug("detected %s , but i don't understand it's architecture: %s",
qPrintable(pathToGcc), qPrintable(compilerTriplet));
return 12;
}
architecture = compilerTripletl.at(0);
if (architecture.contains("arm")) {
endianness = "big-endian";
} else {
endianness = "little-endian";
}
QStringList pathToGccL = pathToGcc.split('/');
QString compilerName = pathToGccL.takeLast().replace(cc, cxx);
if (cflags.contains("--sysroot")) {
QStringList flagl = cflags.split(' ');
bool nextitis = false;
foreach (const QString &flag, flagl) {
if (nextitis) {
sysroot = flag;
break;
}
if (flag == "--sysroot") {
nextitis = true;
}
}
}
qstdout << "==> " << (s?"reconfiguring " + name :"detected")
<< " " << pathToGcc << "\n"
<< " triplet: " << compilerTriplet << "\n"
<< " arch: " << architecture << "\n"
<< " bin: " << pathToGccL.join("/") << "\n"
<< " cc: " << cc << "\n"
;
if (!cxx.isEmpty())
qstdout << " cxx: " << cxx << "\n";
if (!ld.isEmpty())
qstdout << " ld: " << ld << "\n";
if (!sysroot.isEmpty())
qstdout << " sysroot: " << sysroot << "\n";
if (!cflags.isEmpty())
qstdout << " CFLAGS: " << cflags << "\n";
if (!cxxflags.isEmpty())
qstdout << " CXXFLAGS: " << cxxflags << "\n";
if (!ldflags.isEmpty())
qstdout << " CXXFLAGS: " << ldflags << "\n";
qstdout << flush;
if (!s) {
if (name.isEmpty())
name = toolchainType;
s = Platform::Ptr(new Platform(name, settingsPath + "/" + name));
}
// fixme should be cpp.toolchain
// also there is no toolchain:clang
s->settings.setValue("toolchain", "gcc");
s->settings.setValue(Platform::internalKey() + "/completeccpath", pathToGcc);
s->settings.setValue(Platform::internalKey() + "/target-triplet", compilerTriplet);
s->settings.setValue("architecture", architecture);
s->settings.setValue("endianness", endianness);
#if defined(Q_OS_MAC)
s->settings.setValue("targetOS", "mac");
#elif defined(Q_OS_LINUX)
s->settings.setValue("targetOS", "linux");
#else
s->settings.setValue("targetOS", "unknown"); //fixme
#endif
if (compilerName.contains('-')) {
QStringList nl = compilerName.split('-');
s->settings.setValue("cpp/compilerName", nl.takeLast());
s->settings.setValue("cpp/toolchainPrefix", nl.join("-") + '-');
} else {
s->settings.setValue("cpp/compilerName", compilerName);
}
s->settings.setValue("cpp/toolchainInstallPath", pathToGccL.join("/"));
if (!cross.isEmpty())
s->settings.setValue("environment/CROSS_COMPILE", cross);
if (!cflags.isEmpty())
s->settings.setValue("environment/CFLAGS", cflags);
if (!cxxflags.isEmpty())
s->settings.setValue("environment/CXXFLAGS", cxxflags);
if (!ldflags.isEmpty())
s->settings.setValue("environment/LDFLAGS", ldflags);
platforms.insert(s->name, s);
return 0;
}
#ifdef Q_OS_WIN
static void mingwProbe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms)
{
QString mingwPath;
QString mingwBinPath;
QString gccPath;
QByteArray envPath = qgetenv("PATH");
foreach (const QByteArray &dir, envPath.split(';')) {
QFileInfo fi(dir + "/gcc.exe");
if (fi.exists()) {
mingwPath = QFileInfo(dir + "/..").canonicalFilePath();
gccPath = fi.absoluteFilePath();
mingwBinPath = fi.absolutePath();
break;
}
}
if (gccPath.isEmpty())
return;
QProcess process;
process.start(gccPath, QStringList() << "-dumpmachine");
if (!process.waitForStarted()) {
fprintf(stderr, "Could not start \"gcc -dumpmachine\".\n");
return;
}
process.waitForFinished(-1);
QByteArray gccMachineName = process.readAll().trimmed();
if (gccMachineName != "mingw32" && gccMachineName != "mingw64") {
fprintf(stderr, "Detected gcc platform '%s' is not supported.\n", gccMachineName.data());
return;
}
Platform::Ptr platform = platforms.value(gccMachineName);
printf("Platform '%s' detected in '%s'.", gccMachineName.data(), qPrintable(QDir::toNativeSeparators(mingwPath)));
if (!platform) {
platform = Platform::Ptr(new Platform(gccMachineName, settingsPath + "/" + gccMachineName));
platforms.insert(platform->name, platform);
}
platform->settings.setValue("targetOS", "windows");
platform->settings.setValue("cpp/toolchainInstallPath", QDir::toNativeSeparators(mingwBinPath));
platform->settings.setValue("toolchain", "mingw");
}
#endif
int probe(const QString &settingsPath, QHash<QString, Platform::Ptr> &platforms)
{
#ifdef Q_OS_WIN
msvcProbe(settingsPath, platforms);
mingwProbe(settingsPath, platforms);
#else
bool somethingFound = false;
if (specific_probe(settingsPath, platforms, "gcc") == 0)
somethingFound = true;
specific_probe(settingsPath, platforms, "clang", somethingFound);
#endif
if (platforms.isEmpty())
fprintf(stderr, "Could not detect any platforms.\n");
return 0;
}
|
Use native environment variable separator.
|
Use native environment variable separator.
Change-Id: I710e428031fdd624dae9a1be1ff09d63a2218429
Reviewed-by: Joerg Bornemann <[email protected]>
|
C++
|
lgpl-2.1
|
qtproject/qt-labs-qbs,gatzka/qt-labs-qbs,qt-labs/qbs,gatzka/qt-labs-qbs,qt-labs/qbs,qtproject/qt-labs-qbs,qt-labs/qbs,qt-labs/qbs,qt-labs/qbs,Distrotech/qbs,gatzka/qt-labs-qbs,villytiger/qbs,qtproject/qt-labs-qbs,Distrotech/qbs,gatzka/qt-labs-qbs,gatzka/qt-labs-qbs,Distrotech/qbs,Distrotech/qbs,villytiger/qbs,Distrotech/qbs,qtproject/qt-labs-qbs,villytiger/qbs,qtproject/qt-labs-qbs,Distrotech/qbs,qtproject/qt-labs-qbs,gatzka/qt-labs-qbs,qt-labs/qbs,qt-labs/qbs,Distrotech/qbs,villytiger/qbs,villytiger/qbs,villytiger/qbs,qtproject/qt-labs-qbs,gatzka/qt-labs-qbs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.