text string | size int64 | token_count int64 |
|---|---|---|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
********************************************************************/
#include <platform_ndcs.h>
#include "errno.h"
#include "Transport.h"
#include "Listener_srvr.h"
#include "TCPIPSystemSrvr.h"
#include "FileSystemSrvr.h"
#include "Global.h"
#include "SrvrConnect.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <linux/unistd.h>
extern SRVR_GLOBAL_Def *srvrGlobal;
extern void SyncPublicationThread();
void CNSKListenerSrvr::closeTCPIPSession(int fnum)
{
shutdown(fnum, SHUT_RDWR);
close(fnum);
FD_CLR(fnum, &read_fds_);
FD_CLR(fnum, &error_fds_);
// if (fnum == max_read_fd_) max_read_fd_--;
// max_read_fd_ = m_nListenSocketFnum;
max_read_fd_ = pipefd[0]; // m_nListenSocketFnum;
}
bool CNSKListenerSrvr::ListenToPort(int port)
{
char tmp[500];
int error;
struct sockaddr_in6 *sin6 = NULL;
struct sockaddr_in *sin4 = NULL;
max_read_fd_ = 0;
if (m_nListenSocketFnum < 1)
{
sprintf(tmp,"ListenToPort[%d][%d]", port, m_nListenSocketFnum );
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, tmp, O_INIT_PROCESS, F_SOCKET, 0, 0);
if (m_bIPv4 == false)
{
//LCOV_EXCL_START
if ((m_nListenSocketFnum = socket(AF_INET6, SOCK_STREAM, 0)) < 0 )
{
m_bIPv4 = true;
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
}
//LCOV_EXCL_STOP
}
else
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
if (m_nListenSocketFnum < 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_SOCKET, errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
if(strncmp(m_TcpProcessName,"$ZTC0",5) != 0)
{
//LCOV_EXCL_START
/*
* bind to a specific interface (m_TcpProcessName is initialized by default to $ztc0)
*/
struct ifaddrs *ifa = NULL, *ifp = NULL;
bool bFoundInterface = false;
if (getifaddrs (&ifp) < 0)
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, "ListenToPort - getifaddrs", O_INIT_PROCESS, F_SOCKET, errno, 0);
goto bailout;
}
for (ifa = ifp; ifa != NULL; ifa = ifa->ifa_next)
{
if(! ifa->ifa_addr)
continue;
if( (m_bIPv4 == true && ifa->ifa_addr->sa_family != AF_INET) ||
(m_bIPv4 == false && ifa->ifa_addr->sa_family != AF_INET6) ||
(strcmp(ifa->ifa_name,m_TcpProcessName) != 0) )
continue;
bFoundInterface = true;
if(m_bIPv4 == false)
{
sin6 = (struct sockaddr_in6*)ifa->ifa_addr;
memcpy(&m_ListenSocketAddr6,sin6,sizeof(m_ListenSocketAddr6));
m_ListenSocketAddr6.sin6_port = htons((uint16_t) port);
break;
}
else
{
sin4 = (struct sockaddr_in*)ifa->ifa_addr;
memcpy(&m_ListenSocketAddr,sin4,sizeof(m_ListenSocketAddr));
m_ListenSocketAddr.sin_port = htons((in_port_t) port);
break;
}
} // for all interfaces
freeifaddrs(ifp);
if(!bFoundInterface)
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, "ListenToPort - no matching interface", O_INIT_PROCESS, F_SOCKET, errno, 0);
goto bailout;
}
//LCOV_EXCL_STOP
}
else
{
/*
* bind to all available interfaces
*/
if (m_bIPv4 == false)
{
//LCOV_EXCL_START
bzero((char*)&m_ListenSocketAddr6,sizeof(m_ListenSocketAddr6));
m_ListenSocketAddr6.sin6_family = AF_INET6;
m_ListenSocketAddr6.sin6_addr = in6addr_any;
m_ListenSocketAddr6.sin6_port = htons((uint16_t) port);
//LCOV_EXCL_STOP
}
else
{
bzero((char*)&m_ListenSocketAddr,sizeof(m_ListenSocketAddr));
m_ListenSocketAddr.sin_family = AF_INET;
m_ListenSocketAddr.sin_addr.s_addr = INADDR_ANY;
m_ListenSocketAddr.sin_port = htons((in_port_t) port);
}
}
int optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_REUSEADDR, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_REUSEADDR);
goto bailout;
//LCOV_EXCL_STOP
}
if (m_bIPv4 == false)
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr6, (int)sizeof(m_ListenSocketAddr6));
else
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr, (int)sizeof(m_ListenSocketAddr));
if (error < 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_BIND, errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_KEEPALIVE, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"ListenToPort", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_KEEPALIVE);
goto bailout;
//LCOV_EXCL_STOP
}
}
error = listen(m_nListenSocketFnum, 100);
FD_ZERO(&read_fds_);
FD_ZERO(&error_fds_);
if(error >= 0)
{
FD_SET(m_nListenSocketFnum,&read_fds_);
FD_SET(m_nListenSocketFnum,&error_fds_);
// Keep track of highest socket file descriptor, for use in "select"
if (m_nListenSocketFnum > max_read_fd_) max_read_fd_ = m_nListenSocketFnum;
}
else
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_LISTENER, "ListenToPort", O_INIT_PROCESS, F_ACCEPT, errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
// If tracing is enabled, display trace info indicating new "listen"
LISTEN_ON_SOCKET((short)m_nListenSocketFnum);
return true;
bailout:
if (m_nListenSocketFnum > 0)
GTransport.m_TCPIPSystemSrvr_list->del_node(m_nListenSocketFnum);
// closeTCPIPSession(m_nListenSocketFnum);
m_nListenSocketFnum = -2;
sprintf(tmp,"bailout ListenToPort[%d][%d]", port, m_nListenSocketFnum );
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_, tmp, O_INIT_PROCESS, F_SOCKET, 0, 0);
return false;
}
void* CNSKListenerSrvr::OpenTCPIPSession()
{
CTCPIPSystemSrvr* pnode = NULL;
int error;
int nSocketFnum = -2;
if (m_bIPv4 == false)
{
//LCOV_EXCL_START
m_nAcceptFromSocketAddrLen = sizeof(m_AcceptFromSocketAddr6);
nSocketFnum = accept(m_nListenSocketFnum, (sockaddr*)&m_AcceptFromSocketAddr6, (socklen_t *)&m_nAcceptFromSocketAddrLen);
//LCOV_EXCL_STOP
}
else
{
m_nAcceptFromSocketAddrLen = sizeof(m_AcceptFromSocketAddr);
nSocketFnum = accept(m_nListenSocketFnum, (sockaddr*)&m_AcceptFromSocketAddr, (socklen_t *)&m_nAcceptFromSocketAddrLen);
}
if(nSocketFnum == -1)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"OpenTCPIPSession", O_INIT_PROCESS, F_ACCEPT,
errno, 0);
goto bailout;
//LCOV_EXCL_STOP
}
TCP_SetKeepalive(nSocketFnum,
srvrGlobal->clientKeepaliveStatus,
srvrGlobal->clientKeepaliveIdletime,
srvrGlobal->clientKeepaliveIntervaltime,
srvrGlobal->clientKeepaliveRetrycount);
pnode = GTransport.m_TCPIPSystemSrvr_list->ins_node(nSocketFnum);
if (pnode == NULL)
{
//LCOV_EXCL_START
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"OpenTCPIPSession", O_INIT_PROCESS, F_INS_NODE,
SRVR_ERR_MEMORY_ALLOCATE, 0);
goto bailout;
//LCOV_EXCL_STOP
}
// clear/zero the set
FD_ZERO(&read_fds_);
FD_ZERO(&error_fds_);
// (re)set the listening socket
FD_SET(m_nListenSocketFnum,&read_fds_);
FD_SET(m_nListenSocketFnum,&error_fds_);
// (re) set the dummy pipe-read-fd
FD_SET(pipefd[0],&read_fds_);
FD_SET(pipefd[0],&error_fds_);
//set the connected socket
FD_SET(pnode->m_nSocketFnum,&read_fds_);
FD_SET(pnode->m_nSocketFnum,&error_fds_);
if (pnode->m_nSocketFnum > max_read_fd_)
max_read_fd_ = pnode->m_nSocketFnum;
m_nSocketFnum = (short) nSocketFnum;
return pnode;
bailout:
if (pnode != NULL)
GTransport.m_TCPIPSystemSrvr_list->del_node(nSocketFnum);
SRVR::BreakDialogue(NULL);
return NULL;
}
void * CNSKListenerSrvr::tcpip_listener(void *arg)
{
// Parameter is the CNSKListenerSrvr object
CNSKListenerSrvr *listener = (CNSKListenerSrvr *) arg;
int numReadyFds;
int handledFds;
ssize_t countRead;
CTCPIPSystemSrvr* pnode=NULL;
fd_set temp_read_fds, temp_error_fds;
struct timeval timeout;
struct timeval *pTimeout;
msg_enable_open_cleanup();
file_enable_open_cleanup();
//create a the dummy pipe
int rc = pipe(listener->pipefd);
if (rc < 0)
{
listener->TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_PIPE, F_INIT_PIPE,SRVR_ERR_UNKNOWN_REQUEST,0);
listener->TCP_TRACE_OUTPUT_R0();
}
FD_SET(listener->pipefd[0],&listener->read_fds_);
FD_SET(listener->pipefd[0],&listener->error_fds_);
if (listener->pipefd[0] > listener->max_read_fd_)
listener->max_read_fd_ = listener->pipefd[0];
// Persistently wait for input on sockets and then act on it.
while(listener->m_bTCPThreadKeepRunning)
{
// Wait for ready-to-read on any of the tcpip ports
memcpy(&temp_read_fds, &listener->read_fds_, sizeof(temp_read_fds));
memcpy(&temp_error_fds, &listener->error_fds_, sizeof(temp_error_fds));
long connIdleTimeout = SRVR::getConnIdleTimeout();
long srvrIdleTimeout = SRVR::getSrvrIdleTimeout();
bool connIdleTimer = false;
bool srvrIdleTimer = false;
if (srvrGlobal->srvrState == SRVR_CONNECTED)
{
if (connIdleTimeout != INFINITE_CONN_IDLE_TIMEOUT)
{
timeout.tv_sec = connIdleTimeout;
timeout.tv_usec = 0;
connIdleTimer = true;
pTimeout = &timeout;
}
else
{
timeout.tv_sec = 0;
timeout.tv_usec = 0;
pTimeout = NULL;
}
}
else
{
if (srvrIdleTimeout != INFINITE_SRVR_IDLE_TIMEOUT)
{
timeout.tv_sec = srvrIdleTimeout;
timeout.tv_usec = 0;
srvrIdleTimer = true;
pTimeout = &timeout;
}
else
{
timeout.tv_sec = 0;
timeout.tv_usec = 0;
pTimeout = NULL;
}
}
numReadyFds = select(listener->max_read_fd_+1, &temp_read_fds, NULL,&temp_error_fds, pTimeout);
srvrGlobal->mutex->lock();
if (numReadyFds == -1)
{
if (errno == EINTR)
{
srvrGlobal->mutex->unlock();
continue;
}
else
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_SELECT,errno,numReadyFds);
abort();
}
}
if (numReadyFds == 0) //Timeout expired
{
if (connIdleTimer)
SRVR::BreakDialogue(NULL);
else if (srvrIdleTimer)
SRVR::srvrIdleTimerExpired(NULL);
else
{
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_SELECT,errno,numReadyFds);
abort();
}
}
else
{
// Handle all ready-to-read file descriptors
handledFds = 0;
if(FD_ISSET(listener->pipefd[0], &temp_read_fds))
{
//dummy write, exit the loop
listener->m_bTCPThreadKeepRunning = false;
srvrGlobal->mutex->unlock();
break;
}
else if (FD_ISSET(listener->m_nListenSocketFnum,&temp_read_fds))
{
// Initiate a new client session
listener->OpenTCPIPSession();
listener->TRACE_INPUT((short)listener->m_nListenSocketFnum, 0, 0, 0);
handledFds++;
}
else if ((pnode=GTransport.m_TCPIPSystemSrvr_list->m_current_node) != NULL && FD_ISSET(pnode->m_nSocketFnum,&temp_read_fds))
{
short retries = 0;
do
{
countRead = recv(pnode->m_nSocketFnum,
pnode->m_IObuffer,
MAX_TCP_BUFFER_LENGTH, 0);
} while ((countRead < 0) && (errno == EINTR) && (retries++ < 3));
if (countRead <= 0)
{
GTransport.m_TCPIPSystemSrvr_list->del_node(pnode->m_nSocketFnum);
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_SELECT,errno, pnode->m_nSocketFnum);
SRVR::BreakDialogue(NULL);
}
else
{
pnode->m_rlength = countRead;
if (listener->CheckTCPIPRequest(pnode) == NULL)
{
SRVR::BreakDialogue(NULL);
}
}
handledFds++;
}
else
{
listener->TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_FD_ISSET,SRVR_ERR_UNKNOWN_REQUEST, -2);
listener->TCP_TRACE_OUTPUT_R0();
handledFds++;
}
if(handledFds != numReadyFds)
{
listener->TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER,"tcpip_listener", O_SELECT, F_FD_ISSET,SRVR_ERR_UNKNOWN_REQUEST,0);
listener->TCP_TRACE_OUTPUT_R0();
}
}
srvrGlobal->mutex->unlock();
} //while(listener->m_bTCPThreadKeepRunning)
return NULL;
}
int CNSKListenerSrvr::runProgram(char* TcpProcessName, long port, int TransportTrace)
{
short fnum,error;
_cc_status cc;
short timeout;
unsigned short countRead;
SB_Tag_Type tag;
sprintf(m_TcpProcessName,"%s",TcpProcessName);
m_port = port;
INITIALIZE_TRACE(TransportTrace);
if ((error = FILE_OPEN_("$RECEIVE",8,&m_ReceiveFnum, 0, 0, 1, 4000)) != 0)
{
SET_ERROR((long)0, NSK, FILE_SYSTEM, UNKNOWN_API, E_SERVER,
"runProgram", O_INIT_PROCESS, F_FILE_OPEN_, error, 0);
return error;
}
if (ListenToPort(port) == false)
return SRVR_ERR_LISTENER_ERROR1;
READUPDATEX(m_ReceiveFnum, m_RequestBuf, MAX_BUFFER_LENGTH );
// Register with association server
SRVR::RegisterSrvr(srvrGlobal->IpAddress, srvrGlobal->HostName);
// Start tcpip listener thread
tcpip_tid = tcpip_listener_thr.create("TCPIP_listener",
CNSKListenerSrvr::tcpip_listener, this);
// Persistently wait for input on $RECEIVE and then act on it.
while(m_bKeepRunning)
{
RESET_ERRORS((long)0);
timeout = -1;
fnum = m_ReceiveFnum;
cc = AWAITIOX(&fnum, OMITREF, &countRead, &tag, timeout);
if (_status_lt(cc)) // some error or XCANCEL
{
//LCOV_EXCL_START
error=0;
XFILE_GETINFO_(fnum, &error);
if (error == 26) // XCANCEL was called
{
//join the tcpip thread
if(tcpip_tid != 0)
tcpip_listener_thr.join(tcpip_tid,NULL);
m_bKeepRunning = false;
break;
}
//LCOV_EXCL_STOP
}
TRACE_INPUT(fnum,countRead,tag,cc);
if (fnum == m_ReceiveFnum)
{
ADD_ONE_TO_HANDLE(&m_call_id);
CheckReceiveMessage(cc, countRead, &m_call_id);
READUPDATEX(m_ReceiveFnum, m_RequestBuf, MAX_BUFFER_LENGTH );
FS_TRACE_OUTPUT(cc);
}
else
{
//LCOV_EXCL_START
TRACE_UNKNOWN_INPUT();
SET_ERROR((long)0, NSK, TCPIP, UNKNOWN_API, E_SERVER, "runProgram",
O_DO_WRITE_READ, F_FILE_COMPLETE, SRVR_ERR_UNKNOWN_REQUEST,
fnum);
//LCOV_EXCL_STOP
}
}
return 0;
}
void CNSKListenerSrvr::SYSTEM_SNAMP(FILE* fp)
{
short info_ele;
char obuffer[1000];
char* pbuffer = obuffer;
int ip;
ip=sprintf(pbuffer,"\t<----SYSTEM SNAP---->\n");
pbuffer +=ip;
ip=sprintf(pbuffer,"\t\t%15.15s\t\t=\t\t%s(%d)\n","srvrState",frmt_serverstate(srvrGlobal->srvrState),srvrGlobal->srvrState);
pbuffer +=ip;
pbuffer = GTransport.m_FSystemSrvr_list->enum_nodes(pbuffer,fp);
pbuffer = GTransport.m_TCPIPSystemSrvr_list->enum_nodes(pbuffer,fp);
fwrite(obuffer, strlen(obuffer),1,fp);
fwrite("\r\n",2,1,fp);
fflush(fp);
}
void CNSKListenerSrvr::terminateThreads(int status)
{
// m_bKeepRunning = false; // break out of $RECEIVE and listen loop
char dummyWriteBuffer[100];
// Calling sync of repository thread here instead of exitServerProcess() since
// this also takes care of the case when the process is stopped via a system message.
SyncPublicationThread();
if(syscall(__NR_gettid) == srvrGlobal->receiveThrId)
{
// we're in the $recv thread
// If the tcp/ip thread is processing a request, the mutex will be locked
// in which case, we'll wait for that request to complete. Once the request
// is complete, the listen loop will exit out because m_bKeepRunning is false
// If we're able to acquire the lock rightaway, it means the tcp/ip thread is
// waiting on a select - we can then safely terminate the thread
/*
if(tcpip_tid != 0 && srvrGlobal->mutex->trylock() == 0)
tcpip_listener_thr.cancel(tcpip_tid);
*/
// Dummy write
if((tcpip_tid != 0) && (pipefd[1] != 0))
{
strcpy(dummyWriteBuffer, "bye-bye tcp/ip thread!");
write(pipefd[1], dummyWriteBuffer, strlen(dummyWriteBuffer));
}
//Wait tcpip thread to exit
if(tcpip_tid != 0)
tcpip_listener_thr.join(tcpip_tid,NULL);
}
else
{
// we're in the tcp/ip thread - we can just cancel the outstanding
// readupdate posted on $receive and exit the thread
int cc = XCANCEL(m_ReceiveFnum);
tcpip_listener_thr.exit(NULL);
}
}
bool CNSKListenerSrvr::verifyPortAvailable(const char * idForPort, int port)
{
char tmp[500];
int error;
struct sockaddr_in6 *sin6 = NULL;
struct sockaddr_in *sin4 = NULL;
max_read_fd_ = 0;
if (m_bIPv4 == false)
{
if ((m_nListenSocketFnum = socket(AF_INET6, SOCK_STREAM, 0)) < 0 )
{
m_bIPv4 = true;
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
}
}
else
m_nListenSocketFnum = socket(AF_INET, SOCK_STREAM, 0);
if (m_nListenSocketFnum < 0)
{
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"verifyPortAvailable", O_INIT_PROCESS, F_SOCKET, errno, 0);
return false;
}
/*
* bind to all available interfaces
*/
if (m_bIPv4 == false)
{
bzero((char*)&m_ListenSocketAddr6,sizeof(m_ListenSocketAddr6));
m_ListenSocketAddr6.sin6_family = AF_INET6;
m_ListenSocketAddr6.sin6_addr = in6addr_any;
m_ListenSocketAddr6.sin6_port = htons((uint16_t) port);
}
else
{
bzero((char*)&m_ListenSocketAddr,sizeof(m_ListenSocketAddr));
m_ListenSocketAddr.sin_family = AF_INET;
m_ListenSocketAddr.sin_addr.s_addr = INADDR_ANY;
m_ListenSocketAddr.sin_port = htons((in_port_t) port);
}
int optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_REUSEADDR, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"verifyPortAvailable", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_REUSEADDR);
return false;
}
if (m_bIPv4 == false)
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr6, (int)sizeof(m_ListenSocketAddr6));
else
error = bind(m_nListenSocketFnum, (struct sockaddr *)&m_ListenSocketAddr, (int)sizeof(m_ListenSocketAddr));
if (error < 0)
{
sprintf(tmp,"verifyPortAvailable:[%d]",port);
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
tmp, O_INIT_PROCESS, F_BIND, errno, 0);
return false;
}
optVal = 1;
error = setsockopt(m_nListenSocketFnum, SOL_SOCKET, SO_KEEPALIVE, (char*)&optVal, sizeof(optVal));
if (error != 0)
{
SET_WARNING((long)0, NSK, TCPIP, UNKNOWN_API, errorType_,
"verifyPortAvailable", O_INIT_PROCESS, F_SETSOCOPT, errno,
SO_KEEPALIVE);
return false;
}
return true;
}
| 21,105 | 8,540 |
/*
Copyright (c) 2005-2020, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford 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.
*/
#ifndef MONODOMAINPURKINJESOLVER_HPP_
#define MONODOMAINPURKINJESOLVER_HPP_
#include "AbstractDynamicLinearPdeSolver.hpp"
#include "MassMatrixAssembler.hpp"
#include "NaturalNeumannSurfaceTermAssembler.hpp"
#include "MonodomainCorrectionTermAssembler.hpp"
#include "MonodomainTissue.hpp"
#include "MonodomainPurkinjeVolumeAssembler.hpp"
#include "MonodomainPurkinjeCableAssembler.hpp"
/**
* Solver class for Monodomain problems on tissues containing Purkinje fibres.
*
* In such problems, there are a subset of nodes of the mesh which are labelled as
* Purkinje nodes (and 1D elements connecting them). There are two variables to be
* computed, the (normal, myocardium) transmembrane voltage (V), defined at ALL nodes
* of the mesh, and the Purkinje voltage (Vp), defined at the purkinje nodes. Hence, the
* Purkinje nodes have two variables defined on them.
*
* For parallelisation/implementation reasons, we choose to have two variables to be
* defined at ALL nodes, introducing dummy variables Vp for non-Purkinje nodes. We set
* Vp = 0 at non-Purkinje nodes. Hence we solve for {V,Vp} at every node in the mesh,
* and PROBLEM_DIM=2. The linear system to be assembled, written as usual in block form
* but actually in striped form in the code, is:
*
* [ A1 0 ][V ] = [b1]
* [ 0 A2 ][Vp] = [b2]
*
* where each block is of size num_nodes.
*
* A1 and b1 are obtained by integrating over 3D myocardium elements and are therefore
* exactly the same as in a normal monodomain problem.
*
* Suppose the nodes are ordered such that all the Purkinje nodes are last. Then the matrix A2
* needs to be of the form
* A2 = [I 0 ]
* [0 Ap]
* where the first block is of size num_non_purkinje_nodes, and the second is of size num_purkinje_nodes.
* Ap is obtained by assembling over 1D purkinje elements. After assembly we add in the identity block,
* which is just represents the equations Vp=0 for the dummy variables (non-purkinje nodes). Finally,
* we similarly have
* b2 = [0 ]
* [bp]
* where bp involves a loop over 1D purkinje elements.
*
* This class implements the above, and is based on (but doesn't inherit from, as the PROBLEM_DIMENSION
* is different) MonodomainSolver.
*
*
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class MonodomainPurkinjeSolver
: public AbstractDynamicLinearPdeSolver<ELEMENT_DIM,SPACE_DIM,2>
{
private:
/** Saved pointer to the mesh in this class, as the pointer saved in the
* parent class (AbstractDynamicLinearPdeSolver::mpMesh) is not declared to
* be a pointer to a mixed mesh
*/
MixedDimensionMesh<ELEMENT_DIM,SPACE_DIM>* mpMixedMesh;
/** Monodomain tissue class (collection of cells, and conductivities) */
MonodomainTissue<ELEMENT_DIM,SPACE_DIM>* mpMonodomainTissue;
/** Boundary conditions */
BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,2>* mpBoundaryConditions;
/**
* The volume assembler, used to set up volume integral parts of the
* LHS matrix
*/
MonodomainPurkinjeVolumeAssembler<ELEMENT_DIM,SPACE_DIM>* mpVolumeAssembler;
/**
* The cable element assembler, used to set up cable integral parts of the
* LHS matrix
*/
MonodomainPurkinjeCableAssembler<ELEMENT_DIM,SPACE_DIM>* mpCableAssembler;
/** Assembler for surface integrals coming from any non-zero Neumann boundary conditions */
NaturalNeumannSurfaceTermAssembler<ELEMENT_DIM,SPACE_DIM,2>* mpNeumannSurfaceTermsAssembler;
// SVI and Purkinje not yet implemented:
// MonodomainCorrectionTermAssembler<ELEMENT_DIM,SPACE_DIM>* mpMonodomainCorrectionTermAssembler;
/** The mass matrix, used to computing the RHS vector */
Mat mMassMatrix;
/** The vector multiplied by the mass matrix. Ie, if the linear system to
* be solved is Ax=b (excluding surface integrals), this vector is z where b=Mz.
*/
Vec mVecForConstructingRhs;
/**
* Implementation of SetupLinearSystem() which uses the assembler to compute the
* LHS matrix, but sets up the RHS vector using the mass-matrix (constructed
* using a separate assembler) multiplied by a vector
*
* @param currentSolution Solution at current time
* @param computeMatrix Whether to compute the matrix of the linear system
*/
void SetupLinearSystem(Vec currentSolution, bool computeMatrix);
/**
* For the block in the LHS matrix corresponding to the Purkinje voltage at myocardium nodes:
* this block is zero after all elements are assembled so, so we set it to be the
* identity block. This is done by just checking which rows of the matrix has zero
* diagonal values.
*/
void SetIdentityBlockToLhsMatrix();
public:
/**
* Overloaded PrepareForSetupLinearSystem() methods which
* gets the cell models to solve themselves
*
* @param currentSolution solution at current time
*/
void PrepareForSetupLinearSystem(Vec currentSolution);
/**
* Overloaded InitialiseForSolve
*
* @param initialSolution initial solution
*/
virtual void InitialiseForSolve(Vec initialSolution);
/**
* Constructor
*
* @param pMesh pointer to the mesh
* @param pTissue pointer to the tissue
* @param pBoundaryConditions pointer to the boundary conditions
*/
MonodomainPurkinjeSolver(MixedDimensionMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,
MonodomainTissue<ELEMENT_DIM,SPACE_DIM>* pTissue,
BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,2>* pBoundaryConditions);
/**
* Destructor
*/
virtual ~MonodomainPurkinjeSolver();
};
#endif // MONODOMAINPURKINJESOLVER_HPP_
| 7,493 | 2,431 |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "interfaces/queries/query_variant.hpp"
#include "interfaces/queries/get_account.hpp"
#include "interfaces/queries/get_account_asset_transactions.hpp"
#include "interfaces/queries/get_account_assets.hpp"
#include "interfaces/queries/get_account_detail.hpp"
#include "interfaces/queries/get_account_transactions.hpp"
#include "interfaces/queries/get_asset_info.hpp"
#include "interfaces/queries/get_block.hpp"
#include "interfaces/queries/get_pending_transactions.hpp"
#include "interfaces/queries/get_role_permissions.hpp"
#include "interfaces/queries/get_roles.hpp"
#include "interfaces/queries/get_signatories.hpp"
#include "interfaces/queries/get_transactions.hpp"
#include "interfaces/queries/query_payload_meta.hpp"
#include "utils/visitor_apply_for_all.hpp"
using Variant = shared_model::interface::Query::QueryVariantType;
template Variant::~variant();
template Variant::variant(Variant &&);
template bool Variant::operator==(const Variant &) const;
template void Variant::destroy_content() noexcept;
template int Variant::which() const noexcept;
template void Variant::indicate_which(int) noexcept;
template bool Variant::using_backup() const noexcept;
template Variant::convert_copy_into::convert_copy_into(void *) noexcept;
namespace shared_model {
namespace interface {
std::string Query::toString() const {
return detail::PrettyStringBuilder()
.init("Query")
.append("creatorId", creatorAccountId())
.append("queryCounter", std::to_string(queryCounter()))
.append(Signable::toString())
.append(boost::apply_visitor(detail::ToStringVisitor(), get()))
.finalize();
}
bool Query::operator==(const ModelType &rhs) const {
return this->get() == rhs.get();
}
} // namespace interface
} // namespace shared_model
| 1,928 | 601 |
// solving A * X = B
// using driver function gesv()
#include <cstddef>
#include <iostream>
#include <complex>
#include <boost/numeric/bindings/lapack/gesv.hpp>
#include <boost/numeric/bindings/traits/ublas_matrix.hpp>
#include <boost/numeric/bindings/traits/std_vector.hpp>
#include "utils.h"
namespace ublas = boost::numeric::ublas;
namespace lapack = boost::numeric::bindings::lapack;
using std::size_t;
using std::cout;
using std::endl;
typedef std::complex<double> cmpx_t;
typedef ublas::matrix<double, ublas::column_major> m_t;
typedef ublas::matrix<cmpx_t, ublas::column_major> cm_t;
int main() {
cout << endl;
cout << "real system:" << endl << endl;
size_t n = 5;
m_t a (n, n); // system matrix
size_t nrhs = 2;
m_t x (n, nrhs), b (n, nrhs); // b -- right-hand side matrix
std::vector<int> ipiv (n); // pivot vector
init_symm (a);
// [n n-1 n-2 ... 1]
// [n-1 n n-1 ... 2]
// a = [n-2 n-1 n ... 3]
// [ ... ]
// [1 2 ... n-1 n]
m_t aa (a); // copy of a, because a is `lost' after gesv()
for (int i = 0; i < x.size1(); ++i) {
x (i, 0) = 1.;
x (i, 1) = 2.;
}
b = prod (a, x);
print_m (a, "A");
cout << endl;
print_m (b, "B");
cout << endl;
lapack::gesv (a, ipiv, b); // solving the system, b contains x
print_m (b, "X");
cout << endl;
x = prod (aa, b);
print_m (x, "B = A X");
cout << endl;
////////////////////////////////////////////////////////
cout << endl;
cout << "complex system:" << endl << endl;
cm_t ca (3, 3), cb (3, 1), cx (3, 1);
std::vector<int> ipiv2 (3);
ca (0, 0) = cmpx_t (3, 0);
ca (0, 1) = cmpx_t (4, 2);
ca (0, 2) = cmpx_t (-7, 5);
ca (1, 0) = cmpx_t (4, -2);
ca (1, 1) = cmpx_t (-5, 0);
ca (1, 2) = cmpx_t (0, -3);
ca (2, 0) = cmpx_t (-7, -5);
ca (2, 1) = cmpx_t (0, 3);
ca (2, 2) = cmpx_t (2, 0);
print_m (ca, "CA");
cout << endl;
for (int i = 0; i < cx.size1(); ++i)
cx (i, 0) = cmpx_t (1, -1);
cb = prod (ca, cx);
print_m (cb, "CB");
cout << endl;
int ierr = lapack::gesv (ca, ipiv2, cb);
if (ierr == 0)
print_m (cb, "CX");
else
cout << "matrix is singular" << endl;
cout << endl;
}
| 2,250 | 1,071 |
#include "kl25_tsi.h"
#include "mbed.h"
/******************************************************************************
* Example 1 : put a cable on A0 pin and touch this pin for lighting red light
#include "mbed.h"
DigitalOut red(LED_RED);
int main(){
uint16_t sense_A0;
tsiInit(TSI_CURRENT_8uA, TSI_CURRENT_64uA, TSI_DV_1_03V, TSI_DIV_16, TSI_12_SCAN);
TSIChannelName channel= tsiActivateChannel(A0);
while(1) {
sense_A0 = 0;
tsiStart((TSIChannelName)channel);
while(!tsiAvalaible()) {
sense_A0= tsiRead();
printf("TOUCH: %d\r\n", sense_A0);
}
if(sense_A0<380)
red=1;
else
red=0;
}
}
*********************************************************************/
/********************************************************************
* Example read TSI in interrupt
#include "mbed.h"
DigitalOut red(LED_RED);
TSIChannelName gChannel;
void ISR_TSI0(){
gFlagTSI=true;
fgpioToggle(FPTA, 12); // D3 out
tsiStart(gChannel);
}
int main(){
uint16_t sense_A0;
tsiInit(TSI_CURRENT_8uA, TSI_CURRENT_64uA, TSI_DV_1_03V, TSI_DIV_16, TSI_12_SCAN);
gChannel= tsiActivateChannel(A0);
tsiSetTreshold(375,330);
tsiEnableInterrupt();
tsiStart(gChannel);
tsi_attachInterrupt(ISR_TSI0);
while(1) {
sense_A0 = 0;
wait(0.1);
if(gFlagTSI){
sense_A0= tsiRead();
printf("TOUCH: %d\r\n", sense_A0);
if (red.read() == 0)
red= 1;
else
red = 0;
gFlagTSI=false;
}
}
}
**********************************************************/
void (*fTSI0)(void);
// RAM interrupt handler relocated
void TSI0_IRQ_Handler(){
fTSI0();
TSI0->GENCS |=TSI_GENCS_OUTRGF_MASK ;//clear TOF
}
void tsiInit(TSI_Charge_Current refChg, TSI_Charge_Current extChg, TSI_DV dvolt, TSI_DIV_PRESCALER ps, TSI_NUMBER_OF_SCAN nscn) {
// The first version is preconfigured for non-noise detection, no interrupts, not running on stop modes, software trigger
SIM->SCGC5 |= SIM_SCGC5_TSI_MASK; // clock gate for TSI
TSI0->GENCS = 0xC0000080 | ((refChg & 0x07) << 21) | ((extChg & 0x07) << 16) | ((dvolt & 0x03) << 19) | ((ps & 0x07) << 13) | ((nscn & 0x1F) << 8);
}
/* Function to configure a pin to work with the corresponding channel (passed as the single parameter) */
TSIChannelName tsiActivateChannel(PinName pin) {
// reads channel number and sets the MUX of the corresponding pin to ALT0 function
unsigned int port = (unsigned int)pin >> PORT_SHIFT;
unsigned int pin_n = (pin&0xFF)>>2;
switch(port){
case 0: SIM->SCGC5|=SIM_SCGC5_PORTA_MASK; break;
case 1: SIM->SCGC5|=SIM_SCGC5_PORTB_MASK; break;
case 2: SIM->SCGC5|=SIM_SCGC5_PORTC_MASK; break;
}
TSIChannelName channel = (TSIChannelName)pinmap_peripheral(pin, PinMap_TSI);
if(((int)channel)==NC)
error("PinName provided to tsiActivateChannel() does not correspond to any known TSI channel.");
printf("port=%d, pn_n=%d, channel=%d\n\r",port,pin_n,channel);
PORT_Type *port_reg = (PORT_Type *)(PORTA_BASE + 0x1000 *port);
port_reg->PCR[pin_n] &= ~PORT_PCR_MUX_MASK;//choose ALT0 pin
return channel;
}
// Function to trigger the reading of a given channel
void tsiStart(TSIChannelName channel) {
//writes 1 to the software trigger bit, defining the channel number in the respective bits
TSI0->GENCS |= TSI_GENCS_EOSF_MASK; // clears EOSF
TSI0->DATA = TSI_DATA_SWTS_MASK | TSI_DATA_TSICH(channel);
}
void tsiSetTreshold(uint16_t tresholdHigh,uint16_t tresholdLow){
unsigned int tshd = (tresholdLow&0xFFFF) | (tresholdHigh<<16);
TSI0->TSHD=tshd;
printf("treshold=%x\n\r",tshd);
}
void tsiEnableInterruptOnTreshold(){
TSI0->GENCS|=TSI_GENCS_TSIIEN_MASK;//The interrupt will wake MCU from low power mode if this interrupt is enabled.
TSI0->GENCS|=TSI_GENCS_STPE_MASK;//This bit enables TSI module function in low power modes
TSI0->GENCS&=~TSI_GENCS_ESOR_MASK;//0 Out-of-range interrupt is allowed.
}
void tsiEnableInterrupt(){
TSI0->GENCS|=TSI_GENCS_TSIIEN_MASK; //This bit enables TSI module interrupt request to CPU when the scan completes
TSI0->GENCS|=TSI_GENCS_ESOR_MASK;//1 End-of-scan interrupt is allowed.
}
void tsiDisableInterrupt(){
TSI0->GENCS&=~TSI_GENCS_TSIIEN_MASK;//The interrupt will wake MCU from low power mode if this interrupt is enabled.
TSI0->GENCS&=~TSI_GENCS_STPE_MASK;//This bit enables TSI module function in low power modes
}
void tsi_attachTSI0_IRQHandler(){
NVIC_EnableIRQ(TSI0_IRQn);
__enable_irq();
}
void tsi_attachInterrupt(void (*userFunc)(void)){
fTSI0 = userFunc;
NVIC_SetVector(TSI0_IRQn, (uint32_t)TSI0_IRQ_Handler);
NVIC_EnableIRQ(TSI0_IRQn);
__enable_irq();
}
void tsi_dettachInterrupt(){
NVIC_DisableIRQ(TSI0_IRQn);
}
// Function to read scan result; returns zero if not finished
uint16_t tsiRead() {
uint16_t aux;
aux = TSI0->DATA & 0x0000FFFF;
TSI0->GENCS |= TSI_GENCS_EOSF_MASK; // clears EOSF
return aux;
}
| 5,130 | 2,030 |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string s;
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
std::ios_base::sync_with_stdio(false);
cin.tie(0);
ll k, cnt=0;
cin>>k>>s;
sort(s.begin(), s.end());
int len = s.size();
for(int i=0; i<len; i++) {
cnt+=(s[i]-'0');
}
int ans=0;
for(int i=0; cnt<k; i++) {
ans++;
cnt+= (9 - (s[i] - '0') );
}
cout<<ans<<endl;
return 0;
}
| 570 | 261 |
/*=auto=========================================================================
Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile: vtkMRMLColorLogic.cxx,v $
Date: $Date$
Version: $Revision$
=========================================================================auto=*/
// MRMLLogic includes
#include "vtkMRMLColorLogic.h"
// MRML includes
#include "vtkMRMLColorTableNode.h"
#include "vtkMRMLColorTableStorageNode.h"
#include "vtkMRMLFreeSurferProceduralColorNode.h"
#include "vtkMRMLdGEMRICProceduralColorNode.h"
#include "vtkMRMLPETProceduralColorNode.h"
#include "vtkMRMLProceduralColorStorageNode.h"
#include "vtkMRMLScene.h"
// VTK sys includes
#include <vtkLookupTable.h>
#include <vtksys/SystemTools.hxx>
// VTK includes
#include <vtkColorTransferFunction.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
// STD includes
#include <algorithm>
#include <cassert>
#include <ctype.h> // For isspace
#include <functional>
#include <sstream>
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::TempColorNodeID;
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkMRMLColorLogic);
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::DEFAULT_TERMINOLOGY_NAME = "GenericAnatomyColors";
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::StandardTerm::Print(std::ostream& os)
{
vtkIndent indent;
this->PrintSelf(os, indent.GetNextIndent());
}
//----------------------------------------------------------------------------
std::ostream& vtkMRMLColorLogic::StandardTerm::operator<<(std::ostream& os)
{
this->Print(os);
return os;
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::StandardTerm::PrintSelf(std::ostream &os, vtkIndent indent)
{
os << indent << "Code value: " << CodeValue.c_str() << std::endl
<< indent << "Code scheme designator: " << CodingSchemeDesignator.c_str() << std::endl
<< indent << "Code meaning: " << CodeMeaning.c_str()
<< std::endl;
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::ColorLabelCategorization::Print(std::ostream& os)
{
vtkIndent indent;
this->PrintSelf(os, indent.GetNextIndent());
}
//----------------------------------------------------------------------------
std::ostream& vtkMRMLColorLogic::ColorLabelCategorization::operator<<(std::ostream& os)
{
this->Print(os);
return os;
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::ColorLabelCategorization::PrintSelf(ostream &os, vtkIndent indent)
{
os << "Label: " << LabelValue << std::endl;
os << "Segmented property category:\n";
SegmentedPropertyCategory.PrintSelf(os, indent);
os << "Segmented property type:\n";
SegmentedPropertyType.PrintSelf(os, indent);
os << "Segmented property type modifier:\n";
SegmentedPropertyTypeModifier.PrintSelf(os, indent);
os << "Anatomic region:\n";
AnatomicRegion.PrintSelf(os, indent);
os << "Antatomic region modifier:\n";
AnatomicRegionModifier.PrintSelf(os, indent);
os << std::endl;
}
//----------------------------------------------------------------------------
vtkMRMLColorLogic::vtkMRMLColorLogic()
{
this->UserColorFilePaths = NULL;
}
//----------------------------------------------------------------------------
vtkMRMLColorLogic::~vtkMRMLColorLogic()
{
// remove the default color nodes
this->RemoveDefaultColorNodes();
// clear out the lists of files
this->ColorFiles.clear();
this->TerminologyColorFiles.clear();
this->UserColorFiles.clear();
if (this->UserColorFilePaths)
{
delete [] this->UserColorFilePaths;
this->UserColorFilePaths = NULL;
}
}
//------------------------------------------------------------------------------
void vtkMRMLColorLogic::SetMRMLSceneInternal(vtkMRMLScene* newScene)
{
// We are solely interested in vtkMRMLScene::NewSceneEvent,
// we don't want to listen to any other events.
vtkIntArray* sceneEvents = vtkIntArray::New();
sceneEvents->InsertNextValue(vtkMRMLScene::NewSceneEvent);
this->SetAndObserveMRMLSceneEventsInternal(newScene, sceneEvents);
sceneEvents->Delete();
if (newScene)
{
this->OnMRMLSceneNewEvent();
}
}
//------------------------------------------------------------------------------
void vtkMRMLColorLogic::OnMRMLSceneNewEvent()
{
this->AddDefaultColorNodes();
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkObject::PrintSelf(os, indent);
os << indent << "vtkMRMLColorLogic: " << this->GetClassName() << "\n";
os << indent << "UserColorFilePaths: " << this->GetUserColorFilePaths() << "\n";
os << indent << "Color Files:\n";
for (size_t i = 0; i < this->ColorFiles.size(); i++)
{
os << indent.GetNextIndent() << i << " " << this->ColorFiles[i].c_str() << "\n";
}
os << indent << "User Color Files:\n";
for (size_t i = 0; i < this->UserColorFiles.size(); i++)
{
os << indent.GetNextIndent() << i << " " << this->UserColorFiles[i].c_str() << "\n";
}
os << indent << "Terminology Color Files:\n";
for (size_t i = 0; i < this->TerminologyColorFiles.size(); i++)
{
os << indent.GetNextIndent() << i << " " << this->TerminologyColorFiles[i].c_str() << "\n";
}
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultColorNodes()
{
// create the default color nodes, they don't get saved with the scenes as
// they'll be created on start up, and when a new
// scene is opened
if (this->GetMRMLScene() == NULL)
{
vtkWarningMacro("vtkMRMLColorLogic::AddDefaultColorNodes: no scene to which to add nodes\n");
return;
}
this->GetMRMLScene()->StartState(vtkMRMLScene::BatchProcessState);
// add the labels first
this->AddLabelsNode();
// add the rest of the default color table nodes
this->AddDefaultTableNodes();
// add default procedural nodes, including a random one
this->AddDefaultProceduralNodes();
// add freesurfer nodes
this->AddFreeSurferNodes();
// add the PET nodes
this->AddPETNodes();
// add the dGEMRIC nodes
this->AddDGEMRICNodes();
// file based labels
// first check for any new ones
// load the one from the default resources directory
this->AddDefaultFileNodes();
// now add ones in files that the user pointed to, these ones are not hidden
// from the editors
this->AddUserFileNodes();
// now load in the terminology color files and associate them with the
// color nodes
this->AddDefaultTerminologyColors();
vtkDebugMacro("Done adding default color nodes");
this->GetMRMLScene()->EndState(vtkMRMLScene::BatchProcessState);
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::RemoveDefaultColorNodes()
{
// try to find any of the default colour nodes that are still in the scene
if (this->GetMRMLScene() == NULL)
{
// nothing can do, it's gone
return;
}
this->GetMRMLScene()->StartState(vtkMRMLScene::BatchProcessState);
vtkMRMLColorTableNode *basicNode = vtkMRMLColorTableNode::New();
vtkMRMLColorTableNode *node;
for (int i = basicNode->GetFirstType(); i <= basicNode->GetLastType(); i++)
{
// don't have a File node...
if (i != vtkMRMLColorTableNode::File
&& i != vtkMRMLColorTableNode::Obsolete)
{
//std::string id = std::string(this->GetColorTableNodeID(i));
const char* id = this->GetColorTableNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
}
}
basicNode->Delete();
// remove freesurfer nodes
vtkMRMLFreeSurferProceduralColorNode *basicFSNode = vtkMRMLFreeSurferProceduralColorNode::New();
vtkMRMLFreeSurferProceduralColorNode *fsnode;
for (int i = basicFSNode->GetFirstType(); i <= basicFSNode->GetLastType(); i++)
{
basicFSNode->SetType(i);
const char* id = this->GetFreeSurferColorNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
fsnode = vtkMRMLFreeSurferProceduralColorNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (fsnode != NULL)
{
this->GetMRMLScene()->RemoveNode(fsnode);
}
}
basicFSNode->Delete();
// remove the procedural color nodes (after the fs proc nodes as
// getting them by class)
std::vector<vtkMRMLNode *> procNodes;
int numProcNodes = this->GetMRMLScene()->GetNodesByClass("vtkMRMLProceduralColorNode", procNodes);
for (int i = 0; i < numProcNodes; i++)
{
vtkMRMLProceduralColorNode* procNode = vtkMRMLProceduralColorNode::SafeDownCast(procNodes[i]);
if (procNode != NULL &&
strcmp(procNode->GetID(), this->GetProceduralColorNodeID(procNode->GetName())) == 0)
{
// it's one we added
this->GetMRMLScene()->RemoveNode(procNode);
}
}
// remove the fs lookup table node
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(this->GetDefaultFreeSurferLabelMapColorNodeID()));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
// remove the PET nodes
vtkMRMLPETProceduralColorNode *basicPETNode = vtkMRMLPETProceduralColorNode::New();
vtkMRMLPETProceduralColorNode *PETnode;
for (int i = basicPETNode->GetFirstType(); i <= basicPETNode->GetLastType(); i++)
{
basicPETNode->SetType(i);
const char* id = this->GetPETColorNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
PETnode = vtkMRMLPETProceduralColorNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (PETnode != NULL)
{
this->GetMRMLScene()->RemoveNode(PETnode);
}
}
basicPETNode->Delete();
// remove the dGEMRIC nodes
vtkMRMLdGEMRICProceduralColorNode *basicdGEMRICNode = vtkMRMLdGEMRICProceduralColorNode::New();
vtkMRMLdGEMRICProceduralColorNode *dGEMRICnode;
for (int i = basicdGEMRICNode->GetFirstType(); i <= basicdGEMRICNode->GetLastType(); i++)
{
basicdGEMRICNode->SetType(i);
const char* id = this->GetdGEMRICColorNodeID(i);
vtkDebugMacro("vtkMRMLColorLogic::RemoveDefaultColorNodes: trying to find node with id " << id << endl);
dGEMRICnode = vtkMRMLdGEMRICProceduralColorNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(id));
if (dGEMRICnode != NULL)
{
this->GetMRMLScene()->RemoveNode(dGEMRICnode);
}
}
basicdGEMRICNode->Delete();
// remove the file based labels node
for (unsigned int i = 0; i < this->ColorFiles.size(); i++)
{
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(this->GetFileColorNodeID(this->ColorFiles[i].c_str())));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
}
for (unsigned int i = 0; i < this->UserColorFiles.size(); i++)
{
node = vtkMRMLColorTableNode::SafeDownCast(this->GetMRMLScene()->GetNodeByID(this->GetFileColorNodeID(this->UserColorFiles[i].c_str())));
if (node != NULL)
{
this->GetMRMLScene()->RemoveNode(node);
}
}
this->GetMRMLScene()->EndState(vtkMRMLScene::BatchProcessState);
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetColorTableNodeID(int type)
{
vtkNew<vtkMRMLColorTableNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetFreeSurferColorNodeID(int type)
{
vtkNew<vtkMRMLFreeSurferProceduralColorNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetPETColorNodeID (int type )
{
vtkNew<vtkMRMLPETProceduralColorNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetdGEMRICColorNodeID(int type)
{
vtkNew<vtkMRMLdGEMRICProceduralColorNode> basicNode;
basicNode->SetType(type);
return vtkMRMLColorLogic::GetColorNodeID(basicNode.GetPointer());
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetColorNodeID(vtkMRMLColorNode* colorNode)
{
assert(colorNode);
std::string id = std::string(colorNode->GetClassName()) +
std::string(colorNode->GetTypeAsString());
vtkMRMLColorLogic::TempColorNodeID = id;
return vtkMRMLColorLogic::TempColorNodeID.c_str();
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetProceduralColorNodeID(const char *name)
{
std::string id = std::string("vtkMRMLProceduralColorNode") + std::string(name);
vtkMRMLColorLogic::TempColorNodeID = id;
return vtkMRMLColorLogic::TempColorNodeID.c_str();
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetFileColorNodeSingletonTag(const char * fileName)
{
std::string singleton = std::string("File") +
vtksys::SystemTools::GetFilenameName(fileName);
return singleton;
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetFileColorNodeID(const char * fileName)
{
std::string id = std::string("vtkMRMLColorTableNode") +
vtkMRMLColorLogic::GetFileColorNodeSingletonTag(fileName);
vtkMRMLColorLogic::TempColorNodeID = id;
return vtkMRMLColorLogic::TempColorNodeID.c_str();
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultVolumeColorNodeID()
{
return vtkMRMLColorLogic::GetColorTableNodeID(vtkMRMLColorTableNode::Grey);
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultLabelMapColorNodeID()
{
return vtkMRMLColorLogic::GetProceduralColorNodeID("RandomIntegers");
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultEditorColorNodeID()
{
return vtkMRMLColorLogic::GetProceduralColorNodeID("RandomIntegers");
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultModelColorNodeID()
{
return vtkMRMLColorLogic::GetFreeSurferColorNodeID(vtkMRMLFreeSurferProceduralColorNode::Heat);
}
//----------------------------------------------------------------------------
const char *vtkMRMLColorLogic::GetDefaultChartColorNodeID()
{
return vtkMRMLColorLogic::GetProceduralColorNodeID("RandomIntegers");
}
//----------------------------------------------------------------------------
const char * vtkMRMLColorLogic::GetDefaultFreeSurferLabelMapColorNodeID()
{
return vtkMRMLColorLogic::GetFreeSurferColorNodeID(vtkMRMLFreeSurferProceduralColorNode::Labels);
}
//----------------------------------------------------------------------------
void vtkMRMLColorLogic::AddColorFile(const char *fileName, std::vector<std::string> *Files)
{
if (fileName == NULL)
{
vtkErrorMacro("AddColorFile: can't add a null color file name");
return;
}
if (Files == NULL)
{
vtkErrorMacro("AddColorFile: no array to which to add color file to!");
return;
}
// check if it's in the vector already
std::string fileNameStr = std::string(fileName);
for (unsigned int i = 0; i < Files->size(); i++)
{
std::string fileToCheck;
try
{
fileToCheck = Files->at(i);
}
catch (...)
{
// an out_of_range exception can be thrown.
}
if (fileToCheck.compare(fileNameStr) == 0)
{
vtkDebugMacro("AddColorFile: already have this file at index " << i << ", not adding it again: " << fileNameStr.c_str());
return;
}
}
vtkDebugMacro("AddColorFile: adding file name to Files: " << fileNameStr.c_str());
Files->push_back(fileNameStr);
}
//----------------------------------------------------------------------------
vtkMRMLColorNode* vtkMRMLColorLogic::LoadColorFile(const char *fileName, const char *nodeName)
{
// try loading it as a color table node first
vtkMRMLColorTableNode* node = this->CreateFileNode(fileName);
vtkMRMLColorNode * addedNode = NULL;
if (node)
{
node->SetAttribute("Category", "File");
node->SaveWithSceneOn();
node->GetStorageNode()->SaveWithSceneOn();
node->HideFromEditorsOff();
node->SetSingletonTag(NULL);
if (nodeName != NULL)
{
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(nodeName));
node->SetName(uname.c_str());
}
addedNode =
vtkMRMLColorNode::SafeDownCast(this->GetMRMLScene()->AddNode(node));
vtkDebugMacro("LoadColorFile: Done: Read and added file node: " << fileName);
node->Delete();
}
else
{
// try loading it as a procedural node
vtkWarningMacro("Trying to read color file as a procedural color node");
vtkMRMLProceduralColorNode *procNode = this->CreateProceduralFileNode(fileName);
if (procNode)
{
procNode->SetAttribute("Category", "File");
procNode->SaveWithSceneOn();
procNode->GetStorageNode()->SaveWithSceneOn();
procNode->HideFromEditorsOff();
procNode->SetSingletonTag(NULL);
if (nodeName != NULL)
{
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(nodeName));
procNode->SetName(uname.c_str());
}
addedNode =
vtkMRMLColorNode::SafeDownCast(this->GetMRMLScene()->AddNode(procNode));
vtkDebugMacro("LoadColorFile: Done: Read and added file procNode: " << fileName);
procNode->Delete();
}
}
return addedNode;
}
//------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateLabelsNode()
{
vtkMRMLColorTableNode *labelsNode = vtkMRMLColorTableNode::New();
labelsNode->SetTypeToLabels();
labelsNode->SetAttribute("Category", "Discrete");
labelsNode->SaveWithSceneOff();
labelsNode->SetName(labelsNode->GetTypeAsString());
labelsNode->SetSingletonTag(labelsNode->GetTypeAsString());
return labelsNode;
}
//------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateDefaultTableNode(int type)
{
vtkMRMLColorTableNode *node = vtkMRMLColorTableNode::New();
node->SetType(type);
const char* typeName = node->GetTypeAsString();
if (strstr(typeName, "Tint") != NULL)
{
node->SetAttribute("Category", "Tint");
}
else if (strstr(typeName, "Shade") != NULL)
{
node->SetAttribute("Category", "Shade");
}
else
{
node->SetAttribute("Category", "Discrete");
}
if (strcmp(typeName, "(unknown)") == 0)
{
return node;
}
node->SaveWithSceneOff();
node->SetName(node->GetTypeAsString());
node->SetSingletonTag(node->GetTypeAsString());
return node;
}
//------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CreateRandomNode()
{
vtkDebugMacro("vtkMRMLColorLogic::CreateRandomNode: making a random mrml proc color node");
vtkMRMLProceduralColorNode *procNode = vtkMRMLProceduralColorNode::New();
procNode->SetName("RandomIntegers");
procNode->SetAttribute("Category", "Discrete");
procNode->SaveWithSceneOff();
procNode->SetSingletonTag(procNode->GetTypeAsString());
vtkColorTransferFunction *func = procNode->GetColorTransferFunction();
const int dimension = 1000;
double table[3*dimension];
double* tablePtr = table;
for (int i = 0; i < dimension; ++i)
{
*tablePtr++ = static_cast<double>(rand())/RAND_MAX;
*tablePtr++ = static_cast<double>(rand())/RAND_MAX;
*tablePtr++ = static_cast<double>(rand())/RAND_MAX;
}
func->BuildFunctionFromTable(VTK_INT_MIN, VTK_INT_MAX, dimension, table);
func->Build();
procNode->SetNamesFromColors();
return procNode;
}
//------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CreateRedGreenBlueNode()
{
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: making a red - green - blue mrml proc color node");
vtkMRMLProceduralColorNode *procNode = vtkMRMLProceduralColorNode::New();
procNode->SetName("RedGreenBlue");
procNode->SetAttribute("Category", "Continuous");
procNode->SaveWithSceneOff();
procNode->SetSingletonTag(procNode->GetTypeAsString());
procNode->SetDescription("A color transfer function that maps from -6 to 6, red through green to blue");
vtkColorTransferFunction *func = procNode->GetColorTransferFunction();
func->SetColorSpaceToRGB();
func->AddRGBPoint(-6.0, 1.0, 0.0, 0.0);
func->AddRGBPoint(0.0, 0.0, 1.0, 0.0);
func->AddRGBPoint(6.0, 0.0, 0.0, 1.0);
procNode->SetNamesFromColors();
return procNode;
}
//------------------------------------------------------------------------------
vtkMRMLFreeSurferProceduralColorNode* vtkMRMLColorLogic::CreateFreeSurferNode(int type)
{
vtkMRMLFreeSurferProceduralColorNode *node = vtkMRMLFreeSurferProceduralColorNode::New();
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: setting free surfer proc color node type to " << type);
node->SetType(type);
node->SetAttribute("Category", "FreeSurfer");
node->SaveWithSceneOff();
if (node->GetTypeAsString() == NULL)
{
vtkWarningMacro("Node type as string is null");
node->SetName("NoName");
}
else
{
node->SetName(node->GetTypeAsString());
}
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: set proc node name to " << node->GetName());
/*
if (this->GetFreeSurferColorNodeID(i) == NULL)
{
vtkDebugMacro("Error getting default node id for freesurfer node " << i);
}
*/
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: Getting default fs color node id for type " << type);
node->SetSingletonTag(node->GetTypeAsString());
return node;
}
//------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateFreeSurferFileNode(const char* fileName)
{
if (fileName == NULL)
{
vtkErrorMacro("Unable to get the labels file name, not adding");
return 0;
}
vtkMRMLColorTableNode* node = this->CreateFileNode(fileName);
if (!node)
{
return 0;
}
node->SetAttribute("Category", "FreeSurfer");
node->SetName("FreeSurferLabels");
node->SetSingletonTag(node->GetTypeAsString());
return node;
}
//--------------------------------------------------------------------------------
vtkMRMLPETProceduralColorNode* vtkMRMLColorLogic::CreatePETColorNode(int type)
{
vtkMRMLPETProceduralColorNode *nodepcn = vtkMRMLPETProceduralColorNode::New();
nodepcn->SetType(type);
nodepcn->SetAttribute("Category", "PET");
nodepcn->SaveWithSceneOff();
if (nodepcn->GetTypeAsString() == NULL)
{
vtkWarningMacro("Node type as string is null");
nodepcn->SetName("NoName");
}
else
{
vtkDebugMacro("Got node type as string " << nodepcn->GetTypeAsString());
nodepcn->SetName(nodepcn->GetTypeAsString());
}
nodepcn->SetSingletonTag(nodepcn->GetTypeAsString());
return nodepcn;
}
//---------------------------------------------------------------------------------
vtkMRMLdGEMRICProceduralColorNode* vtkMRMLColorLogic::CreatedGEMRICColorNode(int type)
{
vtkMRMLdGEMRICProceduralColorNode *pcnode = vtkMRMLdGEMRICProceduralColorNode::New();
pcnode->SetType(type);
pcnode->SetAttribute("Category", "Cartilage MRI");
pcnode->SaveWithSceneOff();
if (pcnode->GetTypeAsString() == NULL)
{
vtkWarningMacro("Node type as string is null");
pcnode->SetName("NoName");
}
else
{
vtkDebugMacro("Got node type as string " << pcnode->GetTypeAsString());
pcnode->SetName(pcnode->GetTypeAsString());
}
pcnode->SetSingletonTag(pcnode->GetTypeAsString());
return pcnode;
}
//---------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateDefaultFileNode(const std::string& colorFileName)
{
vtkMRMLColorTableNode* ctnode = this->CreateFileNode(colorFileName.c_str());
if (!ctnode)
{
return 0;
}
if (strcmp(ctnode->GetName(),"GenericColors") == 0 ||
strcmp(ctnode->GetName(),"GenericAnatomyColors") == 0)
{
vtkDebugMacro("Found default lut node");
// No category to float to the top of the node
// can't unset an attribute, so just don't set it at all
}
else
{
ctnode->SetAttribute("Category", "Default Labels from File");
}
return ctnode;
}
//---------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateUserFileNode(const std::string& colorFileName)
{
vtkMRMLColorTableNode * ctnode = this->CreateFileNode(colorFileName.c_str());
if (ctnode == 0)
{
return 0;
}
ctnode->SetAttribute("Category", "Auto Loaded User Color Files");
ctnode->SaveWithSceneOn();
ctnode->HideFromEditorsOff();
return ctnode;
}
//--------------------------------------------------------------------------------
std::vector<std::string> vtkMRMLColorLogic::FindDefaultColorFiles()
{
return std::vector<std::string>();
}
//--------------------------------------------------------------------------------
std::vector<std::string> vtkMRMLColorLogic::FindDefaultTerminologyColorFiles()
{
return std::vector<std::string>();
}
//--------------------------------------------------------------------------------
std::vector<std::string> vtkMRMLColorLogic::FindUserColorFiles()
{
return std::vector<std::string>();
}
//--------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CreateFileNode(const char* fileName)
{
vtkMRMLColorTableNode * ctnode = vtkMRMLColorTableNode::New();
ctnode->SetTypeToFile();
ctnode->SaveWithSceneOff();
ctnode->HideFromEditorsOn();
ctnode->SetScene(this->GetMRMLScene());
// make a storage node
vtkNew<vtkMRMLColorTableStorageNode> colorStorageNode;
colorStorageNode->SaveWithSceneOff();
if (this->GetMRMLScene())
{
this->GetMRMLScene()->AddNode(colorStorageNode.GetPointer());
ctnode->SetAndObserveStorageNodeID(colorStorageNode->GetID());
}
ctnode->GetStorageNode()->SetFileName(fileName);
std::string basename = vtksys::SystemTools::GetFilenameWithoutExtension(fileName);
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(basename.c_str()));
ctnode->SetName(uname.c_str());
vtkDebugMacro("CreateFileNode: About to read user file " << fileName);
if (ctnode->GetStorageNode()->ReadData(ctnode) == 0)
{
vtkErrorMacro("Unable to read file as color table " << (ctnode->GetFileName() ? ctnode->GetFileName() : ""));
if (this->GetMRMLScene())
{
ctnode->SetAndObserveStorageNodeID(NULL);
ctnode->SetScene(NULL);
this->GetMRMLScene()->RemoveNode(colorStorageNode.GetPointer());
}
ctnode->Delete();
return 0;
}
vtkDebugMacro("CreateFileNode: finished reading user file " << fileName);
ctnode->SetSingletonTag(
this->GetFileColorNodeSingletonTag(fileName).c_str());
return ctnode;
}
//--------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CreateProceduralFileNode(const char* fileName)
{
vtkMRMLProceduralColorNode * cpnode = vtkMRMLProceduralColorNode::New();
cpnode->SetTypeToFile();
cpnode->SaveWithSceneOff();
cpnode->HideFromEditorsOn();
cpnode->SetScene(this->GetMRMLScene());
// make a storage node
vtkMRMLProceduralColorStorageNode *colorStorageNode = vtkMRMLProceduralColorStorageNode::New();
colorStorageNode->SaveWithSceneOff();
if (this->GetMRMLScene())
{
this->GetMRMLScene()->AddNode(colorStorageNode);
cpnode->SetAndObserveStorageNodeID(colorStorageNode->GetID());
}
colorStorageNode->Delete();
cpnode->GetStorageNode()->SetFileName(fileName);
std::string basename = vtksys::SystemTools::GetFilenameWithoutExtension(fileName);
std::string uname( this->GetMRMLScene()->GetUniqueNameByString(basename.c_str()));
cpnode->SetName(uname.c_str());
vtkDebugMacro("CreateProceduralFileNode: About to read user file " << fileName);
if (cpnode->GetStorageNode()->ReadData(cpnode) == 0)
{
vtkErrorMacro("Unable to read procedural colour file " << (cpnode->GetFileName() ? cpnode->GetFileName() : ""));
if (this->GetMRMLScene())
{
cpnode->SetAndObserveStorageNodeID(NULL);
cpnode->SetScene(NULL);
this->GetMRMLScene()->RemoveNode(colorStorageNode);
}
cpnode->Delete();
return 0;
}
vtkDebugMacro("CreateProceduralFileNode: finished reading user procedural color file " << fileName);
cpnode->SetSingletonTag(
this->GetFileColorNodeSingletonTag(fileName).c_str());
return cpnode;
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddLabelsNode()
{
vtkMRMLColorTableNode* labelsNode = this->CreateLabelsNode();
//if (this->GetMRMLScene()->GetNodeByID(labelsNode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(labelsNode, labelsNode->GetSingletonTag());
this->GetMRMLScene()->AddNode(labelsNode);
}
labelsNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultTableNode(int i)
{
vtkMRMLColorTableNode* node = this->CreateDefaultTableNode(i);
//if (node->GetSingletonTag())
{
//if (this->GetMRMLScene()->GetNodeByID(node->GetSingletonTag()) == NULL)
{
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: requesting id " << node->GetSingletonTag() << endl);
//this->GetMRMLScene()->RequestNodeID(node, node->GetSingletonTag());
this->GetMRMLScene()->AddNode(node);
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: added node " << node->GetID() << ", requested id was " << node->GetSingletonTag() << ", type = " << node->GetTypeAsString() << endl);
}
//else
// {
// vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: didn't add node " << node->GetID() << " as it was already in the scene.\n");
// }
}
node->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultProceduralNodes()
{
// random one
vtkMRMLProceduralColorNode* randomNode = this->CreateRandomNode();
this->GetMRMLScene()->AddNode(randomNode);
randomNode->Delete();
// red green blue one
vtkMRMLProceduralColorNode* rgbNode = this->CreateRedGreenBlueNode();
this->GetMRMLScene()->AddNode(rgbNode);
rgbNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddFreeSurferNode(int type)
{
vtkMRMLFreeSurferProceduralColorNode* node = this->CreateFreeSurferNode(type);
//if (this->GetMRMLScene()->GetNodeByID(node->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(node, node->GetSingletonTag());
this->GetMRMLScene()->AddNode(node);
vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: added node " << node->GetID() << ", requested id was " << node->GetSingletonTag()<< ", type = " << node->GetTypeAsString() << endl);
}
//else
// {
// vtkDebugMacro("vtkMRMLColorLogic::AddDefaultColorNodes: didn't add node " << node->GetID() << " as it was already in the scene.\n");
// }
node->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddFreeSurferFileNode(vtkMRMLFreeSurferProceduralColorNode* basicFSNode)
{
vtkMRMLColorTableNode* node = this->CreateFreeSurferFileNode(basicFSNode->GetLabelsFileName());
if (node)
{
//if (this->GetMRMLScene()->GetNodeByID(node->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(node, node->GetSingletonTag());
this->GetMRMLScene()->AddNode(node);
}
//else
// {
// vtkDebugMacro("Unable to add a new colour node " << node->GetSingletonTag()
// << " with freesurfer colours, from file: "
// << node->GetStorageNode()->GetFileName()
// << " as there is already a node with this id in the scene");
// }
node->Delete();
}
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddPETNode(int type)
{
vtkDebugMacro("AddDefaultColorNodes: adding PET nodes");
vtkMRMLPETProceduralColorNode *nodepcn = this->CreatePETColorNode(type);
//if (this->GetMRMLScene()->GetNodeByID( nodepcn->GetSingletonTag() ) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(nodepcn, nodepcn->GetSingletonTag() );
this->GetMRMLScene()->AddNode(nodepcn);
}
nodepcn->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDGEMRICNode(int type)
{
vtkDebugMacro("AddDefaultColorNodes: adding dGEMRIC nodes");
vtkMRMLdGEMRICProceduralColorNode *pcnode = this->CreatedGEMRICColorNode(type);
//if (this->GetMRMLScene()->GetNodeByID(pcnode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(pcnode, pcnode->GetSingletonTag());
this->GetMRMLScene()->AddNode(pcnode);
}
pcnode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultFileNode(int i)
{
vtkMRMLColorTableNode* ctnode = this->CreateDefaultFileNode(this->ColorFiles[i]);
if (ctnode)
{
//if (this->GetMRMLScene()->GetNodeByID(ctnode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(ctnode, ctnode->GetSingletonTag());
this->GetMRMLScene()->AddNode(ctnode);
ctnode->Delete();
vtkDebugMacro("AddDefaultColorFiles: Read and added file node: " << this->ColorFiles[i].c_str());
}
//else
// {
// vtkDebugMacro("AddDefaultColorFiles: node " << ctnode->GetSingletonTag() << " already in scene");
// }
}
else
{
vtkWarningMacro("Unable to read color file " << this->ColorFiles[i].c_str());
}
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddUserFileNode(int i)
{
vtkMRMLColorTableNode* ctnode = this->CreateUserFileNode(this->UserColorFiles[i]);
if (ctnode)
{
//if (this->GetMRMLScene()->GetNodeByID(ctnode->GetSingletonTag()) == NULL)
{
//this->GetMRMLScene()->RequestNodeID(ctnode, ctnode->GetSingletonTag());
this->GetMRMLScene()->AddNode(ctnode);
vtkDebugMacro("AddDefaultColorFiles: Read and added user file node: " << this->UserColorFiles[i].c_str());
}
//else
// {
// vtkDebugMacro("AddDefaultColorFiles: node " << ctnode->GetSingletonTag() << " already in scene");
// }
}
else
{
vtkWarningMacro("Unable to read user color file " << this->UserColorFiles[i].c_str());
}
ctnode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultTableNodes()
{
vtkMRMLColorTableNode* basicNode = vtkMRMLColorTableNode::New();
for (int i = basicNode->GetFirstType(); i <= basicNode->GetLastType(); i++)
{
// don't add a second Lables node, File node or the old atlas node
if (i != vtkMRMLColorTableNode::Labels &&
i != vtkMRMLColorTableNode::File &&
i != vtkMRMLColorTableNode::Obsolete &&
i != vtkMRMLColorTableNode::User)
{
this->AddDefaultTableNode(i);
}
}
basicNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddFreeSurferNodes()
{
vtkDebugMacro("AddDefaultColorNodes: Adding Freesurfer nodes");
vtkMRMLFreeSurferProceduralColorNode* basicFSNode = vtkMRMLFreeSurferProceduralColorNode::New();
vtkDebugMacro("AddDefaultColorNodes: first type = " << basicFSNode->GetFirstType() << ", last type = " << basicFSNode->GetLastType());
for (int type = basicFSNode->GetFirstType(); type <= basicFSNode->GetLastType(); ++type)
{
this->AddFreeSurferNode(type);
}
// add a regular colour tables holding the freesurfer volume file colours and
// surface colours
this->AddFreeSurferFileNode(basicFSNode);
basicFSNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddPETNodes()
{
vtkMRMLPETProceduralColorNode* basicPETNode = vtkMRMLPETProceduralColorNode::New();
for (int type = basicPETNode->GetFirstType(); type <= basicPETNode->GetLastType(); ++type)
{
this->AddPETNode(type);
}
basicPETNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDGEMRICNodes()
{
vtkMRMLdGEMRICProceduralColorNode* basicdGEMRICNode = vtkMRMLdGEMRICProceduralColorNode::New();
for (int type = basicdGEMRICNode->GetFirstType(); type <= basicdGEMRICNode->GetLastType(); ++type)
{
this->AddDGEMRICNode(type);
}
basicdGEMRICNode->Delete();
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultFileNodes()
{
this->ColorFiles = this->FindDefaultColorFiles();
vtkDebugMacro("AddDefaultColorNodes: found " << this->ColorFiles.size() << " default color files");
for (unsigned int i = 0; i < this->ColorFiles.size(); i++)
{
this->AddDefaultFileNode(i);
}
}
//----------------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddUserFileNodes()
{
this->UserColorFiles = this->FindUserColorFiles();
vtkDebugMacro("AddDefaultColorNodes: found " << this->UserColorFiles.size() << " user color files");
for (unsigned int i = 0; i < this->UserColorFiles.size(); i++)
{
this->AddUserFileNode(i);
}
}
//----------------------------------------------------------------------------------------
vtkMRMLColorTableNode* vtkMRMLColorLogic::CopyNode(vtkMRMLColorNode* nodeToCopy, const char* copyName)
{
vtkMRMLColorTableNode *colorNode = vtkMRMLColorTableNode::New();
colorNode->SetName(copyName);
colorNode->SetTypeToUser();
colorNode->SetAttribute("Category", "User Generated");
colorNode->SetHideFromEditors(false);
colorNode->SetNamesInitialised(nodeToCopy->GetNamesInitialised());
if (nodeToCopy->GetLookupTable())
{
double* range = nodeToCopy->GetLookupTable()->GetRange();
colorNode->GetLookupTable()->SetRange(range[0], range[1]);
}
colorNode->SetNumberOfColors(nodeToCopy->GetNumberOfColors());
for (int i = 0; i < nodeToCopy->GetNumberOfColors(); ++i)
{
double color[4];
nodeToCopy->GetColor(i, color);
colorNode->SetColor(i, nodeToCopy->GetColorName(i), color[0], color[1], color[2], color[3]);
}
return colorNode;
}
//----------------------------------------------------------------------------------------
vtkMRMLProceduralColorNode* vtkMRMLColorLogic::CopyProceduralNode(vtkMRMLColorNode* nodeToCopy, const char* copyName)
{
vtkMRMLProceduralColorNode *colorNode = vtkMRMLProceduralColorNode::New();
if (nodeToCopy->IsA("vtkMRMLProceduralColorNode"))
{
colorNode->Copy(nodeToCopy);
// the copy will copy any singleton tag, make sure it's unset
colorNode->SetSingletonTag(NULL);
}
colorNode->SetName(copyName);
colorNode->SetTypeToUser();
colorNode->SetAttribute("Category", "User Generated");
colorNode->SetHideFromEditors(false);
return colorNode;
}
//------------------------------------------------------------------------------
void vtkMRMLColorLogic::AddDefaultTerminologyColors()
{
this->TerminologyColorFiles = this->FindDefaultTerminologyColorFiles();
vtkDebugMacro("AddDefaultTerminologyColorNodes: found " << this->TerminologyColorFiles.size() << " default terminology color files");
for (unsigned int i = 0; i < this->TerminologyColorFiles.size(); i++)
{
this->InitializeTerminologyMappingFromFile(this->TerminologyColorFiles[i]);
}
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::CreateNewTerminology(std::string lutName)
{
if (lutName.length() == 0)
{
return false;
}
if (this->TerminologyExists(lutName))
{
vtkWarningMacro("Create new terminology: one already exists with name " << lutName);
return false;
}
this->ColorCategorizationMaps[lutName] = ColorCategorizationMapType();
return this->AssociateTerminologyWithColorNode(lutName);
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::TerminologyExists(std::string lutName)
{
if (lutName.length() == 0)
{
return false;
}
if (this->ColorCategorizationMaps.find(lutName) !=
this->ColorCategorizationMaps.end())
{
return true;
}
else
{
return false;
}
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic
::AddTermToTerminology(std::string lutName, int labelValue,
std::string categoryValue,
std::string categorySchemeDesignator,
std::string categoryMeaning,
std::string typeValue,
std::string typeSchemeDesignator,
std::string typeMeaning,
std::string modifierValue,
std::string modifierSchemeDesignator,
std::string modifierMeaning,
std::string regionValue,
std::string regionSchemeDesignator,
std::string regionMeaning,
std::string regionModifierValue,
std::string regionModifierSchemeDesignator,
std::string regionModifierMeaning)
{
StandardTerm category(categoryValue, categorySchemeDesignator, categoryMeaning);
StandardTerm type(typeValue, typeSchemeDesignator, typeMeaning);
StandardTerm modifier(modifierValue, modifierSchemeDesignator, modifierMeaning);
StandardTerm region(regionValue, regionSchemeDesignator, regionMeaning);
StandardTerm regionModifier(regionModifierValue, regionModifierSchemeDesignator, regionModifierMeaning);
return this->AddTermToTerminologyMapping(lutName, labelValue, category, type, modifier, region, regionModifier);
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::AddTermToTerminologyMapping(std::string lutName, int labelValue,
StandardTerm category, StandardTerm type, StandardTerm modifier,
StandardTerm region, StandardTerm regionModifier)
{
if (lutName.length() == 0)
{
return false;
}
// check if the terminology mapping exists already, if not, create it
if (!this->TerminologyExists(lutName))
{
vtkDebugMacro("Adding a new terminology for " << lutName);
bool createFlag = this->CreateNewTerminology(lutName);
if (!createFlag)
{
vtkWarningMacro("Unable to create new terminology for " << lutName.c_str() << " or associate it with a color node.");
return false;
}
}
ColorLabelCategorization termMapping;
termMapping.LabelValue = labelValue;
termMapping.SegmentedPropertyCategory = category;
termMapping.SegmentedPropertyType = type;
termMapping.SegmentedPropertyTypeModifier = modifier;
termMapping.AnatomicRegion = region;
termMapping.AnatomicRegionModifier = regionModifier;
this->ColorCategorizationMaps[lutName][termMapping.LabelValue] = termMapping;
return true;
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::AssociateTerminologyWithColorNode(std::string lutName)
{
if (lutName.length() == 0)
{
return false;
}
vtkMRMLNode *colorNode = this->GetMRMLScene()->GetFirstNodeByName(lutName.c_str());
if (!colorNode)
{
vtkWarningMacro("Unable to associate terminology with named color node: " << lutName);
return false;
}
colorNode->SetAttribute("TerminologyName", lutName.c_str());
return true;
}
//------------------------------------------------------------------------------
bool vtkMRMLColorLogic::InitializeTerminologyMappingFromFile(std::string mapFileName)
{
std::cout << "Initializing terminology mapping for map file " << mapFileName << std::endl;
std::ifstream mapFile(mapFileName.c_str());
bool status = mapFile.is_open();
std::string lutName = "";
bool addFlag = true;
bool assocFlag = true;
bool parseFlag = true;
if (status)
{
while (!mapFile.eof())
{
std::string lineIn;
std::getline(mapFile, lineIn);
if (lineIn[0] == '#')
{
continue;
}
if (lineIn.find("SlicerLUT=") == std::string::npos)
{
continue;
}
size_t delim = lineIn.find("=");
lutName = lineIn.substr(delim+1,lineIn.length()-delim);
assocFlag = this->CreateNewTerminology(lutName);
break;
}
while (!mapFile.eof())
{
std::string lineIn, lineLeft;
std::getline(mapFile, lineIn);
if (lineIn.length()<30 || lineIn[0] == '#')
{
continue;
}
std::vector<std::string> tokens;
std::stringstream ss(lineIn);
std::string item;
while (std::getline(ss,item,','))
{
tokens.push_back(item);
}
if (tokens.size() < 5)
{
vtkWarningMacro("InitializeTerminologyMappingFromFile: line has incorrect number of tokens: "
<< tokens.size()
<< " < 5");
parseFlag = false;
}
else
{
int labelValue = atoi(tokens[0].c_str());
StandardTerm category, type, modifier;
if (this->ParseTerm(tokens[2],category) &&
this->ParseTerm(tokens[3],type))
{
// modifier is optional, ParseTerm will return false on an empty string
this->ParseTerm(tokens[4],modifier);
// for now region doesn't appear in the file
StandardTerm region, regionModifier;
addFlag = addFlag && this->AddTermToTerminologyMapping(lutName, labelValue, category, type, modifier, region, regionModifier);
}
else
{
vtkWarningMacro("InitializeTerminologyMappingFromFile: failed to parse category or type: "
<< tokens[2].c_str() << "\n"
<< tokens[3].c_str() << "\n"
<< tokens[4].c_str());
parseFlag = false;
}
}
}
}
std::cout << this->ColorCategorizationMaps[lutName].size()
<< " terms were read for Slicer LUT " << lutName << std::endl;
return status && addFlag && assocFlag && parseFlag;
}
//-------------------------------------------------------------------------------
bool vtkMRMLColorLogic::
LookupCategorizationFromLabel(int label, ColorLabelCategorization& labelCat, const char *lutName)
{
bool success = false;
if (this->TerminologyExists(lutName))
{
// set the label value so that if it's not found, it's still a valid categorisation
labelCat.LabelValue = label;
if (this->ColorCategorizationMaps[lutName].find(label) !=
this->ColorCategorizationMaps[lutName].end())
{
labelCat = this->ColorCategorizationMaps[lutName][label];
success = true;
}
}
return success;
}
//---------------------------------------------------------------------------
std::string vtkMRMLColorLogic::
GetTerminologyFromLabel(const std::string& categorization,
const std::string& standardTerm,
int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
StandardTerm term;
if (categorization.compare("SegmentedPropertyCategory") == 0)
{
term = labelCat.SegmentedPropertyCategory;
}
else if (categorization.compare("SegmentedPropertyType") == 0)
{
term = labelCat.SegmentedPropertyType;
}
else if (categorization.compare("SegmentedPropertyTypeModifier") == 0)
{
term = labelCat.SegmentedPropertyTypeModifier;
}
else if (categorization.compare("AnatomicRegion") == 0)
{
term = labelCat.AnatomicRegion;
}
else if (categorization.compare("AnatomicRegionModifier") == 0)
{
term = labelCat.AnatomicRegionModifier;
}
// now get the requested coding from the standard term
if (standardTerm.compare("CodeValue") == 0)
{
returnString = term.CodeValue;
}
else if (standardTerm.compare("CodeMeaning") == 0)
{
returnString = term.CodeMeaning;
}
else if (standardTerm.compare("CodingSchemeDesignator") == 0)
{
returnString = term.CodingSchemeDesignator;
}
}
return returnString;
}
//---------------------------------------------------------------------------
bool vtkMRMLColorLogic::PrintCategorizationFromLabel(int label, const char *lutName)
{
ColorLabelCategorization labelCat;
if (!this->TerminologyExists(lutName))
{
return false;
}
if (this->ColorCategorizationMaps[lutName].find(label) !=
this->ColorCategorizationMaps[lutName].end())
{
labelCat = this->ColorCategorizationMaps[lutName][label];
labelCat.Print(std::cout);
return true;
}
return false;
}
//---------------------------------------------------------------------------
std::string vtkMRMLColorLogic::RemoveLeadAndTrailSpaces(std::string in)
{
std::string ret = in;
ret.erase(ret.begin(), std::find_if(ret.begin(),ret.end(),
std::not1(std::ptr_fun<int,int>(isspace))));
ret.erase(std::find_if(ret.rbegin(),ret.rend(),
std::not1(std::ptr_fun<int,int>(isspace))).base(), ret.end());
return ret;
}
//---------------------------------------------------------------------------
bool vtkMRMLColorLogic::ParseTerm(const std::string inputStr, StandardTerm& term)
{
std::string str = inputStr;
str = this->RemoveLeadAndTrailSpaces(str);
if (str.length() < 10)
{
// can get empty strings for optional modifiers
return false;
}
// format check, should be enclosed in parentheses, have two ;'s
if (str.at(0) != '(' ||
str.at(str.length()-1) != ')')
{
vtkWarningMacro(<< __LINE__
<< ": ParseTerm: input string doesn't start/end with parentheses "
<< str);
return false;
}
size_t n = std::count(str.begin(), str.end(), ';');
if (n != 2)
{
vtkWarningMacro(<< __LINE__
<< ": ParseTerm: input string doesn't have 2 semi colons "
<< str);
return false;
}
// get rid of parentheses
str = str.substr(1,str.length()-2);
size_t found = str.find(";");
term.CodeValue = str.substr(0,found);
str = str.substr(found+1,str.length());
found = str.find(";");
term.CodingSchemeDesignator = str.substr(0,found);
str = str.substr(found+1, str.length());
term.CodeMeaning = str;
return true;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategoryCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyCategory.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategoryCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyCategory.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategoryCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyCategory.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyCategory(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.SegmentedPropertyCategory.CodeValue
+ sep
+ labelCat.SegmentedPropertyCategory.CodingSchemeDesignator
+ sep
+ labelCat.SegmentedPropertyCategory.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyType.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyType.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyType.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyType(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.SegmentedPropertyType.CodeValue
+ sep
+ labelCat.SegmentedPropertyType.CodingSchemeDesignator
+ sep
+ labelCat.SegmentedPropertyType.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifierCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyTypeModifier.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifierCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyTypeModifier.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifierCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.SegmentedPropertyTypeModifier.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetSegmentedPropertyTypeModifier(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.SegmentedPropertyTypeModifier.CodeValue
+ sep
+ labelCat.SegmentedPropertyTypeModifier.CodingSchemeDesignator
+ sep
+ labelCat.SegmentedPropertyTypeModifier.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegion.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegion.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegion.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegion(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.AnatomicRegion.CodeValue
+ sep
+ labelCat.AnatomicRegion.CodingSchemeDesignator
+ sep
+ labelCat.AnatomicRegion.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifierCodeValue(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegionModifier.CodeValue;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifierCodeMeaning(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegionModifier.CodeMeaning;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifierCodingSchemeDesignator(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
returnString = labelCat.AnatomicRegionModifier.CodingSchemeDesignator;
}
return returnString;
}
//----------------------------------------------------------------------------
std::string vtkMRMLColorLogic::GetAnatomicRegionModifier(int label, const char *lutName)
{
std::string returnString;
ColorLabelCategorization labelCat;
if (this->LookupCategorizationFromLabel(label, labelCat, lutName))
{
std::string sep = std::string(":");
returnString = labelCat.AnatomicRegionModifier.CodeValue
+ sep
+ labelCat.AnatomicRegionModifier.CodingSchemeDesignator
+ sep
+ labelCat.AnatomicRegionModifier.CodeMeaning;
if (returnString.compare("::") == 0)
{
// reset it to an empty string
returnString = "";
}
}
return returnString;
}
| 62,613 | 18,956 |
//
// CameraGoToPositionEffect.hpp
// G3MiOSSDK
//
// Created by José Miguel S N on 24/10/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef G3MiOSSDK_CameraGoToPositionEffect
#define G3MiOSSDK_CameraGoToPositionEffect
#include "Geodetic3D.hpp"
class CameraGoToPositionEffect : public EffectWithDuration {
private:
const Geodetic3D _fromPosition;
const Geodetic3D _toPosition;
const Angle _fromHeading;
const Angle _toHeading;
const Angle _fromPitch;
const Angle _toPitch;
const bool _linearHeight;
double _middleHeight;
double calculateMaxHeight(const Planet* planet) {
// curve parameters
const double distanceInDegreesMaxHeight = 180;
const double maxHeight = planet->getRadii().axisAverage() * 5;
// rough estimation of distance using lat/lon degrees
const double deltaLatInDeg = _fromPosition._latitude._degrees - _toPosition._latitude._degrees;
const double deltaLonInDeg = _fromPosition._longitude._degrees - _toPosition._longitude._degrees;
const double distanceInDeg = IMathUtils::instance()->sqrt((deltaLatInDeg * deltaLatInDeg) +
(deltaLonInDeg * deltaLonInDeg));
if (distanceInDeg >= distanceInDegreesMaxHeight) {
return maxHeight;
}
const double middleHeight = (distanceInDeg / distanceInDegreesMaxHeight) * maxHeight;
const double averageHeight = (_fromPosition._height + _toPosition._height) / 2;
if (middleHeight < averageHeight) {
const double delta = (averageHeight - middleHeight) / 2.0;
return averageHeight + delta;
}
// const double averageHeight = (_fromPosition._height + _toPosition._height) / 2;
// if (middleHeight < averageHeight) {
// return (averageHeight + middleHeight) / 2.0;
// }
return middleHeight;
}
public:
CameraGoToPositionEffect(const TimeInterval& duration,
const Geodetic3D& fromPosition,
const Geodetic3D& toPosition,
const Angle& fromHeading,
const Angle& toHeading,
const Angle& fromPitch,
const Angle& toPitch,
const bool linearTiming,
const bool linearHeight):
EffectWithDuration(duration, linearTiming),
_fromPosition(fromPosition),
_toPosition(toPosition),
_fromHeading(fromHeading),
_toHeading(toHeading),
_fromPitch(fromPitch),
_toPitch(toPitch),
_linearHeight(linearHeight)
{
}
void doStep(const G3MRenderContext* rc,
const TimeInterval& when) {
const double alpha = getAlpha(when);
double height;
if (_linearHeight) {
height = IMathUtils::instance()->linearInterpolation(_fromPosition._height,
_toPosition._height,
alpha);
}
else {
height = IMathUtils::instance()->quadraticBezierInterpolation(_fromPosition._height,
_middleHeight,
_toPosition._height,
alpha);
}
Camera *camera = rc->getNextCamera();
camera->setGeodeticPosition(Angle::linearInterpolation(_fromPosition._latitude, _toPosition._latitude, alpha),
Angle::linearInterpolation(_fromPosition._longitude, _toPosition._longitude, alpha),
height);
const Angle heading = Angle::linearInterpolation(_fromHeading, _toHeading, alpha);
camera->setHeading(heading);
const Angle middlePitch = Angle::fromDegrees(-90);
// const Angle pitch = (alpha < 0.5)
// ? Angle::linearInterpolation(_fromPitch, middlePitch, alpha*2)
// : Angle::linearInterpolation(middlePitch, _toPitch, (alpha-0.5)*2);
if (alpha <= 0.1) {
camera->setPitch( Angle::linearInterpolation(_fromPitch, middlePitch, alpha*10) );
}
else if (alpha >= 0.9) {
camera->setPitch( Angle::linearInterpolation(middlePitch, _toPitch, (alpha-0.9)*10) );
}
else {
camera->setPitch(middlePitch);
}
}
void stop(const G3MRenderContext* rc,
const TimeInterval& when) {
Camera* camera = rc->getNextCamera();
camera->setGeodeticPosition(_toPosition);
camera->setPitch(_toPitch);
camera->setHeading(_toHeading);
}
void cancel(const TimeInterval& when) {
// do nothing, just leave the effect in the intermediate state
}
void start(const G3MRenderContext* rc,
const TimeInterval& when) {
EffectWithDuration::start(rc, when);
_middleHeight = calculateMaxHeight(rc->getPlanet());
}
};
#endif
| 4,933 | 1,455 |
// Copyright 2013 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 "cc/test/test_in_process_context_provider.h"
#include "base/lazy_instance.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gl_in_process_context.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "gpu/command_buffer/client/gles2_lib.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"
#include "gpu/skia_bindings/gl_bindings_skia_cmd_buffer.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
#include "ui/gfx/native_widget_types.h"
namespace cc {
// static
scoped_ptr<gpu::GLInProcessContext> CreateTestInProcessContext() {
const bool is_offscreen = true;
const bool share_resources = true;
gpu::gles2::ContextCreationAttribHelper attribs;
attribs.alpha_size = 8;
attribs.blue_size = 8;
attribs.green_size = 8;
attribs.red_size = 8;
attribs.depth_size = 24;
attribs.stencil_size = 8;
attribs.samples = 0;
attribs.sample_buffers = 0;
attribs.fail_if_major_perf_caveat = false;
attribs.bind_generates_resource = false;
gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu;
scoped_ptr<gpu::GLInProcessContext> context =
make_scoped_ptr(gpu::GLInProcessContext::Create(
NULL,
NULL,
is_offscreen,
gfx::kNullAcceleratedWidget,
gfx::Size(1, 1),
NULL,
share_resources,
attribs,
gpu_preference,
gpu::GLInProcessContextSharedMemoryLimits()));
DCHECK(context);
return context.Pass();
}
TestInProcessContextProvider::TestInProcessContextProvider()
: context_(CreateTestInProcessContext()) {}
TestInProcessContextProvider::~TestInProcessContextProvider() {
}
bool TestInProcessContextProvider::BindToCurrentThread() { return true; }
gpu::gles2::GLES2Interface* TestInProcessContextProvider::ContextGL() {
return context_->GetImplementation();
}
gpu::ContextSupport* TestInProcessContextProvider::ContextSupport() {
return context_->GetImplementation();
}
namespace {
// Singleton used to initialize and terminate the gles2 library.
class GLES2Initializer {
public:
GLES2Initializer() { ::gles2::Initialize(); }
~GLES2Initializer() { ::gles2::Terminate(); }
private:
DISALLOW_COPY_AND_ASSIGN(GLES2Initializer);
};
static base::LazyInstance<GLES2Initializer> g_gles2_initializer =
LAZY_INSTANCE_INITIALIZER;
} // namespace
static void BindGrContextCallback(const GrGLInterface* interface) {
TestInProcessContextProvider* context_provider =
reinterpret_cast<TestInProcessContextProvider*>(interface->fCallbackData);
gles2::SetGLContext(context_provider->ContextGL());
}
class GrContext* TestInProcessContextProvider::GrContext() {
if (gr_context_)
return gr_context_.get();
// The GrGLInterface factory will make GL calls using the C GLES2 interface.
// Make sure the gles2 library is initialized first on exactly one thread.
g_gles2_initializer.Get();
gles2::SetGLContext(ContextGL());
skia::RefPtr<GrGLInterface> interface =
skia::AdoptRef(skia_bindings::CreateCommandBufferSkiaGLBinding());
interface->fCallback = BindGrContextCallback;
interface->fCallbackData = reinterpret_cast<GrGLInterfaceCallbackData>(this);
gr_context_ = skia::AdoptRef(GrContext::Create(
kOpenGL_GrBackend, reinterpret_cast<GrBackendContext>(interface.get())));
return gr_context_.get();
}
ContextProvider::Capabilities
TestInProcessContextProvider::ContextCapabilities() {
return ContextProvider::Capabilities();
}
bool TestInProcessContextProvider::IsContextLost() { return false; }
void TestInProcessContextProvider::VerifyContexts() {}
void TestInProcessContextProvider::DeleteCachedResources() {
if (gr_context_)
gr_context_->freeGpuResources();
}
bool TestInProcessContextProvider::DestroyedOnMainThread() { return false; }
void TestInProcessContextProvider::SetLostContextCallback(
const LostContextCallback& lost_context_callback) {}
void TestInProcessContextProvider::SetMemoryPolicyChangedCallback(
const MemoryPolicyChangedCallback& memory_policy_changed_callback) {}
} // namespace cc
| 4,402 | 1,455 |
#include <iostream>
#include "machine.h"
/**
* @file
* @brief Address transfer operations.
*/
namespace mixal {
/** Increase rA or rX by the address value.
*
* @see overflow
*/
void Computer::executeINC(const InstructionWord& instruction, Register5* reg) {
int32_t value = reg->value();
int32_t address = getIndexedAddress(instruction);
value += address;
reg->set(checkRange(value));
}
/** Decrease rA or rX by the address value.
*
* @see overflow
*/
void Computer::executeDEC(const InstructionWord& instruction, Register5* reg) {
int32_t value = reg->value();
int32_t address = getIndexedAddress(instruction);
value -= address;
reg->set(checkRange(value));
}
/** Enter the immediate address value to rA or rX. */
void Computer::executeENT(const InstructionWord& instruction, Register5* reg) {
int32_t address = getIndexedAddress(instruction);
reg->set(address);
if (address == 0) {
reg->negative = instruction.negative;
}
}
/** Enter the negative immediate address value to rA or rX. */
void Computer::executeENN(const InstructionWord& instruction, Register5* reg) {
int32_t address = getIndexedAddress(instruction);
reg->set(-address);
if (address == 0) {
reg->negative = !instruction.negative;
}
}
/** Increase rI by the address value. */
void Computer::executeINCi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t value = rIi.value();
int16_t address = getIndexedAddress(instruction);
value += address;
rIi.set(checkRange(value, 2));
}
/** Decrease rI by the address value. */
void Computer::executeDECi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t value = rIi.value();
int16_t address = getIndexedAddress(instruction);
value -= address;
rIi.set(checkRange(value, 2));
}
/** Enter address value to rI. */
void Computer::executeENTi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t address = getIndexedAddress(instruction);
rIi.set(checkRange(address, 2));
if (address == 0) {
rIi.negative = instruction.negative;
}
}
/** Enter negative address value to rI. */
void Computer::executeENNi(const InstructionWord& instruction) {
int registerIndex = instruction.operation() - Instructions::INC1 + 1;
auto& rIi = rI(registerIndex);
int16_t address = getIndexedAddress(instruction);
rIi.set(checkRange(-address, 2));
if (address == 0) {
rIi.negative = !instruction.negative;
}
}
}; // namespace mixal
| 2,811 | 911 |
/***********************************************************************************
** MIT License **
** **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) **
** **
** Permission is hereby granted, free of charge, to any person obtaining a copy **
** of this software and associated documentation files (the "Software"), to deal **
** in the Software without restriction, including without limitation the rights **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell **
** copies of the Software, and to permit persons to whom the Software is **
** furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE **
** SOFTWARE. **
***********************************************************************************/
#include "SiteIcon.hpp"
#include "Web/WebView.hpp"
#include "Widgets/AddressBar/AddressBar.hpp"
#include "Widgets/SiteInfo.hpp"
#include "Widgets/SiteInfoWidget.hpp"
#include "BrowserWindow.hpp"
#include "Application.hpp"
namespace Sn {
SiteIcon::SiteIcon(BrowserWindow* window, Sn::AddressBar* parent) :
ToolButton(parent),
m_window(window),
m_addressBar(parent)
{
setObjectName(QLatin1String("addressbar-siteicon"));
setToolButtonStyle(Qt::ToolButtonIconOnly);
setCursor(Qt::ArrowCursor);
setToolTip(AddressBar::tr("Show information about this page"));
setFocusPolicy(Qt::ClickFocus);
}
SiteIcon::~SiteIcon()
{
// Empty
}
void SiteIcon::setWebView(Sn::WebView* view)
{
m_view = view;
}
void SiteIcon::updateIcon(bool secure)
{
if (secure)
ToolButton::setIcon(Application::getAppIcon("locked"));
else
ToolButton::setIcon(Application::getAppIcon("nonlocked"));
}
void SiteIcon::popupClosed()
{
setDown(false);
}
void SiteIcon::contextMenuEvent(QContextMenuEvent* event)
{
// It's just to prevent the propagation to the address bar
event->accept();
}
void SiteIcon::mouseReleaseEvent(QMouseEvent* event)
{
bool activated = false;
if (event->button() == Qt::LeftButton && rect().contains(event->pos()))
activated = showPopup();
if (activated)
setUpdatesEnabled(false);
ToolButton::mouseReleaseEvent(event);
if (activated) {
setDown(true);
setUpdatesEnabled(true);
}
}
bool SiteIcon::showPopup()
{
if (!m_view || !m_window)
return false;
QUrl url{m_view->url()};
if (!SiteInfo::canShowSiteInfo(url))
return false;
setDown(true);
SiteInfoWidget* info{new SiteInfoWidget(m_window)};
info->showAt(parentWidget());
connect(info, &SiteInfoWidget::destroyed, this, &SiteIcon::popupClosed);
return true;
}
} | 3,723 | 1,098 |
#include <time.h>
#include "TimeValue.h"
namespace Kriti {
TimeValue TimeValue::current() {
struct timespec current;
clock_gettime(CLOCK_MONOTONIC, ¤t);
return current.tv_nsec + current.tv_sec*1000000000;
}
} // namespace Kriti
| 252 | 98 |
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#undef OATPP_MACRO_API_CONTROLLER_PARAM_MACRO
#undef OATPP_MACRO_API_CONTROLLER_PARAM_INFO
#undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE
#undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME
#undef OATPP_MACRO_API_CONTROLLER_PARAM_TYPE_STR
#undef OATPP_MACRO_API_CONTROLLER_PARAM_NAME_STR
#undef OATPP_MACRO_API_CONTROLLER_PARAM
#undef REQUEST
#undef HEADER
#undef PATH
#undef QUERIES
#undef QUERY
#undef BODY_STRING
#undef BODY_DTO
// INIT // ------------------------------------------------------
#undef REST_CONTROLLER_INIT
#undef OATPP_MACRO_API_CONTROLLER_MACRO_SELECTOR
// REQUEST MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_REQUEST
#undef OATPP_MACRO_API_CONTROLLER_REQUEST_INFO
// HEADER MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_HEADER_1
#undef OATPP_MACRO_API_CONTROLLER_HEADER_2
#undef OATPP_MACRO_API_CONTROLLER_HEADER
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_1
#undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO_2
#undef OATPP_MACRO_API_CONTROLLER_HEADER_INFO
// PATH MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_PATH_1
#undef OATPP_MACRO_API_CONTROLLER_PATH_2
#undef OATPP_MACRO_API_CONTROLLER_PATH
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_1
#undef OATPP_MACRO_API_CONTROLLER_PATH_INFO_2
#undef OATPP_MACRO_API_CONTROLLER_PATH_INFO
// QUERIES MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_QUERIES
#undef OATPP_MACRO_API_CONTROLLER_QUERIES_INFO
// QUERY MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_QUERY_1
#undef OATPP_MACRO_API_CONTROLLER_QUERY_2
#undef OATPP_MACRO_API_CONTROLLER_QUERY
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_1
#undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO_2
#undef OATPP_MACRO_API_CONTROLLER_QUERY_INFO
// BODY_STRING MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_BODY_STRING
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_BODY_STRING_INFO
// BODY_DTO MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_BODY_DTO
// __INFO
#undef OATPP_MACRO_API_CONTROLLER_BODY_DTO_INFO
// FOR EACH // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_DECL
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_PUT
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_CALL
#undef OATPP_MACRO_API_CONTROLLER_FOR_EACH_PARAM_INFO
// ENDPOINT_INFO MACRO // ------------------------------------------------------
#undef ENDPOINT_INFO
// ENDPOINT MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_DEFAULTS
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_0
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_0
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_DECL_1
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_1
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_0
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_MACRO_1
#undef ENDPOINT
#undef ENDPOINT_INTERCEPTOR
// ENDPOINT ASYNC MACRO // ------------------------------------------------------
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL_DEFAULTS
#undef OATPP_MACRO_API_CONTROLLER_ENDPOINT_ASYNC_DECL
#undef ENDPOINT_ASYNC
#undef ENDPOINT_ASYNC_INIT
#undef ENDPOINT_INTERCEPTOR_ASYNC
| 4,471 | 1,824 |
// ==========================================================
// PNG Loader and Writer
//
// Design and implementation by
// - Floris van den Berg (flvdberg@wxs.nl)
// - Herve Drolon (drolon@infonie.fr)
// - Detlev Vendt (detlev.vendt@brillit.de)
// - Aaron Shumate (trek@startreker.com)
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
#ifdef _MSC_VER
#pragma warning (disable : 4786) // identifier was truncated to 'number' characters
#endif
#include "FreeImage.h"
#include "Utilities.h"
#include "../Metadata/FreeImageTag.h"
// ----------------------------------------------------------
#define PNG_BYTES_TO_CHECK 8
// ----------------------------------------------------------
#include "../LibPNG/png.h"
// ----------------------------------------------------------
typedef struct {
FreeImageIO *s_io;
fi_handle s_handle;
} fi_ioStructure, *pfi_ioStructure;
/////////////////////////////////////////////////////////////////////////////
// libpng interface
//
static void
_ReadProc(png_structp png_ptr, unsigned char *data, png_size_t size) {
pfi_ioStructure pfio = (pfi_ioStructure)png_get_io_ptr(png_ptr);
unsigned n = pfio->s_io->read_proc(data, (unsigned int)size, 1, pfio->s_handle);
if(size && (n == 0)) {
throw "Read error: invalid or corrupted PNG file";
}
}
static void
_WriteProc(png_structp png_ptr, unsigned char *data, png_size_t size) {
pfi_ioStructure pfio = (pfi_ioStructure)png_get_io_ptr(png_ptr);
pfio->s_io->write_proc(data, (unsigned int)size, 1, pfio->s_handle);
}
static void
_FlushProc(png_structp png_ptr) {
// empty flush implementation
}
static void
error_handler(png_structp png_ptr, const char *error) {
throw error;
}
// in FreeImage warnings disabled
static void
warning_handler(png_structp png_ptr, const char *warning) {
}
// ==========================================================
// Metadata routines
// ==========================================================
static BOOL
ReadMetadata(png_structp png_ptr, png_infop info_ptr, FIBITMAP *dib) {
// XMP keyword
char *g_png_xmp_keyword = "XML:com.adobe.xmp";
FITAG *tag = NULL;
png_textp text_ptr = NULL;
int num_text = 0;
// iTXt/tEXt/zTXt chuncks
if(png_get_text(png_ptr, info_ptr, &text_ptr, &num_text) > 0) {
for(int i = 0; i < num_text; i++) {
// create a tag
tag = FreeImage_CreateTag();
if(!tag) return FALSE;
DWORD tag_length = (DWORD) MAX(text_ptr[i].text_length, text_ptr[i].itxt_length);
FreeImage_SetTagLength(tag, tag_length);
FreeImage_SetTagCount(tag, tag_length);
FreeImage_SetTagType(tag, FIDT_ASCII);
FreeImage_SetTagValue(tag, text_ptr[i].text);
if(strcmp(text_ptr[i].key, g_png_xmp_keyword) == 0) {
// store the tag as XMP
FreeImage_SetTagKey(tag, g_TagLib_XMPFieldName);
FreeImage_SetMetadata(FIMD_XMP, dib, FreeImage_GetTagKey(tag), tag);
} else {
// store the tag as a comment
FreeImage_SetTagKey(tag, text_ptr[i].key);
FreeImage_SetMetadata(FIMD_COMMENTS, dib, FreeImage_GetTagKey(tag), tag);
}
// destroy the tag
FreeImage_DeleteTag(tag);
}
}
return TRUE;
}
static BOOL
WriteMetadata(png_structp png_ptr, png_infop info_ptr, FIBITMAP *dib) {
// XMP keyword
char *g_png_xmp_keyword = "XML:com.adobe.xmp";
FITAG *tag = NULL;
FIMETADATA *mdhandle = NULL;
BOOL bResult = TRUE;
png_text text_metadata;
// set the 'Comments' metadata as iTXt chuncks
mdhandle = FreeImage_FindFirstMetadata(FIMD_COMMENTS, dib, &tag);
if(mdhandle) {
do {
memset(&text_metadata, 0, sizeof(png_text));
text_metadata.compression = 1; // iTXt, none
text_metadata.key = (char*)FreeImage_GetTagKey(tag); // keyword, 1-79 character description of "text"
text_metadata.text = (char*)FreeImage_GetTagValue(tag); // comment, may be an empty string (ie "")
text_metadata.text_length = FreeImage_GetTagLength(tag);// length of the text string
text_metadata.itxt_length = FreeImage_GetTagLength(tag);// length of the itxt string
text_metadata.lang = 0; // language code, 0-79 characters or a NULL pointer
text_metadata.lang_key = 0; // keyword translated UTF-8 string, 0 or more chars or a NULL pointer
// set the tag
png_set_text(png_ptr, info_ptr, &text_metadata, 1);
} while(FreeImage_FindNextMetadata(mdhandle, &tag));
FreeImage_FindCloseMetadata(mdhandle);
bResult &= TRUE;
}
// set the 'XMP' metadata as iTXt chuncks
tag = NULL;
FreeImage_GetMetadata(FIMD_XMP, dib, g_TagLib_XMPFieldName, &tag);
if(tag && FreeImage_GetTagLength(tag)) {
memset(&text_metadata, 0, sizeof(png_text));
text_metadata.compression = 1; // iTXt, none
text_metadata.key = g_png_xmp_keyword; // keyword, 1-79 character description of "text"
text_metadata.text = (char*)FreeImage_GetTagValue(tag); // comment, may be an empty string (ie "")
text_metadata.text_length = FreeImage_GetTagLength(tag);// length of the text string
text_metadata.itxt_length = FreeImage_GetTagLength(tag);// length of the itxt string
text_metadata.lang = 0; // language code, 0-79 characters or a NULL pointer
text_metadata.lang_key = 0; // keyword translated UTF-8 string, 0 or more chars or a NULL pointer
// set the tag
png_set_text(png_ptr, info_ptr, &text_metadata, 1);
bResult &= TRUE;
}
return bResult;
}
// ==========================================================
// Plugin Interface
// ==========================================================
static int s_format_id;
// ==========================================================
// Plugin Implementation
// ==========================================================
static const char * DLL_CALLCONV
Format() {
return "PNG";
}
static const char * DLL_CALLCONV
Description() {
return "Portable Network Graphics";
}
static const char * DLL_CALLCONV
Extension() {
return "png";
}
static const char * DLL_CALLCONV
RegExpr() {
return "^.PNG\r";
}
static const char * DLL_CALLCONV
MimeType() {
return "image/png";
}
static BOOL DLL_CALLCONV
Validate(FreeImageIO *io, fi_handle handle) {
BYTE png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
BYTE signature[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
io->read_proc(&signature, 1, 8, handle);
return (memcmp(png_signature, signature, 8) == 0);
}
static BOOL DLL_CALLCONV
SupportsExportDepth(int depth) {
return (
(depth == 1) ||
(depth == 4) ||
(depth == 8) ||
(depth == 24) ||
(depth == 32)
);
}
static BOOL DLL_CALLCONV
SupportsExportType(FREE_IMAGE_TYPE type) {
return (
(type == FIT_BITMAP) ||
(type == FIT_UINT16) ||
(type == FIT_RGB16) ||
(type == FIT_RGBA16)
);
}
static BOOL DLL_CALLCONV
SupportsICCProfiles() {
return TRUE;
}
// ----------------------------------------------------------
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
png_structp png_ptr = NULL;
png_infop info_ptr;
png_uint_32 width, height;
png_colorp png_palette = NULL;
int color_type, palette_entries = 0;
int bit_depth, pixel_depth; // pixel_depth = bit_depth * channels
FIBITMAP *dib = NULL;
RGBQUAD *palette = NULL; // pointer to dib palette
png_bytepp row_pointers = NULL;
int i;
fi_ioStructure fio;
fio.s_handle = handle;
fio.s_io = io;
if (handle) {
try {
// check to see if the file is in fact a PNG file
BYTE png_check[PNG_BYTES_TO_CHECK];
io->read_proc(png_check, PNG_BYTES_TO_CHECK, 1, handle);
if (png_sig_cmp(png_check, (png_size_t)0, PNG_BYTES_TO_CHECK) != 0)
return NULL; // Bad signature
// create the chunk manage structure
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, error_handler, warning_handler);
if (!png_ptr)
return NULL;
// create the info structure
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
return NULL;
}
// init the IO
png_set_read_fn(png_ptr, &fio, _ReadProc);
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return NULL;
}
// because we have already read the signature...
png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK);
// read the IHDR chunk
png_read_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL);
pixel_depth = info_ptr->pixel_depth;
// get image data type (assume standard image type)
FREE_IMAGE_TYPE image_type = FIT_BITMAP;
if (bit_depth == 16) {
if ((pixel_depth == 16) && (color_type == PNG_COLOR_TYPE_GRAY)) {
image_type = FIT_UINT16;
}
else if ((pixel_depth == 48) && (color_type == PNG_COLOR_TYPE_RGB)) {
image_type = FIT_RGB16;
}
else if ((pixel_depth == 64) && (color_type == PNG_COLOR_TYPE_RGB_ALPHA)) {
image_type = FIT_RGBA16;
} else {
// tell libpng to strip 16 bit/color files down to 8 bits/color
png_set_strip_16(png_ptr);
bit_depth = 8;
}
}
#ifndef FREEIMAGE_BIGENDIAN
if((image_type == FIT_UINT16) || (image_type == FIT_RGB16) || (image_type == FIT_RGBA16)) {
// turn on 16 bit byte swapping
png_set_swap(png_ptr);
}
#endif
// set some additional flags
switch(color_type) {
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_RGB_ALPHA:
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip the RGB pixels to BGR (or RGBA to BGRA)
if(image_type == FIT_BITMAP)
png_set_bgr(png_ptr);
#endif
break;
case PNG_COLOR_TYPE_PALETTE:
// expand palette images to the full 8 bits from 2 bits/pixel
if (pixel_depth == 2) {
png_set_packing(png_ptr);
pixel_depth = 8;
}
break;
case PNG_COLOR_TYPE_GRAY:
// expand grayscale images to the full 8 bits from 2 bits/pixel
// but *do not* expand fully transparent palette entries to a full alpha channel
if (pixel_depth == 2) {
png_set_expand_gray_1_2_4_to_8(png_ptr);
pixel_depth = 8;
}
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
// expand 8-bit greyscale + 8-bit alpha to 32-bit
png_set_gray_to_rgb(png_ptr);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip the RGBA pixels to BGRA
png_set_bgr(png_ptr);
#endif
pixel_depth = 32;
break;
default:
throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
}
// Get the background color to draw transparent and alpha images over.
// Note that even if the PNG file supplies a background, you are not required to
// use it - you should use the (solid) application background if it has one.
png_color_16p image_background = NULL;
RGBQUAD rgbBkColor;
if (png_get_bKGD(png_ptr, info_ptr, &image_background)) {
rgbBkColor.rgbRed = (BYTE)image_background->red;
rgbBkColor.rgbGreen = (BYTE)image_background->green;
rgbBkColor.rgbBlue = (BYTE)image_background->blue;
rgbBkColor.rgbReserved = 0;
}
// unlike the example in the libpng documentation, we have *no* idea where
// this file may have come from--so if it doesn't have a file gamma, don't
// do any correction ("do no harm")
double gamma = 0;
double screen_gamma = 2.2;
if (png_get_gAMA(png_ptr, info_ptr, &gamma) && ( flags & PNG_IGNOREGAMMA ) != PNG_IGNOREGAMMA)
png_set_gamma(png_ptr, screen_gamma, gamma);
// all transformations have been registered; now update info_ptr data
png_read_update_info(png_ptr, info_ptr);
// color type may have changed, due to our transformations
color_type = png_get_color_type(png_ptr,info_ptr);
// create a DIB and write the bitmap header
// set up the DIB palette, if needed
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
png_set_invert_alpha(png_ptr);
if(image_type == FIT_BITMAP) {
dib = FreeImage_Allocate(width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
} else {
dib = FreeImage_AllocateT(image_type, width, height, pixel_depth);
}
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
if(image_type == FIT_BITMAP) {
dib = FreeImage_Allocate(width, height, 32, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
} else {
dib = FreeImage_AllocateT(image_type, width, height, pixel_depth);
}
break;
case PNG_COLOR_TYPE_PALETTE:
dib = FreeImage_Allocate(width, height, pixel_depth);
png_get_PLTE(png_ptr,info_ptr, &png_palette,&palette_entries);
palette = FreeImage_GetPalette(dib);
// store the palette
for (i = 0; i < palette_entries; i++) {
palette[i].rgbRed = png_palette[i].red;
palette[i].rgbGreen = png_palette[i].green;
palette[i].rgbBlue = png_palette[i].blue;
}
// store the transparency table
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
int num_trans = 0;
png_bytep trans = NULL;
png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
FreeImage_SetTransparencyTable(dib, (BYTE *)trans, num_trans);
}
break;
case PNG_COLOR_TYPE_GRAY:
dib = FreeImage_AllocateT(image_type, width, height, pixel_depth);
if(pixel_depth <= 8) {
palette = FreeImage_GetPalette(dib);
palette_entries = 1 << pixel_depth;
for (i = 0; i < palette_entries; i++) {
palette[i].rgbRed =
palette[i].rgbGreen =
palette[i].rgbBlue = (BYTE)((i * 255) / (palette_entries - 1));
}
}
// store the transparency table
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_color_16p trans_values = NULL;
png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_values);
if(trans_values) {
if (trans_values->gray < palette_entries) {
BYTE table[256];
memset(table, 0xFF, palette_entries);
table[trans_values->gray] = 0;
FreeImage_SetTransparencyTable(dib, table, palette_entries);
}
}
}
break;
default:
throw FI_MSG_ERROR_UNSUPPORTED_FORMAT;
}
// store the background color
if(image_background) {
FreeImage_SetBackgroundColor(dib, &rgbBkColor);
}
// get physical resolution
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_pHYs)) {
png_uint_32 res_x, res_y;
// we'll overload this var and use 0 to mean no phys data,
// since if it's not in meters we can't use it anyway
int res_unit_type = 0;
png_get_pHYs(png_ptr,info_ptr,&res_x,&res_y,&res_unit_type);
if (res_unit_type == 1) {
FreeImage_SetDotsPerMeterX(dib, res_x);
FreeImage_SetDotsPerMeterY(dib, res_y);
}
}
// get possible ICC profile
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
png_charp profile_name = NULL;
png_charp profile_data = NULL;
png_uint_32 profile_length = 0;
int compression_type;
png_get_iCCP(png_ptr, info_ptr, &profile_name, &compression_type, &profile_data, &profile_length);
// copy ICC profile data (must be done after FreeImage_Allocate)
FreeImage_CreateICCProfile(dib, profile_data, profile_length);
}
// set the individual row_pointers to point at the correct offsets
row_pointers = (png_bytepp)malloc(height * sizeof(png_bytep));
if (!row_pointers) {
if (palette)
png_free(png_ptr, palette);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
FreeImage_Unload(dib);
return NULL;
}
// read in the bitmap bits via the pointer table
for (png_uint_32 k = 0; k < height; k++)
row_pointers[height - 1 - k] = FreeImage_GetScanLine(dib, k);
png_read_image(png_ptr, row_pointers);
// check if the bitmap contains transparency, if so enable it in the header
if (FreeImage_GetBPP(dib) == 32)
if (FreeImage_GetColorType(dib) == FIC_RGBALPHA)
FreeImage_SetTransparent(dib, TRUE);
else
FreeImage_SetTransparent(dib, FALSE);
// cleanup
if (row_pointers) {
free(row_pointers);
row_pointers = NULL;
}
// read the rest of the file, getting any additional chunks in info_ptr
png_read_end(png_ptr, info_ptr);
// get possible metadata (it can be located both before and after the image data)
ReadMetadata(png_ptr, info_ptr, dib);
if (png_ptr) {
// clean up after the read, and free any memory allocated - REQUIRED
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
}
return dib;
} catch (const char *text) {
if (png_ptr)
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
if (row_pointers)
free(row_pointers);
if (dib)
FreeImage_Unload(dib);
FreeImage_OutputMessageProc(s_format_id, text);
return NULL;
}
}
return NULL;
}
static BOOL DLL_CALLCONV
Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette = NULL;
png_uint_32 width, height;
BOOL has_alpha_channel = FALSE;
RGBQUAD *pal; // pointer to dib palette
int bit_depth, pixel_depth; // pixel_depth = bit_depth * channels
int palette_entries;
int interlace_type;
fi_ioStructure fio;
fio.s_handle = handle;
fio.s_io = io;
if ((dib) && (handle)) {
try {
// create the chunk manage structure
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, error_handler, warning_handler);
if (!png_ptr) {
return FALSE;
}
// allocate/initialize the image information data.
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
return FALSE;
}
// Set error handling. REQUIRED if you aren't supplying your own
// error handling functions in the png_create_write_struct() call.
if (setjmp(png_jmpbuf(png_ptr))) {
// if we get here, we had a problem reading the file
png_destroy_write_struct(&png_ptr, &info_ptr);
return FALSE;
}
// init the IO
png_set_write_fn(png_ptr, &fio, _WriteProc, _FlushProc);
// set physical resolution
png_uint_32 res_x = (png_uint_32)FreeImage_GetDotsPerMeterX(dib);
png_uint_32 res_y = (png_uint_32)FreeImage_GetDotsPerMeterY(dib);
if ((res_x > 0) && (res_y > 0)) {
png_set_pHYs(png_ptr, info_ptr, res_x, res_y, 1);
}
// Set the image information here. Width and height are up to 2^31,
// bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
// the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
// PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
// or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
// PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
// currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
width = FreeImage_GetWidth(dib);
height = FreeImage_GetHeight(dib);
pixel_depth = FreeImage_GetBPP(dib);
BOOL bInterlaced = FALSE;
if( (flags & PNG_INTERLACED) == PNG_INTERLACED) {
interlace_type = PNG_INTERLACE_ADAM7;
bInterlaced = TRUE;
} else {
interlace_type = PNG_INTERLACE_NONE;
}
// set the ZLIB compression level or default to PNG default compression level (ZLIB level = 6)
int zlib_level = flags & 0x0F;
if((zlib_level >= 1) && (zlib_level <= 9)) {
png_set_compression_level(png_ptr, zlib_level);
} else if((flags & PNG_Z_NO_COMPRESSION) == PNG_Z_NO_COMPRESSION) {
png_set_compression_level(png_ptr, Z_NO_COMPRESSION);
}
// filtered strategy works better for high color images
if(pixel_depth >= 16){
png_set_compression_strategy(png_ptr, Z_FILTERED);
png_set_filter(png_ptr, 0, PNG_FILTER_NONE|PNG_FILTER_SUB|PNG_FILTER_PAETH);
} else {
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
}
FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(dib);
if(image_type == FIT_BITMAP) {
// standard image type
bit_depth = (pixel_depth > 8) ? 8 : pixel_depth;
} else {
// 16-bit greyscale or 16-bit RGB(A)
bit_depth = 16;
}
switch (FreeImage_GetColorType(dib)) {
case FIC_MINISWHITE:
// Invert monochrome files to have 0 as black and 1 as white (no break here)
png_set_invert_mono(png_ptr);
case FIC_MINISBLACK:
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_GRAY, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
break;
case FIC_PALETTE:
{
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_PALETTE, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
// set the palette
palette_entries = 1 << bit_depth;
palette = (png_colorp)png_malloc(png_ptr, palette_entries * sizeof (png_color));
pal = FreeImage_GetPalette(dib);
for (int i = 0; i < palette_entries; i++) {
palette[i].red = pal[i].rgbRed;
palette[i].green = pal[i].rgbGreen;
palette[i].blue = pal[i].rgbBlue;
}
png_set_PLTE(png_ptr, info_ptr, palette, palette_entries);
// You must not free palette here, because png_set_PLTE only makes a link to
// the palette that you malloced. Wait until you are about to destroy
// the png structure.
break;
}
case FIC_RGBALPHA :
has_alpha_channel = TRUE;
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_RGBA, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip BGR pixels to RGB
if(image_type == FIT_BITMAP)
png_set_bgr(png_ptr);
#endif
break;
case FIC_RGB:
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
PNG_COLOR_TYPE_RGB, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR
// flip BGR pixels to RGB
if(image_type == FIT_BITMAP)
png_set_bgr(png_ptr);
#endif
break;
case FIC_CMYK:
break;
}
// write possible ICC profile
FIICCPROFILE *iccProfile = FreeImage_GetICCProfile(dib);
if (iccProfile->size && iccProfile->data) {
png_set_iCCP(png_ptr, info_ptr, "Embedded Profile", 0, (png_charp)iccProfile->data, iccProfile->size);
}
// write metadata
WriteMetadata(png_ptr, info_ptr, dib);
// Optional gamma chunk is strongly suggested if you have any guess
// as to the correct gamma of the image.
// png_set_gAMA(png_ptr, info_ptr, gamma);
// set the transparency table
if (FreeImage_IsTransparent(dib) && (FreeImage_GetTransparencyCount(dib) > 0)) {
png_set_tRNS(png_ptr, info_ptr, FreeImage_GetTransparencyTable(dib), FreeImage_GetTransparencyCount(dib), NULL);
}
// set the background color
if(FreeImage_HasBackgroundColor(dib)) {
png_color_16 image_background;
RGBQUAD rgbBkColor;
FreeImage_GetBackgroundColor(dib, &rgbBkColor);
memset(&image_background, 0, sizeof(png_color_16));
image_background.blue = rgbBkColor.rgbBlue;
image_background.green = rgbBkColor.rgbGreen;
image_background.red = rgbBkColor.rgbRed;
image_background.index = rgbBkColor.rgbReserved;
png_set_bKGD(png_ptr, info_ptr, &image_background);
}
// Write the file header information.
png_write_info(png_ptr, info_ptr);
// write out the image data
#ifndef FREEIMAGE_BIGENDIAN
if (bit_depth == 16) {
// turn on 16 bit byte swapping
png_set_swap(png_ptr);
}
#endif
int number_passes = 1;
if (bInterlaced) {
number_passes = png_set_interlace_handling(png_ptr);
}
if ((pixel_depth == 32) && (!has_alpha_channel)) {
BYTE *buffer = (BYTE *)malloc(width * 3);
// transparent conversion to 24-bit
// the number of passes is either 1 for non-interlaced images, or 7 for interlaced images
for (int pass = 0; pass < number_passes; pass++) {
for (png_uint_32 k = 0; k < height; k++) {
FreeImage_ConvertLine32To24(buffer, FreeImage_GetScanLine(dib, height - k - 1), width);
png_write_row(png_ptr, buffer);
}
}
free(buffer);
} else {
// the number of passes is either 1 for non-interlaced images, or 7 for interlaced images
for (int pass = 0; pass < number_passes; pass++) {
for (png_uint_32 k = 0; k < height; k++) {
png_write_row(png_ptr, FreeImage_GetScanLine(dib, height - k - 1));
}
}
}
// It is REQUIRED to call this to finish writing the rest of the file
// Bug with png_flush
png_write_end(png_ptr, info_ptr);
// clean up after the write, and free any memory allocated
if (palette) {
png_free(png_ptr, palette);
}
png_destroy_write_struct(&png_ptr, &info_ptr);
return TRUE;
} catch (const char *text) {
FreeImage_OutputMessageProc(s_format_id, text);
}
}
return FALSE;
}
// ==========================================================
// Init
// ==========================================================
void DLL_CALLCONV
InitPNG(Plugin *plugin, int format_id) {
s_format_id = format_id;
plugin->format_proc = Format;
plugin->description_proc = Description;
plugin->extension_proc = Extension;
plugin->regexpr_proc = RegExpr;
plugin->open_proc = NULL;
plugin->close_proc = NULL;
plugin->pagecount_proc = NULL;
plugin->pagecapability_proc = NULL;
plugin->load_proc = Load;
plugin->save_proc = Save;
plugin->validate_proc = Validate;
plugin->mime_proc = MimeType;
plugin->supports_export_bpp_proc = SupportsExportDepth;
plugin->supports_export_type_proc = SupportsExportType;
plugin->supports_icc_profiles_proc = SupportsICCProfiles;
}
| 26,522 | 11,586 |
/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
//using namespace std;
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
//sleep(60);
//::cout << "after sleep\n";
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://meep-mg-manager"));
// Build request URI and start the request.
uri_builder builder(U("/v1/mg/mysrv/app/server"));
//builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::POST, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
//printf("Received response status code:%u\n", response.status_code());
std::cout << "Received response status code: " << response.status_code() << std::endl;
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
//printf("Error exception:%s\n", e.what());
std::cout << "Error exception: " << e.what() << std::endl;
}
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
bool connected = false;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
while(true)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
std::cout << "ERROR opening socket: " << strerror(errno) << std::endl;
}
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
std::cout << "ERROR on binding: " << strerror(errno) << std::endl;
}
std::cout << "listening on port: " << portno << std::endl;
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
std::cout << "ERROR on accept: " << strerror(errno) << std::endl;
}
close(sockfd); // so that no one else can connect until the current connection is closed
connected = true;
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
setsockopt(newsockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
while(connected)
{
bzero(buffer,256);
n = recv(newsockfd,buffer,1,0);
if (n < 0)
{
std::cout << "ERROR reading from socket: " << strerror(errno) << std::endl;
connected = false;
}
std::cout << "count: "<< (int)buffer[0] << std::endl;
buffer[0]++;
n = send(newsockfd,buffer,1,MSG_NOSIGNAL);
if (n < 0)
{
std::cout << "ERROR writing to socket: " << strerror(errno) << std::endl;
connected = false;
}
}
}
close(newsockfd);
close(sockfd);
return 0;
} | 4,249 | 1,551 |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_BITWISE_AND_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_BITWISE_AND_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-bitwise
Function object implementing bitwise_and capabilities
Computes the bitwise and of the two parameters.
The operands must share the same bit size.
The result type is the one of the first operand.
Infix notation can be used with operator '&',
but this will not work in scalar mode if any
operand is floating point because of C++ limitations.
@par Semantic:
For every parameters of @c x of type @c T0, @c y of type @c T1:
@code
T0 r = bitwise_and(x,y);
@endcode
is similar to:
@code
T0 r = x & y;
@endcode
@see bitwise_or, bitwise_xor, bitwise_notand,
bitwise_andnot, bitwise_notor, bitwise_ornot, complement
**/
T0 bitwise_and(T0 const& x, T1 const& y);
} }
#endif
#include <boost/simd/function/scalar/bitwise_and.hpp>
#include <boost/simd/function/simd/bitwise_and.hpp>
#endif
| 1,461 | 488 |
// A Calandar
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const string days[] = {"Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
string date;
ll yy1, yy2, m1, m2, d1, d2, offset;
int main()
{
int T; scanf("%d", &T);
while (T--)
{
scanf("%lld%lld%lld", &yy1, &m1, &d1);
cin >> date;
scanf("%lld%lld%lld", &yy2, &m2, &d2);
offset = (yy2 - yy1) *12 * 30 + (m2 - m1) * 30 + (d2 - d1);
for (int i = 1; i < 6; i++)
{
if (date == days[i])
{
offset += i; break;
}
}
offset = (offset % 5 + 5) % 5;
puts(days[offset].c_str());
}
return 0;
} | 722 | 315 |
//
// Created by zelenyy on 07.12.17.
//
#include "SensitiveDetectorFactory.hh"
#include "SensitiveScoredDetector.hh"
#include "G4SDManager.hh"
using namespace std;
G4VSensitiveDetector *SensitiveDetectorFactory::getSensitiveDetector(G4GDMLAuxListType::const_iterator vit) {
auto name = (*vit).value;
G4SDManager *fSDM = G4SDManager::GetSDMpointer();
G4VSensitiveDetector *tempDetector;
if (name == "SensitiveScoredDetector") {
tempDetector = new SensitiveScoredDetector(name, fSettings);
} else {
tempDetector = IDetectorFactory::getSensitiveDetector(vit);
}
fSDM->AddNewDetector(tempDetector);
G4cout << "Create new detector: " << name << endl;
return tempDetector;
}
| 728 | 268 |
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "if.h"
#include "if_else.h"
#include "switch.h"
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Test is even function")
{
REQUIRE(is_even(2) == true);
}
TEST_CASE("Test get generation function")
{
REQUIRE(get_generation(2010) == "Centenial");
REQUIRE(get_generation(1990) == "Millenial");
REQUIRE(get_generation(1970) == "Generation X");
REQUIRE(get_generation(1950) == "Baby Boomer");
REQUIRE(get_generation(1930) == "Silent Generation");
//REQUIRE(get_generation(1000) == "Invalid Year");
}
TEST_CASE("Test menu function ")
{
REQUIRE(menu(0) == "Invalid Option");
REQUIRE(menu(1) == "Option 1");
REQUIRE(menu(2) == "Option 2");
REQUIRE(menu(3) == "Option 3");
REQUIRE(menu(4) == "Option 4");
REQUIRE(menu(5) == "Invalid Option");
} | 924 | 391 |
/*
* SendMessageAction.cpp
*
* Created on: 3 août 2015
* Author: horfee
*/
#include "SendMessageAction.h"
#include "../Properties.h"
#include <ctime>
#include <locale>
namespace alarmpi {
SendMessageAction::SendMessageAction(std::string name, std::string message, bool synchronous): Action(name, synchronous), message(message) {
}
SendMessageAction::~SendMessageAction() {
}
std::string SendMessageAction::getMessage() const {
return message;
}
void SendMessageAction::execute(Device* device, Mode* mode) {
// if ( !stopAsked() ) {
// setRunning();
size_t pos = message.find("$device");
std::string msg = message;
if ( pos != std::string::npos ) {
msg = message.substr(0, pos) + device->getDescription() + message.substr(pos + std::string("$device").length());
}
pos = msg.find("$mode");
if ( pos != std::string::npos ) {
msg = msg.substr(0, pos) + mode->getName() + msg.substr(pos + std::string("$mode").length());
}
pos = msg.find("$time");
if ( pos != std::string::npos ) {
std::time_t t = std::time(NULL);
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%X", std::localtime(&t));
msg = msg.substr(0, pos) + std::string(mbstr) + msg.substr(pos + std::string("$time").length());
}
pos = msg.find("$date");
if ( pos != std::string::npos ) {
std::time_t t = std::time(NULL);
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%x", std::localtime(&t));
msg = msg.substr(0, pos) + std::string(mbstr) + msg.substr(pos + std::string("$date").length());
}
pos = msg.find("$action.");
if ( pos != std::string::npos ) {
size_t pos2 = msg.find(" ", pos + 8);
std::string val = msg.substr(pos + 8, pos2 - (pos + 8));
Json::Value v = this->toJSON();
Json::Value v2 = v[val];
std::string res;
if ( v2.type() == Json::ValueType::stringValue ) {
res = v2.asString();
} else if ( v2.type() == Json::ValueType::intValue ) {
res = std::to_string(v2.asInt());
} else if ( v2.type() == Json::ValueType::realValue ) {
res = std::to_string(v2.asDouble());
} else if ( v2.type() == Json::ValueType::booleanValue ) {
res = std::to_string(v2.asBool());
} else if ( v2.type() == Json::ValueType::uintValue ) {
res = std::to_string(v2.asUInt());
}
msg = msg.substr(0, pos) + res + msg.substr(pos2);
}
// if ( !stopAsked() ) {
system->sendSMS(msg);
// }
// }
// Action::execute(device, mode);
}
Json::Value SendMessageAction::toJSON() const {
Json::Value res = Action::toJSON();
res["message"] = message;
return res;
}
std::string SendMessageAction::getType() const {
return "SENDMESSAGEACTION";
}
} /* namespace alarmpi */
| 2,658 | 1,064 |
/**
* Copyright (C) 2019-2022 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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.
*/
// ------ I N C L U D E F I L E S -------------------------------------------
// Local - Include Files
#include "SubCmd.h"
#include "XBHelpMenusCore.h"
#include "XBUtilitiesCore.h"
#include "XBHelpMenus.h"
#include "XBMain.h"
#include "XBUtilities.h"
namespace XBU = XBUtilities;
// 3rd Party Library - Include Files
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <cstdlib>
namespace po = boost::program_options;
// System - Include Files
#include <iostream>
// ------ Program entry point -------------------------------------------------
void main_(int argc, char** argv,
const std::string & _executable,
const std::string & _description,
const SubCmdsCollection &_subCmds)
{
bool isUserDomain = boost::iequals(_executable, "xbutil");
// Global options
bool bVerbose = false;
bool bTrace = false;
bool bHelp = false;
bool bBatchMode = false;
bool bShowHidden = false;
bool bForce = false;
bool bVersion = false;
std::string sDevice;
// Build Options
po::options_description globalSubCmdOptions("Global Command Options");
globalSubCmdOptions.add_options()
("verbose", boost::program_options::bool_switch(&bVerbose), "Turn on verbosity")
("batch", boost::program_options::bool_switch(&bBatchMode), "Enable batch mode (disables escape characters)")
("force", boost::program_options::bool_switch(&bForce), "When possible, force an operation")
;
po::options_description globalOptions("Global Options");
globalOptions.add_options()
("help", boost::program_options::bool_switch(&bHelp), "Help to use this application")
("version", boost::program_options::bool_switch(&bVersion), "Report the version of XRT and its drivers")
;
globalOptions.add(globalSubCmdOptions);
// Hidden Options
po::options_description hiddenOptions("Hidden Options");
hiddenOptions.add_options()
("device,d", boost::program_options::value<decltype(sDevice)>(&sDevice)->default_value("")->implicit_value("default"), "If specified with no BDF value and there is only 1 device, that device will be automatically selected.\n")
("trace", boost::program_options::bool_switch(&bTrace), "Enables code flow tracing")
("show-hidden", boost::program_options::bool_switch(&bShowHidden), "Shows hidden options and commands")
("subCmd", po::value<std::string>(), "Command to execute")
("subCmdArgs", po::value<std::vector<std::string> >(), "Arguments for command")
;
// Merge the options to one common collection
po::options_description allOptions("All Options");
allOptions.add(globalOptions).add(hiddenOptions);
// Create a sub-option command and arguments
po::positional_options_description positionalCommand;
positionalCommand.
add("subCmd", 1 /* max_count */).
add("subCmdArgs", -1 /* Unlimited max_count */);
// -- Parse the command line
po::parsed_options parsed = po::command_line_parser(argc, argv).
options(allOptions). // Global options
positional(positionalCommand). // Our commands
allow_unregistered(). // Allow for unregistered options (needed for sub options)
run(); // Parse the options
po::variables_map vm;
try {
po::store(parsed, vm); // Can throw
po::notify(vm); // Can throw
} catch (po::error& e) {
// Something bad happen with parsing our options
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
XBU::report_commands_help(_executable, _description, globalOptions, hiddenOptions, _subCmds);
throw xrt_core::error(std::errc::operation_canceled);
}
if(bVersion) {
std::cout << XBU::get_xrt_pretty_version();
return;
}
// -- Enable/Disable helper "global" options
XBU::disable_escape_codes( bBatchMode );
XBU::setVerbose( bVerbose );
XBU::setTrace( bTrace );
XBU::setShowHidden( bShowHidden );
XBU::setForce( bForce );
// Check to see if help was requested and no command was found
if (vm.count("subCmd") == 0) {
XBU::report_commands_help( _executable, _description, globalOptions, hiddenOptions, _subCmds);
return;
}
// -- Now see if there is a command to work with
// Get the command of choice
std::string sCommand = vm["subCmd"].as<std::string>();
// Search for the subcommand (case sensitive)
std::shared_ptr<SubCmd> subCommand;
for (auto & subCmdEntry : _subCmds) {
if (sCommand.compare(subCmdEntry->getName()) == 0) {
subCommand = subCmdEntry;
break;
}
}
if ( !subCommand) {
std::cerr << "ERROR: " << "Unknown command: '" << sCommand << "'" << std::endl;
XBU::report_commands_help( _executable, _description, globalOptions, hiddenOptions, _subCmds);
throw xrt_core::error(std::errc::operation_canceled);
}
// -- Prepare the data
std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
opts.erase(opts.begin());
if (bHelp == true)
opts.push_back("--help");
#ifdef ENABLE_DEFAULT_ONE_DEVICE_OPTION
// If the user has NOT specified a device AND the command to be executed
// is not the examine command, then automatically add the device.
// Note: "examine" produces different reports depending if the user has
// specified the --device option or not.
if ( sDevice.empty() &&
(subCommand->isDefaultDeviceValid())) {
sDevice = "default";
}
#endif
// Was default device requested?
if (boost::iequals(sDevice, "default")) {
sDevice.clear();
boost::property_tree::ptree available_devices = XBU::get_available_devices(isUserDomain);
// DRC: Are there any devices
if (available_devices.empty())
throw std::runtime_error("No devices found.");
// DRC: Are there multiple devices, if so then no default device can be found.
if (available_devices.size() > 1) {
std::cerr << "\nERROR: Multiple devices found. Please specify a single device using the --device option\n\n";
std::cerr << "List of available devices:" << std::endl;
for (auto &kd : available_devices) {
boost::property_tree::ptree& dev = kd.second;
std::cerr << boost::format(" [%s] : %s\n") % dev.get<std::string>("bdf") % dev.get<std::string>("vbnv");
}
std::cout << std::endl;
throw xrt_core::error(std::errc::operation_canceled);
}
// We have only 1 item in the array, get it
for (const auto &kd : available_devices)
sDevice = kd.second.get<std::string>("bdf"); // Exit after the first item
}
// If there is a device value, pass it to the sub commands.
if (!sDevice.empty()) {
opts.push_back("-d");
opts.push_back(sDevice);
}
subCommand->setGlobalOptions(globalSubCmdOptions);
// -- Execute the sub-command
subCommand->execute(opts);
}
| 7,679 | 2,429 |
#include <core/vec_factory.h>
#include <core/optimizers/gradient_descent.h>
#include <core/vec_tools/fill.h>
#include <core/vec_tools/distance.h>
#include <core/funcs/lq.h>
#include <gtest/gtest.h>
TEST(Optimizer, GradientDescentTest) {
const int N = 10;
const double q = 2;
const double EPS = 0.01;
GradientDescent gd(EPS);
auto cursor = Vec(N);
VecTools::fill(1, cursor);
auto b = Vec(N);
VecTools::fill(2, b);
Lq distFunc(q, b);
gd.optimize(distFunc, cursor);
EXPECT_LE(VecTools::distanceLq(q, cursor, b), EPS);
}
| 569 | 239 |
// Copyright (C) 2000, International Business Machines
// Corporation and others. All Rights Reserved.
#ifndef _BCP_MATRIX_H
#define _BCP_MATRIX_H
// This file is fully docified.
#include <cmath>
#include <cfloat>
#include "CoinPackedVector.hpp"
#include "CoinPackedMatrix.hpp"
#include "BCP_vector.hpp"
//#############################################################################
class BCP_buffer;
//#############################################################################
/** This class holds a column in a compressed form. That is, it is a packed
vector with an objective coefficient, lower and upper bound. */
class BCP_col : public CoinPackedVector {
protected:
/**@name Data members */
/*@{*/
/** The objective function coefficient corresponding to the column. */
double _Objective;
/** The lower bound corresponding to the column. */
double _LowerBound;
/** The upper bound corresponding to the column. */
double _UpperBound;
/*@}*/
//--------------------------------------------------------------------------
public:
/**@name Query methods */
/*@{*/
/** Return the objective coefficient. */
inline double Objective() const { return _Objective; }
/** Return the lower bound. */
inline double LowerBound() const { return _LowerBound; }
/** Return the upper bound. */
inline double UpperBound() const { return _UpperBound; }
/*@}*/
//--------------------------------------------------------------------------
/**@name General modifying methods */
/*@{*/
/** Set the objective coefficient to the given value. */
inline void Objective(const double obj) { _Objective = obj; }
/** Set the lower bound to the given value. */
inline void LowerBound(const double lb) { _LowerBound = lb; }
/** Set the upper bound to the given value. */
inline void UpperBound(const double ub) { _UpperBound = ub; }
/** Assignment operator: copy over the contents of <code>x</code>. */
BCP_col& operator=(const BCP_col& x) {
CoinPackedVector::operator=(x);
_Objective = x.Objective();
_LowerBound = x.LowerBound();
_UpperBound = x.UpperBound();
return *this;
}
/** Set the objective coefficient, lower and upper bounds to the given
values. Also invokes the assign method of the underlying packed vector.
*/
inline void
assign(const int size, int*& ElementIndices, double*& ElementValues,
const double Obj, const double LB, const double UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_Objective = Obj;
_LowerBound = LB;
_UpperBound = UB;
}
/** Copy the arguments into the appropriate data members. */
inline void
copy(const int size, const int* ElementIndices, const double* ElementValues,
const double Obj, const double LB, const double UB) {
CoinPackedVector::setVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_Objective = Obj;
_LowerBound = LB;
_UpperBound = UB;
}
/** Same as the other <code>copy()</code> method, except that instead of
using vectors the indices (values) are given in
<code>[firstind,lastind)</code> (<code>[firstval,lastval)</code>). */
inline void
copy(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double Obj, const double LB, const double UB) {
CoinPackedVector::setVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */);
_Objective = Obj;
_LowerBound = LB;
_UpperBound = UB;
}
/*@}*/
//--------------------------------------------------------------------------
/**@name Constructors / Destructor */
/*@{*/
/** The default constructor creates an empty column with 0 as objective
coefficient, 0.0 as lower and +infinity as upper bound. */
BCP_col() : CoinPackedVector(false /* no test for duplicate index */),
_Objective(0), _LowerBound(0.0), _UpperBound(1e31) {}
/** The copy constructor makes a copy of <code>x</code>. */
BCP_col(const BCP_col& x) :
CoinPackedVector(x), _Objective(x.Objective()),
_LowerBound(x.LowerBound()), _UpperBound(x.UpperBound()) {}
/** This constructor acts exactly like the <code>copy</code> method with
the same argument list. */
BCP_col(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double Obj, const double LB, const double UB) :
CoinPackedVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */),
_Objective(Obj), _LowerBound(LB), _UpperBound(UB) {}
/** This constructor acts exactly like the <code>assign</code> method with
the same argument list. */
BCP_col(const int size, int*& ElementIndices, double*& ElementValues,
const double Obj, const double LB, const double UB) :
CoinPackedVector(), _Objective(Obj), _LowerBound(LB), _UpperBound(UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
}
BCP_col(const CoinPackedVectorBase& vec,
const double Obj, const double LB, const double UB) :
CoinPackedVector(vec.getNumElements(),
vec.getIndices(), vec.getElements()),
_Objective(Obj), _LowerBound(LB), _UpperBound(UB) {}
/** The destructor deletes all data members. */
~BCP_col() {}
/*@}*/
};
//#############################################################################
/** This class holds a row in a compressed form. That is, it is a packed
vector with a lower and upper bound. */
class BCP_row : public CoinPackedVector {
protected:
/**@name Data members */
/*@{*/
/** The lower bound corresponding to the row. */
double _LowerBound;
/** The upper bound corresponding to the row. */
double _UpperBound;
/*@}*/
//--------------------------------------------------------------------------
public:
/**@name Query methods */
/*@{*/
/** Return the lower bound. */
inline double LowerBound() const { return _LowerBound; }
/** Return the upper bound. */
inline double UpperBound() const { return _UpperBound; }
/*@}*/
//--------------------------------------------------------------------------
/**@name General modifying methods */
/*@{*/
/** Set the lower bound to the given value. */
inline void LowerBound(double lb) { _LowerBound = lb; }
/** Set the upper bound to the given value. */
inline void UpperBound(double ub) { _UpperBound = ub; }
/** Assignment operator: copy over the contents of <code>x</code>. */
BCP_row& operator=(const BCP_row& x) {
CoinPackedVector::operator=(x);
_LowerBound = x.LowerBound();
_UpperBound = x.UpperBound();
return *this;
}
/** Set the lower and upper bounds to the given values. Also invokes the
assign method of the underlying packed vector. */
void
assign(const int size, int*& ElementIndices, double*& ElementValues,
const double LB, const double UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_LowerBound = LB;
_UpperBound = UB;
}
/** Copy the arguments into the appropriate data members. */
void
copy(const int size, const int* ElementIndices, const double* ElementValues,
const double LB, const double UB) {
CoinPackedVector::setVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
_LowerBound = LB;
_UpperBound = UB;
}
/** Same as the other <code>copy()</code> method, except that instead of
using vectors the indices (values) are given in
<code>[firstind,lastind)</code> (<code>[firstval,lastval)</code>). */
void
copy(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double LB, const double UB) {
CoinPackedVector::setVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */);
_LowerBound = LB;
_UpperBound = UB;
}
/*@}*/
//--------------------------------------------------------------------------
/**@name Constructors / Destructor */
/*@{*/
/** The default constructor creates an empty row with -infinity as lower
and +infinity as upper bound. */
BCP_row() : CoinPackedVector(false /* no test for duplicate index */),
_LowerBound(-DBL_MAX), _UpperBound(DBL_MAX) {}
/** The copy constructor makes a copy of <code>x</code>. */
BCP_row(const BCP_row& x) :
CoinPackedVector(x),
_LowerBound(x.LowerBound()), _UpperBound(x.UpperBound()) {}
/** This constructor acts exactly like the <code>copy</code> method with
the same argument list. */
BCP_row(BCP_vec<int>::const_iterator firstind,
BCP_vec<int>::const_iterator lastind,
BCP_vec<double>::const_iterator firstval,
BCP_vec<double>::const_iterator lastval,
const double LB, const double UB) :
CoinPackedVector(lastind - firstind, firstind, firstval,
false /* no test for duplicate index */),
_LowerBound(LB), _UpperBound(UB) {}
/** This constructor acts exactly like the <code>assign</code> method with
the same argument list. */
BCP_row(const int size, int*& ElementIndices, double*& ElementValues,
const double LB, const double UB) :
CoinPackedVector(), _LowerBound(LB), _UpperBound(UB) {
CoinPackedVector::assignVector(size, ElementIndices, ElementValues,
false /* no test for duplicate index */);
}
BCP_row(const CoinPackedVectorBase& vec, const double LB, const double UB) :
CoinPackedVector(vec.getNumElements(),
vec.getIndices(), vec.getElements()),
_LowerBound(LB), _UpperBound(UB) {}
/** The destructor deletes all data members. */
~BCP_row() {}
/*@}*/
};
//#############################################################################
//#############################################################################
/** An object of type <code>CBP_lp_relax</code> holds the description of an lp
relaxation. The matrix, lower/upper bounds on the variables and cuts and
objective coefficients for the variables. */
class BCP_lp_relax : public CoinPackedMatrix {
private:
/**@name Data members */
/*@{*/
/** The objective coefficients of the variables. */
BCP_vec<double> _Objective;
/** The lower bounds on the variables. */
BCP_vec<double> _ColLowerBound;
/** The upper bounds on the variables. */
BCP_vec<double> _ColUpperBound;
/** The lower bounds on the cuts. */
BCP_vec<double> _RowLowerBound;
/** The upper bounds on the cuts. */
BCP_vec<double> _RowUpperBound;
/*@}*/
//--------------------------------------------------------------------------
public:
/**@name Query methods */
/*@{*/
/** The number of columns. */
inline size_t colnum() const { return _ColLowerBound.size(); }
/** The number of rows. */
inline size_t rownum() const { return _RowLowerBound.size(); }
/** A const reference to the vector of objective coefficients. */
inline const BCP_vec<double>& Objective() const {return _Objective;}
/** A const reference to the vector of lower bounds on the variables. */
inline const BCP_vec<double>& ColLowerBound() const {return _ColLowerBound;}
/** A const reference to the vector of upper bounds on the variables. */
inline const BCP_vec<double>& ColUpperBound() const {return _ColUpperBound;}
/** A const reference to the vector of lower bounds on the cuts. */
inline const BCP_vec<double>& RowLowerBound() const {return _RowLowerBound;}
/** A const reference to the vector of upper bounds on the cuts. */
inline const BCP_vec<double>& RowUpperBound() const {return _RowUpperBound;}
/*@}*/
//--------------------------------------------------------------------------
/**@name Methods modifying the whole LP relaxation. */
/*@{*/
/** Copy the content of <code>x</code> into the LP relaxation. */
BCP_lp_relax& operator=(const BCP_lp_relax& mat);
/** Reserve space in the LP relaxation for at least <code>MaxColNum</code>
columns, <code>MaxRowNum</code> rows and <code>MaxNonzeros</code>
nonzero entries. This is useful when columns/rows are added to the LP
relaxation in small chunks and to avoid a series of reallocation we
reserve sufficient space up front. */
void reserve(const int MaxColNum, const int MaxRowNum,
const int MaxNonzeros);
/** Clear the LP relaxation. */
void clear();
/** Set up the LP relaxation by making a copy of the arguments */
void copyOf(const CoinPackedMatrix& m,
const double* OBJ, const double* CLB, const double* CUB,
const double* RLB, const double* RUB);
/** Set up the LP relaxation by taking over the pointers in the arguments */
void assign(CoinPackedMatrix& m,
double*& OBJ, double*& CLB, double*& CUB,
double*& RLB, double*& RUB);
/*@}*/
//--------------------------------------------------------------------------
/**@name Methods for expanding/shrinking the LP relaxation. */
/*@{*/
#if 0
/** Append the columns in the argument column set to the end of this LP
relaxation. */
void add_col_set(const BCP_col_set& Cols);
/** Append the rows in the argument row set to the end of this LP
relaxation. */
void add_row_set(const BCP_row_set& Rows);
#endif
/** Remove the columns whose indices are listed in <code>pos</code> from
the LP relaxation. */
void erase_col_set(const BCP_vec<int>& pos);
/** Remove the rows whose indices are listed in <code>pos</code> from
the LP relaxation. */
void erase_row_set(const BCP_vec<int>& pos);
/*@}*/
//--------------------------------------------------------------------------
#if 0
/**@name Dot product methods */
/*@{*/
/** Compute the dot product of the index-th column with the full vector
given in <code>col</code>. */
double dot_product_col(const int index, const BCP_vec<double>& col) const;
/** Compute the dot product of the index-th row with the full vector
given in <code>row</code>. */
double dot_product_row(const int index, const BCP_vec<double>& row) const;
/** Compute the dot product of the index-th column with the full vector
starting at <code>col</code>. */
double dot_product_col(const int index, const double* col) const;
/** Compute the dot product of the index-th row with the full vector
starting at <code>row</code>. */
double dot_product_row(const int index, const double* row) const;
/*@}*/
#endif
//--------------------------------------------------------------------------
/**@name Packing/unpacking */
/*@{*/
/** Pack the LP relaxation into the buffer. */
void pack(BCP_buffer& buf) const;
/** Unpack the LP relaxation from the buffer. */
void unpack(BCP_buffer& buf);
/*@}*/
//--------------------------------------------------------------------------
/**@name Constructors and destructor */
/*@{*/
/** Create an empty LP relaxation with given ordering. */
BCP_lp_relax(const bool colordered = true) :
CoinPackedMatrix(colordered, 0, 0, 0, NULL, NULL, NULL, NULL),
_Objective(), _ColLowerBound(), _ColUpperBound(),
_RowLowerBound(), _RowUpperBound() {}
/** The copy constructor makes a copy of the argument LP relaxation. */
BCP_lp_relax(const BCP_lp_relax& mat);
/** Create a row major ordered LP relaxation by assigning the content of
the arguments to the LP relaxation. When the constructor returns the
content of 'rows' doesn't change while that of CLB, CUB and OBJ will be
whatever the default constructor for those arguments create. */
BCP_lp_relax(BCP_vec<BCP_row*>& rows,
BCP_vec<double>& CLB, BCP_vec<double>& CUB,
BCP_vec<double>& OBJ);
/** Same as the previous method except that this method allows extra_gap
and extra_major to be specified. For the description of those see the
documentation of CoinPackedMatrix. (extra_gap will be used for adding
columns, while extra major for adding rows) */
BCP_lp_relax(BCP_vec<BCP_row*>& rows,
BCP_vec<double>& CLB, BCP_vec<double>& CUB,
BCP_vec<double>& OBJ,
double extra_gap, double extra_major);
/** Create a column major ordered LP relaxation by assigning the content of
the arguments to the LP relaxation. When the constructor returns the
content of 'cols' doesn't change while that of RLB and RUB will be
whatever the default constructor for those arguments create. */
BCP_lp_relax(BCP_vec<BCP_col*>& cols,
BCP_vec<double>& RLB, BCP_vec<double>& RUB);
/** Same as the previous method except that this method allows extra_gap
and extra_major to be specified. For the description of those see the
documentation of CoinPackedMatrix. (extra_gap will be used for adding
rows, while extra major for adding columns) */
BCP_lp_relax(BCP_vec<BCP_col*>& cols,
BCP_vec<double>& RLB, BCP_vec<double>& RUB,
double extra_gap, double extra_major);
/** Create an LP relaxation of the given ordering by copying the content
of the arguments to the LP relaxation. */
BCP_lp_relax(const bool colordered,
const BCP_vec<int>& VB, const BCP_vec<int>& EI,
const BCP_vec<double>& EV, const BCP_vec<double>& OBJ,
const BCP_vec<double>& CLB, const BCP_vec<double>& CUB,
const BCP_vec<double>& RLB, const BCP_vec<double>& RUB);
/** Create an LP relaxation of the given ordering by assigning the content
of the arguments to the LP relaxation. When the constructor returns the
content of the arguments will be NULL pointers. <br>
*/
BCP_lp_relax(const bool colordered,
const int rownum, const int colnum, const int nznum,
int*& VB, int*& EI, double*& EV,
double*& OBJ, double*& CLB, double*& CUB,
double*& RLB, double*& RUB);
/** The destructor deletes the data members */
~BCP_lp_relax() {}
/*@}*/
private:
/**@name helper functions for the constructors */
/*@{*/
///
void BCP_createColumnOrderedMatrix(BCP_vec<BCP_row*>& rows,
BCP_vec<double>& CLB,
BCP_vec<double>& CUB,
BCP_vec<double>& OBJ);
///
void BCP_createRowOrderedMatrix(BCP_vec<BCP_col*>& cols,
BCP_vec<double>& RLB,
BCP_vec<double>& RUB);
/*@}*/
};
#endif
| 18,826 | 5,622 |
/*==============================================================================
Copyright (c) Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Kyle Sunderland, PerkLab, Queen's University
and was supported through CANARIE's Research Software Program, and Cancer
Care Ontario.
==============================================================================*/
// Slicer includes
#include <vtkObjectFactory.h>
#include <vtkMRMLScene.h>
#include <vtkMRMLColorLogic.h>
// MRML includes
#include <vtkMRMLVolumeNode.h>
#include <vtkMRMLStreamingVolumeNode.h>
#include <vtkMRMLSelectionNode.h>
#include <vtkMRMLLinearTransformNode.h>
#include <vtkMRMLColorTableNode.h>
// Volumes includes
#include <vtkStreamingVolumeCodecFactory.h>
// SequenceIO includes
#include "vtkSlicerSequenceIOLogic.h"
// Sequences includes
#include <vtkMRMLSequenceNode.h>
// vtkSequenceIOMRML includes
#include "vtkMRMLStreamingVolumeSequenceStorageNode.h"
// VTK includes
#include <vtkMatrix4x4.h>
//---------------------------------------------------------------------------
vtkStandardNewMacro(vtkSlicerSequenceIOLogic);
//---------------------------------------------------------------------------
class vtkSlicerSequenceIOLogic::vtkInternal
{
public:
//---------------------------------------------------------------------------
vtkInternal(vtkSlicerSequenceIOLogic* external);
~vtkInternal();
vtkSlicerSequenceIOLogic* External;
};
//----------------------------------------------------------------------------
// vtkInternal methods
//---------------------------------------------------------------------------
vtkSlicerSequenceIOLogic::vtkInternal::vtkInternal(vtkSlicerSequenceIOLogic* external)
: External(external)
{
}
//---------------------------------------------------------------------------
vtkSlicerSequenceIOLogic::vtkInternal::~vtkInternal()
{
}
//----------------------------------------------------------------------------
// vtkSlicerSequenceIOLogic methods
//---------------------------------------------------------------------------
vtkSlicerSequenceIOLogic::vtkSlicerSequenceIOLogic()
{
this->Internal = new vtkInternal(this);
}
//---------------------------------------------------------------------------
vtkSlicerSequenceIOLogic::~vtkSlicerSequenceIOLogic()
{
if (this->Internal)
{
delete this->Internal;
}
}
//-----------------------------------------------------------------------------
void vtkSlicerSequenceIOLogic::RegisterNodes()
{
if (this->GetMRMLScene() == NULL)
{
vtkErrorMacro("Scene is invalid");
return;
}
this->GetMRMLScene()->RegisterNodeClass(vtkSmartPointer<vtkMRMLStreamingVolumeSequenceStorageNode>::New());
vtkSmartPointer<vtkMRMLStreamingVolumeNode> streamingVolumeNode = vtkSmartPointer<vtkMRMLStreamingVolumeNode>::Take(
vtkMRMLStreamingVolumeNode::SafeDownCast(this->GetMRMLScene()->CreateNodeByClass("vtkMRMLStreamingVolumeNode")));
streamingVolumeNode->SetDefaultSequenceStorageNodeClassName("vtkMRMLStreamingVolumeSequenceStorageNode");
this->GetMRMLScene()->AddDefaultNode(streamingVolumeNode);
}
//---------------------------------------------------------------------------
void vtkSlicerSequenceIOLogic::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkObject::PrintSelf(os, indent);
os << indent << "vtkSlicerSequenceIOLogic: " << this->GetClassName() << "\n";
}
| 3,869 | 1,072 |
/* Shape.FixedFrame.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 3.50
//
// Tag: Desktop
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2017 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/inc/video/lib/Shape.FixedFrame.h>
namespace CCore {
namespace Video {
/* class FixedFrameShape */
void FixedFrameShape::draw_Frame(const DrawBuf &buf,Pane part) const
{
VColor frame=+cfg.frame;
VColor small=+cfg.dragSmall;
VColor frameSmall = has_good_size? frame : small ;
if( hilight==DragType_Bar ) frameSmall=frame=+cfg.frameHilight;
if( drag_type==DragType_Bar ) frameSmall=frame=+cfg.frameDrag;
drawFrame(buf,Pane(Null,size),client,frame,frameSmall,part);
}
void FixedFrameShape::draw_Frame(const DrawBuf &buf) const
{
draw_Frame(buf,Pane(Null,size));
}
void FixedFrameShape::draw_Frame(const DrawBuf &buf,DragType drag_type) const
{
Pane part=getPane(drag_type);
draw_Frame(buf.cut(part),part);
}
void FixedFrameShape::draw_Bar(const DrawBuf &buf) const
{
drawBar(buf,titleBar);
}
void FixedFrameShape::draw_Alert(const DrawBuf &buf) const
{
drawAlert(buf,btnAlert);
}
void FixedFrameShape::draw_Help(const DrawBuf &buf) const
{
drawHelp(buf,btnHelp);
}
void FixedFrameShape::draw_Min(const DrawBuf &buf) const
{
drawMin(buf,btnMin);
}
void FixedFrameShape::draw_Close(const DrawBuf &buf) const
{
drawClose(buf,btnClose);
}
void FixedFrameShape::layout(Point size_)
{
size=size_;
Coord dxy=+cfg.frame_dxy;
Coord tdy=+cfg.title_dy;
Coord bdx=+cfg.btn_dx;
Coord bdy=+cfg.btn_dy;
Coord btn_len = is_main? 5*bdx : 3*bdx ;
if( size>Point( 2*dxy+btn_len+bdx/2+Max(tdy,dxy) , dxy+Max(tdy,dxy) ) )
{
Pane pane=Pane(Null,size);
SplitX(dxy,pane);
SplitX(pane,dxy);
Pane top=SplitY(tdy,pane);
SplitY(pane,dxy);
client=pane;
Coord yb=(tdy-bdy)/2;
Coord tx=top.dx-btn_len;
if( is_main )
{
Coord xb0=top.x+tx;
Coord xb1=xb0+bdx+bdx/8;
Coord xb2=xb1+bdx+bdx/8;
Coord xb3=xb2+bdx+bdx/2;
btnAlert=Pane(xb0,yb,bdx,bdy);
btnHelp=Pane(xb1,yb,bdx,bdy);
btnMin=Pane(xb2,yb,bdx,bdy);
btnClose=Pane(xb3,yb,bdx,bdy);
}
else
{
Coord xb0=top.x+tx;
Coord xb1=xb0+bdx+bdx/2;
btnAlert=Empty;
btnMin=Empty;
btnHelp=Pane(xb0,yb,bdx,bdy);
btnClose=Pane(xb1,yb,bdx,bdy);
}
Coord w=cfg.width.get().roundUp();
titleBar=Pane(top.x+bdx/4,w,tx-bdx/2,tdy-2*w);
}
else
{
client=Empty;
btnAlert=Empty;
btnHelp=Empty;
btnMin=Empty;
btnClose=Pane(Null,bdx,bdy);
titleBar=Empty;
}
}
Point FixedFrameShape::getDeltaSize() const
{
Coord dxy=+cfg.frame_dxy;
Coord tdy=+cfg.title_dy;
return Point(dxy,tdy)+Point(dxy,dxy);
}
Coord FixedFrameShape::getMinDX(bool is_main,StrLen title) const
{
Coord width=cfg.width.get().roundUp();
Coord tdy=+cfg.title_dy;
Coord dxy=+cfg.frame_dxy;
Coord bdx=+cfg.btn_dx;
Coord btn_len = is_main? 5*bdx : 3*bdx ;
Coord dx=getMinTitleDX(title,tdy-2*width);
Replace_max(dx,Max(tdy,dxy));
dx += 2*dxy+btn_len+bdx/2 ;
return dx;
}
DragType FixedFrameShape::dragTest(Point point) const
{
if( btnAlert.contains(point) ) return DragType_Alert;
if( btnHelp.contains(point) ) return DragType_Help;
if( btnMin.contains(point) ) return DragType_Min;
if( btnClose.contains(point) ) return DragType_Close;
return client.contains(point)?DragType_None:DragType_Bar;
}
Pane FixedFrameShape::getPane(DragType drag_type) const
{
switch( drag_type )
{
case DragType_Bar : return Pane(Null,size);
case DragType_Alert : return btnAlert;
case DragType_Help : return btnHelp;
case DragType_Min : return btnMin;
case DragType_Close : return btnClose;
default: return Empty;
}
}
Hint FixedFrameShape::getHint(Point point) const
{
switch( dragTest(point) )
{
case DragType_Alert : return {btnAlert,+cfg.hint_Alert};
case DragType_Help : return {btnHelp,+cfg.hint_Help};
case DragType_Min : return {btnMin,+cfg.hint_Minimize};
case DragType_Close : return {btnClose,+cfg.hint_Close};
default: return Null;
}
}
void FixedFrameShape::draw(const DrawBuf &buf) const
{
draw_Frame(buf);
draw_Bar(buf);
draw_Alert(buf);
draw_Help(buf);
draw_Min(buf);
draw_Close(buf);
}
void FixedFrameShape::draw(const DrawBuf &buf,DragType drag_type) const
{
if( drag_type==DragType_Bar )
{
draw_Frame(buf);
draw_Bar(buf);
draw_Alert(buf);
draw_Help(buf);
draw_Min(buf);
draw_Close(buf);
}
else
{
draw_Frame(buf,drag_type);
switch( drag_type )
{
case DragType_Alert : draw_Alert(buf); break;
case DragType_Help : draw_Help(buf); break;
case DragType_Min : draw_Min(buf); break;
case DragType_Close : draw_Close(buf); break;
}
}
}
void FixedFrameShape::drawHint(const DrawBuf &buf,Hint hint) const
{
FrameShapeBase::drawHint(buf,titleBar,hint);
}
} // namespace Video
} // namespace CCore
| 5,512 | 2,158 |
#include <utility>
#include <vector>
#include <Eigen/Core>
#include <aslam/common/memory.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>
#include <inverted-multi-index/inverted-multi-index-common.h>
#include <inverted-multi-index/inverted-multi-index.h>
namespace loop_closure {
namespace inverted_multi_index {
namespace {
class TestableInvertedMultiIndex : public InvertedMultiIndex<3> {
public:
TestableInvertedMultiIndex(
const Eigen::MatrixXf& words1, const Eigen::MatrixXf& words2,
int num_closest_words_for_nn_search)
: InvertedMultiIndex<3>(words1, words2, num_closest_words_for_nn_search) {
}
using InvertedMultiIndex<3>::words_1_index_;
using InvertedMultiIndex<3>::words_2_index_;
using InvertedMultiIndex<3>::word_index_map_;
using InvertedMultiIndex<3>::inverted_files_;
using InvertedMultiIndex<3>::max_db_descriptor_index_;
};
class InvertedMultiIndexTest : public ::testing::Test {
public:
void SetUp() {
words1_.resize(3, 10);
words1_ << 0.751267059305653, 0.547215529963803, 0.814284826068816,
0.616044676146639, 0.917193663829810, 0.075854289563064,
0.568823660872193, 0.311215042044805, 0.689214503140008,
0.152378018969223, 0.255095115459269, 0.138624442828679,
0.243524968724989, 0.473288848902729, 0.285839018820374,
0.053950118666607, 0.469390641058206, 0.528533135506213,
0.748151592823709, 0.825816977489547, 0.505957051665142,
0.149294005559057, 0.929263623187228, 0.351659507062997,
0.757200229110721, 0.530797553008973, 0.011902069501241,
0.165648729499781, 0.450541598502498, 0.538342435260057;
words2_.resize(3, 5);
words2_ << 0.699076722656686, 0.257508254123736, 0.349983765984809,
0.830828627896291, 0.753729094278495, 0.890903252535798,
0.840717255983663, 0.196595250431208, 0.585264091152724,
0.380445846975357, 0.959291425205444, 0.254282178971531,
0.251083857976031, 0.549723608291140, 0.567821640725221;
}
Eigen::MatrixXf words1_;
Eigen::MatrixXf words2_;
};
TEST_F(InvertedMultiIndexTest, AddDescriptorsWorks) {
// FLAG used to control the amount of backtracking done during kd-tree-based
// nearest neighbor search. In order to work, this test needs a certain amount
// of backtracking.
FLAGS_lc_knn_epsilon = 0.2;
Eigen::MatrixXf descriptors(6, 50);
descriptors << 0.837, 0.298, 0.071, 0.971, 0.205, 0.170, 0.236, 0.043, 0.087,
0.638, 0.583, 0.727, 0.013, 0.741, 0.088, 0.465, 0.514, 0.948, 0.552,
0.118, 0.018, 0.719, 0.482, 0.343, 0.599, 0.984, 0.455, 0.568, 0.576,
0.678, 0.370, 0.506, 0.600, 0.867, 0.888, 0.520, 0.736, 0.227, 0.072,
0.176, 0.858, 0.497, 0.403, 0.861, 0.921, 0.425, 0.671, 0.998, 0.903,
0.938, 0.930, 0.721, 0.448, 0.799, 0.284, 0.239, 0.616, 0.298, 0.906,
0.573, 0.741, 0.156, 0.148, 0.379, 0.706, 0.703, 0.355, 0.351, 0.068,
0.969, 0.354, 0.875, 0.930, 0.869, 0.565, 0.213, 0.309, 0.106, 0.854,
0.163, 0.677, 0.443, 0.087, 0.276, 0.981, 0.792, 0.251, 0.918, 0.980,
0.026, 0.769, 0.473, 0.339, 0.565, 0.326, 0.986, 0.031, 0.662, 0.249,
0.035, 0.886, 0.901, 0.071, 0.524, 0.733, 0.091, 0.311, 0.473, 0.904,
0.531, 0.526, 0.849, 0.618, 0.361, 0.899, 0.763, 0.485, 0.668, 0.575,
0.861, 0.633, 0.427, 0.447, 0.930, 0.124, 0.250, 0.713, 0.405, 0.029,
0.250, 0.432, 0.096, 0.117, 0.666, 0.898, 0.608, 0.097, 0.468, 0.062,
0.943, 0.889, 0.583, 0.268, 0.101, 0.953, 0.780, 0.558, 0.219, 0.034,
0.378, 0.765, 0.044, 0.904, 0.320, 0.570, 0.855, 0.452, 0.344, 0.235,
0.919, 0.958, 0.052, 0.934, 0.927, 0.830, 0.992, 0.711, 0.888, 0.199,
0.056, 0.362, 0.465, 0.311, 0.337, 0.567, 0.951, 0.908, 0.336, 0.734,
0.975, 0.654, 0.448, 0.991, 0.075, 0.128, 0.767, 0.775, 0.565, 0.282,
0.388, 0.698, 0.721, 0.439, 0.631, 0.733, 0.555, 0.991, 0.568, 0.137,
0.178, 0.608, 0.342, 0.451, 0.838, 0.624, 0.879, 0.163, 0.829, 0.508,
0.016, 0.986, 0.644, 0.639, 0.408, 0.485, 0.720, 0.818, 0.689, 0.518,
0.810, 0.513, 0.134, 0.244, 0.271, 0.473, 0.743, 0.445, 0.259, 0.231,
0.772, 0.679, 0.817, 0.654, 0.055, 0.155, 0.941, 0.707, 0.637, 0.460,
0.132, 0.651, 0.524, 0.103, 0.482, 0.090, 0.633, 0.265, 0.352, 0.250,
0.035, 0.748, 0.238, 0.528, 0.061, 0.257, 0.691, 0.227, 0.143, 0.551,
0.207, 0.798, 0.442, 0.920, 0.016, 0.275, 0.457, 0.737, 0.763, 0.951,
0.274, 0.999, 0.092, 0.940, 0.526, 0.270, 0.512, 0.774, 0.466, 0.781,
0.848, 0.947, 0.413, 0.636, 0.867, 0.813, 0.664, 0.702, 0.687, 0.818,
0.825, 0.437, 0.302, 0.145, 0.855, 0.363, 0.091, 0.329, 0.044, 0.380,
0.876;
std::vector<int> nearest_word_per_descriptor = {
43, 47, 38, 41, 26, 35, 37, 26, 46, 44, 40, 11, 25, 18, 48, 43, 15,
23, 0, 46, 25, 42, 44, 47, 32, 3, 4, 2, 34, 5, 45, 31, 8, 22,
42, 40, 8, 48, 49, 29, 43, 18, 37, 34, 14, 46, 4, 42, 7, 2};
std::vector<bool> word_used(50, false);
std::vector<int> word_index(50, -1);
int counter = 0;
for (int i = 0; i < 50; ++i) {
if (!word_used[nearest_word_per_descriptor[i]]) {
word_index[nearest_word_per_descriptor[i]] = counter;
word_used[nearest_word_per_descriptor[i]] = true;
++counter;
}
}
TestableInvertedMultiIndex index(words1_, words2_, 10);
index.AddDescriptors(descriptors);
ASSERT_EQ(50, index.max_db_descriptor_index_);
ASSERT_EQ(32u, index.word_index_map_.size());
ASSERT_EQ(32u, index.inverted_files_.size());
// Ensures that every descriptor is stored in its correct place.
std::vector<int> word_counts(50, 0);
for (int i = 0; i < 50; ++i) {
int word = word_index[nearest_word_per_descriptor[i]];
ASSERT_GE(word, 0);
ASSERT_LT(word, 32);
ASSERT_EQ(
index.inverted_files_[word].descriptors_.size(),
index.inverted_files_[word].indices_.size());
ASSERT_GE(
static_cast<int>(index.inverted_files_[word].descriptors_.size()),
word_counts[word]);
EXPECT_EQ(index.inverted_files_[word].indices_[word_counts[word]], i);
EXPECT_NEAR_EIGEN(
index.inverted_files_[word].descriptors_[word_counts[word]],
descriptors.col(i), 1e-12);
word_counts[word] += 1;
}
index.Clear();
EXPECT_EQ(0, index.max_db_descriptor_index_);
}
TEST_F(InvertedMultiIndexTest, GetNNearestNeighborsWorks) {
Eigen::MatrixXf descriptors(6, 50);
descriptors << 0.837, 0.298, 0.071, 0.971, 0.205, 0.170, 0.236, 0.043, 0.087,
0.638, 0.583, 0.727, 0.013, 0.741, 0.088, 0.465, 0.514, 0.948, 0.552,
0.118, 0.018, 0.719, 0.482, 0.343, 0.599, 0.984, 0.455, 0.568, 0.576,
0.678, 0.370, 0.506, 0.600, 0.867, 0.888, 0.520, 0.736, 0.227, 0.072,
0.176, 0.858, 0.497, 0.403, 0.861, 0.921, 0.425, 0.671, 0.998, 0.903,
0.938, 0.930, 0.721, 0.448, 0.799, 0.284, 0.239, 0.616, 0.298, 0.906,
0.573, 0.741, 0.156, 0.148, 0.379, 0.706, 0.703, 0.355, 0.351, 0.068,
0.969, 0.354, 0.875, 0.930, 0.869, 0.565, 0.213, 0.309, 0.106, 0.854,
0.163, 0.677, 0.443, 0.087, 0.276, 0.981, 0.792, 0.251, 0.918, 0.980,
0.026, 0.769, 0.473, 0.339, 0.565, 0.326, 0.986, 0.031, 0.662, 0.249,
0.035, 0.886, 0.901, 0.071, 0.524, 0.733, 0.091, 0.311, 0.473, 0.904,
0.531, 0.526, 0.849, 0.618, 0.361, 0.899, 0.763, 0.485, 0.668, 0.575,
0.861, 0.633, 0.427, 0.447, 0.930, 0.124, 0.250, 0.713, 0.405, 0.029,
0.250, 0.432, 0.096, 0.117, 0.666, 0.898, 0.608, 0.097, 0.468, 0.062,
0.943, 0.889, 0.583, 0.268, 0.101, 0.953, 0.780, 0.558, 0.219, 0.034,
0.378, 0.765, 0.044, 0.904, 0.320, 0.570, 0.855, 0.452, 0.344, 0.235,
0.919, 0.958, 0.052, 0.934, 0.927, 0.830, 0.992, 0.711, 0.888, 0.199,
0.056, 0.362, 0.465, 0.311, 0.337, 0.567, 0.951, 0.908, 0.336, 0.734,
0.975, 0.654, 0.448, 0.991, 0.075, 0.128, 0.767, 0.775, 0.565, 0.282,
0.388, 0.698, 0.721, 0.439, 0.631, 0.733, 0.555, 0.991, 0.568, 0.137,
0.178, 0.608, 0.342, 0.451, 0.838, 0.624, 0.879, 0.163, 0.829, 0.508,
0.016, 0.986, 0.644, 0.639, 0.408, 0.485, 0.720, 0.818, 0.689, 0.518,
0.810, 0.513, 0.134, 0.244, 0.271, 0.473, 0.743, 0.445, 0.259, 0.231,
0.772, 0.679, 0.817, 0.654, 0.055, 0.155, 0.941, 0.707, 0.637, 0.460,
0.132, 0.651, 0.524, 0.103, 0.482, 0.090, 0.633, 0.265, 0.352, 0.250,
0.035, 0.748, 0.238, 0.528, 0.061, 0.257, 0.691, 0.227, 0.143, 0.551,
0.207, 0.798, 0.442, 0.920, 0.016, 0.275, 0.457, 0.737, 0.763, 0.951,
0.274, 0.999, 0.092, 0.940, 0.526, 0.270, 0.512, 0.774, 0.466, 0.781,
0.848, 0.947, 0.413, 0.636, 0.867, 0.813, 0.664, 0.702, 0.687, 0.818,
0.825, 0.437, 0.302, 0.145, 0.855, 0.363, 0.091, 0.329, 0.044, 0.380,
0.876;
std::vector<int> nearest_word_per_descriptor = {
43, 47, 38, 41, 26, 35, 37, 26, 46, 44, 40, 11, 25, 18, 48, 43, 15,
23, 0, 46, 25, 42, 44, 47, 32, 3, 4, 2, 34, 5, 45, 31, 8, 22,
42, 40, 8, 48, 49, 29, 43, 18, 37, 34, 14, 46, 4, 42, 7, 2};
Eigen::MatrixXf query_descriptors(6, 10);
query_descriptors << 0.971, 0.890, 0.610, 0.509, 0.017, 0.922, 0.901, 0.323,
0.321, 0.745, 0.581, 0.179, 0.900, 0.622, 0.827, 0.945, 0.020, 0.921,
0.409, 0.737, 0.369, 0.800, 0.027, 0.497, 0.493, 0.556, 0.168, 0.705,
0.107, 0.012, 0.913, 0.912, 0.232, 0.611, 0.513, 0.625, 0.543, 0.639,
0.716, 0.584, 0.638, 0.791, 0.944, 0.111, 0.226, 0.626, 0.105, 0.086,
0.834, 0.696, 0.470, 0.813, 0.640, 0.236, 0.182, 0.292, 0.039, 0.230,
0.707, 0.006;
TestableInvertedMultiIndex index(words1_, words2_, 10);
index.AddDescriptors(descriptors);
for (int i = 0; i < 10; ++i) {
std::vector<std::pair<int, int> > ten_closest_words;
common::FindClosestWords<3>(
query_descriptors.col(i), 10, *(index.words_1_index_),
*(index.words_2_index_), words1_.cols(), words2_.cols(),
&ten_closest_words);
std::vector<bool> word_activated(50, 0);
for (int j = 0; j < 10; ++j) {
int word_index = ten_closest_words[j].first * words2_.cols() +
ten_closest_words[j].second;
word_activated[word_index] = true;
}
static constexpr int kNumNeighbors = 10;
Eigen::VectorXi indices(kNumNeighbors, 1);
Eigen::VectorXf distances(kNumNeighbors, 1);
index.GetNNearestNeighbors(
query_descriptors.block<6, 1>(0, i), kNumNeighbors, indices, distances);
// Verifies that the nearest neighbors are correct through linear search.
std::vector<std::pair<float, int> > gt_distances;
int num_neighbors = 0;
for (int j = 0; j < 50; ++j) {
if (!word_activated[nearest_word_per_descriptor[j]])
continue;
float d = (descriptors.col(j) - query_descriptors.col(i)).squaredNorm();
gt_distances.push_back(std::make_pair(d, j));
++num_neighbors;
}
std::sort(gt_distances.begin(), gt_distances.end());
Eigen::VectorXi expected_indices(kNumNeighbors, 1);
int num_elements = std::min(kNumNeighbors, num_neighbors);
for (int j = 0; j < num_elements; ++j) {
EXPECT_FLOAT_EQ(gt_distances[j].first, distances[j]);
expected_indices(j, 0) = gt_distances[j].second;
}
EXPECT_TRUE(
::common::MatricesEqual(
indices.block(0, 0, num_elements, 1),
expected_indices.block(0, 0, num_elements, 1), 1e-9));
}
}
} // namespace
} // namespace inverted_multi_index
} // namespace loop_closure
MAPLAB_UNITTEST_ENTRYPOINT
| 11,488 | 7,911 |
#include <iostream>
#include <iomanip>
using namespace std;
class Hole {
public:
bool isEmpty = true;
int id = -1;
Hole *upRight = nullptr;
Hole *upLeft = nullptr;
Hole *downLeft = nullptr;
Hole *downRight = nullptr;
Hole *left = nullptr;
Hole *right = nullptr;
Hole(bool e, int num) {
isEmpty = e;
id = num;
}
void printHoleID() {
cout << setw(4) << id;
}
void printHolePeg() {
if (isEmpty) {
cout << setw(4) << "-";
} else {
cout << setw(4) << "p";
}
}
};
class PegJumpGame {
private:
Hole *holes[15] = {
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr
};
public:
PegJumpGame() {
holes[0] = new Hole(true, 0);
holes[1] = new Hole(false, 1);
holes[2] = new Hole(false, 2);
holes[3] = new Hole(false, 3);
holes[4] = new Hole(false, 4);
holes[5] = new Hole(false, 5);
holes[6] = new Hole(false, 6);
holes[7] = new Hole(false, 7);
holes[8] = new Hole(false, 8);
holes[9] = new Hole(false, 9);
holes[10] = new Hole(false, 10);
holes[11] = new Hole(false, 11);
holes[12] = new Hole(false, 12);
holes[13] = new Hole(false, 13);
holes[14] = new Hole(false, 14);
holes[0]->downLeft = holes[1];
holes[0]->downRight = holes[2];
holes[1]->upRight = holes[0];
holes[1]->right = holes[2];
holes[1]->downLeft = holes[3];
holes[1]->downRight = holes[4];
holes[2]->upLeft = holes[0];
holes[2]->left = holes[1];
holes[2]->downLeft = holes[4];
holes[2]->downRight = holes[5];
holes[3]->upRight = holes[1];
holes[3]->right = holes[4];
holes[3]->downLeft = holes[6];
holes[3]->downRight = holes[7];
holes[4]->upLeft = holes[1];
holes[4]->upRight = holes[2];
holes[4]->left = holes[3];
holes[4]->right = holes[5];
holes[4]->downLeft = holes[7];
holes[4]->downRight = holes[8];
holes[5]->upLeft = holes[2];
holes[5]->left = holes[4];
holes[5]->downLeft = holes[8];
holes[5]->downRight = holes[9];
holes[6]->upRight = holes[3];
holes[6]->right = holes[7];
holes[6]->downLeft = holes[10];
holes[6]->downRight = holes[11];
holes[7]->upLeft = holes[3];
holes[7]->upRight = holes[4];
holes[7]->left = holes[6];
holes[7]->right = holes[8];
holes[7]->downLeft = holes[11];
holes[7]->downRight = holes[12];
holes[8]->upLeft = holes[4];
holes[8]->upRight = holes[5];
holes[8]->left = holes[7];
holes[8]->right = holes[9];
holes[8]->downLeft = holes[12];
holes[8]->downRight = holes[13];
holes[9]->upLeft = holes[5];
holes[9]->left = holes[8];
holes[9]->downLeft = holes[13];
holes[9]->downRight = holes[14];
holes[10]->upRight = holes[6];
holes[10]->right = holes[11];
holes[11]->upLeft = holes[6];
holes[11]->upRight = holes[7];
holes[11]->left = holes[10];
holes[11]->right = holes[12];
holes[12]->upLeft = holes[7];
holes[12]->upRight = holes[8];
holes[12]->left = holes[11];
holes[12]->right = holes[13];
holes[13]->upLeft = holes[8];
holes[13]->upRight = holes[9];
holes[13]->left = holes[12];
holes[13]->right = holes[14];
holes[14]->upLeft = holes[9];
holes[14]->left = holes[13];
}
bool movePeg(int fromID, string direction) {
Hole *holePtr = holes[fromID];
if (holePtr->isEmpty) {
cout << "\nSorry There is no peg I can use to jump at location " << fromID << ". Move aborted.\n\n";
return false;
}
Hole *jumpOverHole = nullptr;
Hole *jumpToHole = nullptr;
if (direction == "left") {
jumpOverHole = holePtr->left;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->left;
}
} else if (direction == "right") {
jumpOverHole = holePtr->right;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->right;
}
} else if (direction == "upRight" || direction == "upright") {
jumpOverHole = holePtr->upRight;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->upRight;
}
} else if (direction == "upLeft" || direction == "upleft") {
jumpOverHole = holePtr->upLeft;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->upLeft;
}
} else if (direction == "downLeft" || direction == "downleft") {
jumpOverHole = holePtr->downLeft;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->downLeft;
}
} else if (direction == "downRight" || direction == "downright") {
jumpOverHole = holePtr->downRight;
if (jumpOverHole != nullptr) {
jumpToHole = jumpOverHole->downRight;
}
} else {
cout << "\nSorry I do not recognize the direction " << direction << ". Move aborted.\n" << endl;
return false;
}
return doJump(holePtr, jumpOverHole, jumpToHole);
}
bool doJump(Hole *jumpFromHolePtr, Hole *jumpOverHolePtr, Hole *jumpToHolePtr) {
if (jumpFromHolePtr == nullptr || jumpToHolePtr == nullptr || jumpOverHolePtr == nullptr) {
return false;
}
if (jumpToHolePtr->isEmpty == false) {
return false;
}
jumpToHolePtr->isEmpty = false;
jumpFromHolePtr->isEmpty = true;
jumpOverHolePtr->isEmpty = true;
return true;
}
bool printBoard() {
for (int loop = 0; loop < 2; ++loop) {
int holeCount = 0, holeIDProblems = 0, linkProblems = 0;
string pad(14, ' ');
Hole *holePtr = holes[0];
if (holePtr == nullptr) {
cout << "printBoard(): ERROR: holes[0] is null. Cannot print empty board.Abort" << endl;
return false;
}
if (loop == 0) {
cout << "Board Hole Position IDs are:" << endl;
} else {
cout << "\nYour Pegs are:" << endl;
}
cout << pad;
while (holePtr != nullptr) {
if (loop == 0) {
holePtr->printHoleID();
} else {
holePtr->printHolePeg();
}
if (holeCount++ != holePtr->id) {
holeIDProblems++;
}
if (loop == 0) {
linkProblems += (holePtr->left != nullptr ? (holePtr->left->right != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->right != nullptr ? (holePtr->right->left != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->upRight != nullptr ? (holePtr->upRight->downLeft != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->upLeft != nullptr ? (holePtr->upLeft->downRight != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->downLeft != nullptr ? (holePtr->downLeft->upRight != holePtr ? 1 : 0) : 0 );
linkProblems += (holePtr->downRight != nullptr ? (holePtr->downRight->upLeft != holePtr ? 1 : 0) : 0 );
if (linkProblems > 0) {
cout << "\nPrintBoard(): Error: encountered " << linkProblems << " problems with the links on hole with ID == " << holePtr->id << ".Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->left == nullptr && (holePtr->id != 0 && holePtr->id != 1 && holePtr->id !=3 && holePtr->id !=6 && holePtr->id !=10)) {
cout << "\nPrintBoard(): Error: left pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->right == nullptr && (holePtr->id != 0 && holePtr->id != 2 && holePtr->id !=5 && holePtr->id !=9 && holePtr->id !=14)) {
cout << "\nPrintBoard(): Error: right pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->downLeft == nullptr && (holePtr->id != 10 && holePtr->id != 11 && holePtr->id !=12 && holePtr->id !=13 && holePtr->id !=14)) {
cout << "\nPrintBoard(): Error: downLeft pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
if (holePtr->downRight == nullptr && (holePtr->id != 10 && holePtr->id != 11 && holePtr->id !=12 && holePtr->id !=13 && holePtr->id !=14)) {
cout << "\nPrintBoard(): Error: downRight pointer for Hole with id " << holePtr->id << " should NOT be null. Please check your constructor. Abort." << endl;
return false;
}
}
if (holePtr->right != nullptr) {
holePtr = holePtr->right;
} else {
while (holePtr->left != nullptr) {
holePtr = holePtr->left;
}
if (holePtr->downLeft != nullptr) {
holePtr = holePtr->downLeft;
pad.pop_back();
pad.pop_back();
cout << endl;
cout << pad;
} else {
break;
}
}
}
cout << endl;
if (loop == 0 && holeIDProblems != 0) {
cout << "\nPrintBoard(): Error: " << holeIDProblems << " of your hole IDs shown above are not correct! Please check your constructor. Abort." << endl;
return false;
}
}
return true;
}
};
int main() {
cout << "Calling PegJumpGame constructor...." << endl;
PegJumpGame p;
cout << "OK Let's play!!" << endl;
int pegToMove;
string direction;
bool moveSucceeded = false;
if (!p.printBoard()) {
cout << "printBoard found a problem... abort program." << endl;
return 1;
}
for (;;) {
cout << "\nWhat Hole ID would you like to move a peg from (0..14)? ";
cin >> pegToMove;
if (pegToMove <0 || pegToMove > 14) {
cout << "Sorry - that is not a valid number... please try again! " << endl;
continue;
}
cout << "In what direction would you like to move peg #" << pegToMove << " (upLeft, upRight, left, right, downLeft, or downRight) ? ";
cin >> direction;
moveSucceeded = p.movePeg(pegToMove, direction);
if (moveSucceeded) {
cout << "Well-played!" << endl;
if (!p.printBoard()) {
break;
}
} else {
cout << "Sorry that move did not work" << endl;
}
}
}
| 12,609 | 3,675 |
/**
* @example oglplus/026_stencil_shadow.cpp
* @brief Shows how to render shadows using geometry shader and stencil buffer
*
* @oglplus_screenshot{026_stencil_shadow}
*
* Copyright 2008-2015 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
* @oglplus_example_uses_gl{GL_VERSION_3_3}
* @oglplus_example_uses_gl{GL_ARB_separate_shader_objects;GL_EXT_direct_state_access}
*/
#include <oglplus/gl.hpp>
#include <oglplus/all.hpp>
#include <oglplus/shapes/torus.hpp>
#include <cmath>
#include "example.hpp"
namespace oglplus {
class ShadowExample : public Example
{
private:
// the torus vertex attribute builder
shapes::Torus make_torus;
// here will be stored the indices used by the drawing instructions
shapes::Torus::IndexArray torus_indices;
// the instructions for drawing the torus
shapes::DrawingInstructions torus_instr;
// wrapper around the current OpenGL context
Context gl;
// Shaders and program for rendering of the objects
VertexShader vs_object;
FragmentShader fs_object;
Program object_prog;
// Shaders and program for rendering of the shadow effect
VertexShader vs_shadow;
GeometryShader gs_shadow;
FragmentShader fs_shadow;
Program shadow_prog;
// Uniforms
Uniform<Mat4f>
object_projection_matrix, object_camera_matrix, object_model_matrix,
shadow_projection_matrix, shadow_camera_matrix, shadow_model_matrix;
Uniform<Vec3f> object_color;
Uniform<GLfloat> object_light_mult;
// A vertex array object for the torus
VertexArray torus;
// VBOs for the torus' vertices and normals
Buffer torus_verts, torus_normals;
// A vertex array object for the shadowed plane
VertexArray plane;
// VBOs for the plane's vertices and normals
Buffer plane_verts, plane_normals;
public:
ShadowExample(void)
: make_torus(1.0, 0.7, 72, 48)
, torus_indices(make_torus.Indices())
, torus_instr(make_torus.Instructions())
, object_projection_matrix(object_prog)
, object_camera_matrix(object_prog)
, object_model_matrix(object_prog)
, shadow_projection_matrix(shadow_prog)
, shadow_camera_matrix(shadow_prog)
, shadow_model_matrix(shadow_prog)
, object_color(object_prog)
, object_light_mult(object_prog)
{
vs_object.Source(
"#version 140\n"
"in vec4 Position;"
"in vec3 Normal;"
"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
"uniform vec3 LightPos;"
"out vec3 vertNormal;"
"out vec3 vertLight;"
"void main(void)"
"{"
" gl_Position = ModelMatrix * Position;"
" vertNormal = mat3(ModelMatrix)*Normal;"
" vertLight = LightPos - gl_Position.xyz;"
" gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
"}"
);
vs_object.Compile();
fs_object.Source(
"#version 140\n"
"in vec3 vertNormal;"
"in vec3 vertLight;"
"uniform vec3 Color;"
"uniform float LightMult;"
"out vec4 fragColor;"
"void main(void)"
"{"
" float l = sqrt(length(vertLight));"
" float d = l > 0.0 ?"
" dot("
" vertNormal,"
" normalize(vertLight)"
" ) / l : 0.0;"
" float i = 0.3 + max(d, 0.0) * LightMult;"
" fragColor = vec4(Color*i, 1.0);"
"}"
);
fs_object.Compile();
object_prog.AttachShader(vs_object);
object_prog.AttachShader(fs_object);
object_prog.Link().Use();
object_projection_matrix.BindTo("ProjectionMatrix");
object_camera_matrix.BindTo("CameraMatrix");
object_model_matrix.BindTo("ModelMatrix");
object_color.BindTo("Color");
object_light_mult.BindTo("LightMult");
vs_shadow.Source(
"#version 150\n"
"in vec4 Position;"
"in vec3 Normal;"
"uniform mat4 ModelMatrix;"
"uniform vec3 LightPos;"
"out float ld;"
"void main(void)"
"{"
" gl_Position = ModelMatrix * Position;"
" vec3 geomNormal = mat3(ModelMatrix)*Normal;"
" vec3 lightDir = LightPos - gl_Position.xyz;"
" ld = dot(geomNormal, normalize(lightDir));"
"}"
);
vs_shadow.Compile();
gs_shadow.Source(
"#version 150\n"
"layout(triangles) in;"
"layout(triangle_strip, max_vertices = 12) out;"
"in float ld[];"
"uniform mat4 CameraMatrix, ProjectionMatrix;"
"uniform vec3 LightPos;"
"void main(void)"
"{"
" for(int v=0; v!=3; ++v)"
" {"
" int a = v, b = (v+1)%3, c = (v+2)%3;"
" vec4 pa = gl_in[a].gl_Position;"
" vec4 pb = gl_in[b].gl_Position;"
" vec4 pc = gl_in[c].gl_Position;"
" vec4 px, py;"
" if(ld[a] == 0.0 && ld[b] == 0.0)"
" {"
" px = pa;"
" py = pb;"
" }"
" else if(ld[a] > 0.0 && ld[b] < 0.0)"
" {"
" float x = ld[a]/(ld[a]-ld[b]);"
" float y;"
" px = mix(pa, pb, x);"
" if(ld[c] < 0.0)"
" {"
" y = ld[a]/(ld[a]-ld[c]);"
" py = mix(pa, pc, y);"
" }"
" else"
" {"
" y = ld[c]/(ld[c]-ld[b]);"
" py = mix(pc, pb, y);"
" }"
" }"
" else continue;"
" vec3 vx = px.xyz - LightPos;"
" vec3 vy = py.xyz - LightPos;"
" vec4 sx = vec4(px.xyz + vx*10.0, 1.0);"
" vec4 sy = vec4(py.xyz + vy*10.0, 1.0);"
" vec4 cpx = CameraMatrix * px;"
" vec4 cpy = CameraMatrix * py;"
" vec4 csx = CameraMatrix * sx;"
" vec4 csy = CameraMatrix * sy;"
" gl_Position = ProjectionMatrix * cpy;"
" EmitVertex();"
" gl_Position = ProjectionMatrix * cpx;"
" EmitVertex();"
" gl_Position = ProjectionMatrix * csy;"
" EmitVertex();"
" gl_Position = ProjectionMatrix * csx;"
" EmitVertex();"
" EndPrimitive();"
" break;"
" }"
"}"
);
gs_shadow.Compile();
fs_shadow.Source(
"#version 150\n"
"out vec4 fragColor;"
"void main(void)"
"{"
" fragColor = vec4(0.0, 0.0, 0.0, 1.0);"
"}"
);
fs_shadow.Compile();
shadow_prog.AttachShader(vs_shadow);
shadow_prog.AttachShader(gs_shadow);
shadow_prog.AttachShader(fs_shadow);
shadow_prog.Link().Use();
shadow_projection_matrix.BindTo("ProjectionMatrix");
shadow_camera_matrix.BindTo("CameraMatrix");
shadow_model_matrix.BindTo("ModelMatrix");
// bind the VAO for the torus
torus.Bind();
// bind the VBO for the torus vertices
torus_verts.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Positions(data);
Buffer::Data(Buffer::Target::Array, data);
VertexArrayAttrib attr(
VertexArrayAttrib::GetCommonLocation(
MakeGroup(object_prog, shadow_prog),
"Position"
)
);
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VBO for the torus normals
torus_normals.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Normals(data);
Buffer::Data(Buffer::Target::Array, data);
object_prog.Use();
VertexArrayAttrib attr(object_prog, "Normal");
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VAO for the plane
plane.Bind();
// bind the VBO for the plane vertices
plane_verts.Bind(Buffer::Target::Array);
{
GLfloat data[4*3] = {
-9.0f, 0.0f, -9.0f,
-9.0f, 0.0f, 9.0f,
9.0f, 0.0f, -9.0f,
9.0f, 0.0f, 9.0f
};
Buffer::Data(Buffer::Target::Array, 4*3, data);
object_prog.Use();
VertexArrayAttrib attr(object_prog, "Position");
attr.Setup<GLfloat>(3);
attr.Enable();
}
// bind the VBO for the torus normals
plane_normals.Bind(Buffer::Target::Array);
{
GLfloat data[4*3] = {
-0.1f, 1.0f, 0.1f,
-0.1f, 1.0f, -0.1f,
0.1f, 1.0f, 0.1f,
0.1f, 1.0f, -0.1f
};
Buffer::Data(Buffer::Target::Array, 4*3, data);
object_prog.Use();
VertexArrayAttrib attr(object_prog, "Normal");
attr.Setup<GLfloat>(3);
attr.Enable();
}
Vec3f lightPos(2.0f, 9.0f, 3.0f);
ProgramUniform<Vec3f>(object_prog, "LightPos").Set(lightPos);
ProgramUniform<Vec3f>(shadow_prog, "LightPos").Set(lightPos);
gl.ClearColor(0.2f, 0.2f, 0.2f, 0.0f);
gl.ClearDepth(1.0f);
gl.ClearStencil(0);
gl.Enable(Capability::DepthTest);
gl.Enable(Capability::CullFace);
gl.FrontFace(make_torus.FaceWinding());
}
void Reshape(GLuint width, GLuint height)
{
gl.Viewport(width, height);
Mat4f projection = CamMatrixf::PerspectiveX(
Degrees(70),
float(width)/height,
1, 30
);
object_prog.Use();
object_projection_matrix.Set(projection);
shadow_prog.Use();
shadow_projection_matrix.Set(projection);
}
void Render(double time)
{
gl.Clear().ColorBuffer().DepthBuffer().StencilBuffer();
auto camera = CamMatrixf::Orbiting(
Vec3f(),
9.0,
FullCircles(time * 0.1),
Degrees(15 + (-SineWave(0.25+time/12.5)+1.0)* 0.5 * 75)
);
ModelMatrixf identity;
ModelMatrixf model =
ModelMatrixf::Translation(0.0f, 2.5f, 0.0) *
ModelMatrixf::RotationA(
Vec3f(1.0f, 1.0f, 1.0f),
FullCircles(time * 0.2)
);
gl.CullFace(Face::Back);
gl.ColorMask(true, true, true, true);
gl.DepthMask(true);
gl.Disable(Capability::StencilTest);
object_prog.Use();
object_camera_matrix.Set(camera);
object_light_mult.Set(0.2f);
object_model_matrix.Set(identity);
plane.Bind();
gl.DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
object_model_matrix.Set(model);
torus.Bind();
torus_instr.Draw(torus_indices);
gl.ColorMask(false, false, false, false);
gl.DepthMask(false);
gl.Enable(Capability::StencilTest);
gl.StencilFunc(CompareFunction::Always, 0);
gl.StencilOpSeparate(
Face::Front,
StencilOp::Keep,
StencilOp::Keep,
StencilOp::Incr
);
gl.StencilOpSeparate(
Face::Back,
StencilOp::Keep,
StencilOp::Keep,
StencilOp::Decr
);
shadow_prog.Use();
shadow_camera_matrix.Set(camera);
shadow_model_matrix.Set(model);
gl.CullFace(Face::Back);
torus_instr.Draw(torus_indices);
gl.CullFace(Face::Front);
torus_instr.Draw(torus_indices);
gl.CullFace(Face::Back);
gl.ColorMask(true, true, true, true);
gl.DepthMask(true);
gl.Clear().DepthBuffer();
gl.StencilFunc(CompareFunction::Equal, 0);
gl.StencilOp(StencilOp::Keep, StencilOp::Keep, StencilOp::Keep);
object_prog.Use();
object_light_mult.Set(2.5);
object_model_matrix.Set(identity);
object_color.Set(0.8f, 0.7f, 0.4f);
plane.Bind();
gl.DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
object_model_matrix.Set(model);
object_color.Set(0.9f, 0.8f, 0.1f);
torus.Bind();
torus_instr.Draw(torus_indices);
}
bool Continue(double time)
{
return time < 60.0;
}
};
void setupExample(ExampleParams& /*params*/){ }
std::unique_ptr<ExampleThread> makeExampleThread(
Example& /*example*/,
unsigned /*thread_id*/,
const ExampleParams& /*params*/
){ return std::unique_ptr<ExampleThread>(); }
std::unique_ptr<Example> makeExample(const ExampleParams& /*params*/)
{
return std::unique_ptr<Example>(new ShadowExample);
}
} // namespace oglplus
| 10,795 | 4,954 |
/*
* Copyright (c) 2017 Cisco and/or 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.
*/
#ifndef __VOM_L2_EMULATION_CMDS_H__
#define __VOM_L2_EMULATION_CMDS_H__
#include "vom/l2_emulation.hpp"
#include "vom/rpc_cmd.hpp"
#include <vapi/l2e.api.vapi.hpp>
namespace VOM {
namespace l2_emulation_cmds {
/**
* A functor class that enable L2 emulation to an interface
*/
class enable_cmd : public rpc_cmd<HW::item<bool>, vapi::L2_emulation>
{
public:
/**
* Constructor
*/
enable_cmd(HW::item<bool>& item, const handle_t& itf);
/**
* Issue the command to VPP/HW
*/
rc_t issue(connection& con);
/**
* convert to string format for debug purposes
*/
std::string to_string() const;
/**
* Comparison operator - only used for UT
*/
bool operator==(const enable_cmd& i) const;
private:
/**
* The interface to bind
*/
const handle_t m_itf;
};
/**
* A cmd class that Unbinds L2 configuration from an interface
*/
class disable_cmd : public rpc_cmd<HW::item<bool>, vapi::L2_emulation>
{
public:
/**
* Constructor
*/
disable_cmd(HW::item<bool>& item, const handle_t& itf);
/**
* Issue the command to VPP/HW
*/
rc_t issue(connection& con);
/**
* convert to string format for debug purposes
*/
std::string to_string() const;
/**
* Comparison operator - only used for UT
*/
bool operator==(const disable_cmd& i) const;
private:
/**
* The interface to bind
*/
const handle_t m_itf;
};
}; // namespace l2_emulation_cmds
}; // namespace VOM
/*
* fd.io coding-style-patch-verification: OFF
*
* Local Variables:
* eval: (c-set-style "mozilla")
* End:
*/
#endif
| 2,185 | 778 |
/*
Copyright (c) 2019 Agenium Scale
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 NSIMD_CXX_ADV_API_HPP
#define NSIMD_CXX_ADV_API_HPP
#include <nsimd/nsimd.h>
#include <ostream>
namespace nsimd {
// ----------------------------------------------------------------------------
// For ARM SVE we need a special struct
#ifdef NSIMD_SVE
#define NSIMD_STRUCT __sizeless_struct
#else
#define NSIMD_STRUCT struct
#endif
// ----------------------------------------------------------------------------
// Definition of pack
template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD>
NSIMD_STRUCT pack;
template <typename T, typename SimdExt>
NSIMD_STRUCT pack<T, 1, SimdExt> {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = 1;
simd_vector car;
// Default ctor
pack() {}
// Ctor that splats
template <typename S> pack(S const &s) { car = set1(T(s), T(), SimdExt()); }
// Ctor taking a SIMD vector
pack(simd_vector v) { car = v; }
// Underlying native SIMD vector getter
simd_vector native_register() const { return car; }
friend std::ostream &operator<<(std::ostream &os, pack const &a0) {
T buf[max_len_t<T>::value];
storeu(buf, a0.car, T(), SimdExt());
os << "{ ";
int n = len(a0);
for (int i = 0; i < n; i++) {
os << buf[i];
if (i < n - 1) {
os << ", ";
}
}
os << " }";
return os;
}
};
template <typename T, int N, typename SimdExt>
NSIMD_STRUCT pack {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = N;
simd_vector car;
pack<T, N - 1, SimdExt> cdr;
// Default ctor
pack() {}
// Ctor that splats
template <typename S> pack(S const &s) : cdr(s) {
car = set1(T(s), T(), SimdExt());
}
friend std::ostream &operator<<(std::ostream &os, pack const &a0) {
os << pack<T, 1, SimdExt>(a0.car) << ", " << a0.cdr;
return os;
}
};
// ----------------------------------------------------------------------------
// Definition of logical
template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD>
NSIMD_STRUCT packl;
template <typename T, typename SimdExt>
NSIMD_STRUCT packl<T, 1, SimdExt> {
typedef typename simd_traits<T, SimdExt>::simd_vectorl simd_vectorl;
simd_vectorl car;
// Default ctor
packl() {}
// Ctor taking a SIMD vector
packl(simd_vectorl v) { car = v; }
// Underlying native SIMD vector getter
simd_vectorl native_register() const { return car; }
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = 1;
};
template <typename T, int N, typename SimdExt>
NSIMD_STRUCT packl {
typename simd_traits<T, SimdExt>::simd_vectorl car;
packl<T, N - 1, SimdExt> cdr;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = N;
};
// ----------------------------------------------------------------------------
// Definition of SOA of degree 2
template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD>
NSIMD_STRUCT packx2;
template <typename T, typename SimdExt> NSIMD_STRUCT packx2<T, 1, SimdExt> {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = 1;
pack<T, 1, SimdExt> v0;
pack<T, 1, SimdExt> v1;
void set_car(simd_vector v0_, simd_vector v1_) {
v0.car = v0_;
v1.car = v1_;
}
};
template <typename T, int N, typename SimdExt> NSIMD_STRUCT packx2 {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = N;
pack<T, N, SimdExt> v0;
pack<T, N, SimdExt> v1;
void set_car(simd_vector v0_, simd_vector v1_) {
v0.car = v0_;
v1.car = v1_;
}
void set_cdr(pack<T, N - 1, SimdExt> const &v0_,
pack<T, N - 1, SimdExt> const &v1_) {
v0.cdr = v0_;
v1.cdr = v1_;
}
};
// ----------------------------------------------------------------------------
// Definition of SOA of degree 3
template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD>
NSIMD_STRUCT packx3;
template <typename T, typename SimdExt> NSIMD_STRUCT packx3<T, 1, SimdExt> {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = 1;
pack<T, 1, SimdExt> v0;
pack<T, 1, SimdExt> v1;
pack<T, 1, SimdExt> v2;
void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_) {
v0.car = v0_;
v1.car = v1_;
v2.car = v2_;
}
};
template <typename T, int N, typename SimdExt> NSIMD_STRUCT packx3 {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = N;
pack<T, N, SimdExt> v0;
pack<T, N, SimdExt> v1;
pack<T, N, SimdExt> v2;
void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_) {
v0.car = v0_;
v1.car = v1_;
v2.car = v2_;
}
void set_cdr(pack<T, N - 1, SimdExt> const &v0_,
pack<T, N - 1, SimdExt> const &v1_,
pack<T, N - 1, SimdExt> const &v2_) {
v0.cdr = v0_;
v1.cdr = v1_;
v2.cdr = v2_;
}
};
// ----------------------------------------------------------------------------
// Definition of SOA of degree 4
template <typename T, int N = 1, typename SimdExt = NSIMD_SIMD>
NSIMD_STRUCT packx4;
template <typename T, typename SimdExt> NSIMD_STRUCT packx4<T, 1, SimdExt> {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = 1;
pack<T, 1, SimdExt> v0;
pack<T, 1, SimdExt> v1;
pack<T, 1, SimdExt> v2;
pack<T, 1, SimdExt> v3;
void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_,
simd_vector v3_) {
v0.car = v0_;
v1.car = v1_;
v2.car = v2_;
v3.car = v3_;
}
};
template <typename T, int N, typename SimdExt>
NSIMD_STRUCT packx4 {
typedef typename simd_traits<T, SimdExt>::simd_vector simd_vector;
typedef T value_type;
typedef SimdExt simd_ext;
static const int unroll = N;
pack<T, N, SimdExt> v0;
pack<T, N, SimdExt> v1;
pack<T, N, SimdExt> v2;
pack<T, N, SimdExt> v3;
void set_car(simd_vector v0_, simd_vector v1_, simd_vector v2_,
simd_vector v3_) {
v0.car = v0_;
v1.car = v1_;
v2.car = v2_;
v3.car = v3_;
}
void set_cdr(pack<T, N - 1, SimdExt> const &v0_,
pack<T, N - 1, SimdExt> const &v1_,
pack<T, N - 1, SimdExt> const &v2_,
pack<T, N - 1, SimdExt> const &v3_) {
v0.cdr = v0_;
v1.cdr = v1_;
v2.cdr = v2_;
v3.cdr = v3_;
}
};
// ----------------------------------------------------------------------------
// The len function cannot be auto-generated
template <typename T, int N, typename SimdExt>
int len(pack<T, N, SimdExt> const &) {
return N * len(T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int len(packl<T, N, SimdExt> const &) {
return N * len(T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int len(packx2<T, N, SimdExt> const &) {
return 2 * N * len(T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int len(packx3<T, N, SimdExt> const &) {
return 3 * N * len(T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int len(packx4<T, N, SimdExt> const &) {
return 4 * N * len(T(), SimdExt());
}
// ----------------------------------------------------------------------------
// The addv function cannot be auto-generated
template <typename T, typename SimdExt>
T addv(pack<T, 1, SimdExt> const &a0) {
return addv(a0.car, T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
T addv(pack<T, N, SimdExt> const &a0) {
return addv(a0.car, T(), SimdExt()) + addv(a0.cdr);
}
// ----------------------------------------------------------------------------
// The all function cannot be auto-generated
template <typename T, typename SimdExt>
int all(packl<T, 1, SimdExt> const &a0) {
return all(a0.car, T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int all(packl<T, N, SimdExt> const &a0) {
return all(a0.car, T(), SimdExt()) && all(a0.cdr);
}
// ----------------------------------------------------------------------------
// The any function cannot be auto-generated
template <typename T, typename SimdExt>
int any(packl<T, 1, SimdExt> const &a0) {
return any(a0.car, T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int any(packl<T, N, SimdExt> const &a0) {
return any(a0.car, T(), SimdExt()) || any(a0.cdr);
}
// ----------------------------------------------------------------------------
// The nbtrue function cannot be auto-generated
template <typename T, typename SimdExt>
int nbtrue(packl<T, 1, SimdExt> const &a0) {
return nbtrue(a0.car, T(), SimdExt());
}
template <typename T, int N, typename SimdExt>
int nbtrue(packl<T, N, SimdExt> const &a0) {
return nbtrue(a0.car, T(), SimdExt()) + nbtrue(a0.cdr);
}
// ----------------------------------------------------------------------------
// Include functions that act on packs
} // namespace nsimd
#include <nsimd/cxx_adv_api_functions.hpp>
namespace nsimd {
// ----------------------------------------------------------------------------
// The if_else function cannot be auto-generated
template <typename L, typename T, typename SimdExt>
pack<T, 1, SimdExt> if_else(packl<L, 1, SimdExt> const &a0,
pack<T, 1, SimdExt> const &a1,
pack<T, 1, SimdExt> const &a2) {
pack<T, 1, SimdExt> ret;
ret.car = if_else(a0.car, a1.car, a2.car, L(), T(), SimdExt());
return ret;
}
template <typename L, typename T, int N, typename SimdExt>
pack<T, N, SimdExt> if_else(packl<L, N, SimdExt> const &a0,
pack<T, N, SimdExt> const &a1,
pack<T, N, SimdExt> const &a2) {
pack<T, N, SimdExt> ret;
ret.car = if_else(a0.car, a1.car, a2.car, L(), T(), SimdExt());
ret.cdr = if_else(a0.cdr, a1.cdr, a2.cdr);
return ret;
}
// ----------------------------------------------------------------------------
// Loads/Stores templated on the alignment cannot be auto-generated
namespace detail {
template <typename SimdVector, typename Alignment> struct load_helper {};
template <typename SimdVector> struct load_helper<SimdVector, aligned> {
template <typename A0> static SimdVector load(A0 a0) {
return loada<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector loadl(A0 a0) {
return loadla<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector load2(A0 a0) {
return load2a<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector load3(A0 a0) {
return load3a<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector load4(A0 a0) {
return load4a<SimdVector, A0>(a0);
}
};
template <typename SimdVector> struct load_helper<SimdVector, unaligned> {
template <typename A0> static SimdVector load(A0 a0) {
return loadu<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector loadl(A0 a0) {
return loadlu<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector load2(A0 a0) {
return load2u<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector load3(A0 a0) {
return load3u<SimdVector, A0>(a0);
}
template <typename A0> static SimdVector load4(A0 a0) {
return load4u<SimdVector, A0>(a0);
}
};
template <typename SimdVector, typename Alignment> struct store_helper {};
template <typename SimdVector> struct store_helper<SimdVector, aligned> {
template <typename A0, typename A1> static SimdVector store(A0 a0, A1 a1) {
storea<SimdVector, A0, A1>(a0, a1);
}
template <typename A0, typename A1> static SimdVector storel(A0 a0, A1 a1) {
storela<SimdVector, A0, A1>(a0, a1);
}
template <typename A0, typename A1, typename A2>
static SimdVector store2(A0 a0, A1 a1, A2 a2) {
store2a<SimdVector, A0, A1, A2>(a0, a1, a2);
}
template <typename A0, typename A1, typename A2, typename A3>
static SimdVector store3(A0 a0, A1 a1, A2 a2, A3 a3) {
store3a<SimdVector, A0, A1, A2, A3>(a0, a1, a2, a3);
}
template <typename A0, typename A1, typename A2, typename A3, typename A4>
static SimdVector store4(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
store4a<SimdVector, A0>(a0, a1, a2, a3, a4);
}
};
template <typename SimdVector> struct store_helper<SimdVector, unaligned> {
template <typename A0, typename A1> static SimdVector store(A0 a0, A1 a1) {
storeu<SimdVector, A0, A1>(a0, a1);
}
template <typename A0, typename A1> static SimdVector storel(A0 a0, A1 a1) {
storelu<SimdVector, A0, A1>(a0, a1);
}
template <typename A0, typename A1, typename A2>
static SimdVector store2(A0 a0, A1 a1, A2 a2) {
store2u<SimdVector, A0, A1, A2>(a0, a1, a2);
}
template <typename A0, typename A1, typename A2, typename A3>
static SimdVector store3(A0 a0, A1 a1, A2 a2, A3 a3) {
store3u<SimdVector, A0, A1, A2, A3>(a0, a1, a2, a3);
}
template <typename A0, typename A1, typename A2, typename A3, typename A4>
static SimdVector store4(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
store4u<SimdVector, A0>(a0, a1, a2, a3, a4);
}
};
} // namespace detail
template <typename SimdVector, typename Alignment, typename A0>
SimdVector load(A0 a0) {
return detail::load_helper<SimdVector, Alignment>::load(a0);
}
template <typename SimdVector, typename Alignment, typename A0>
SimdVector loadl(A0 a0) {
return detail::load_helper<SimdVector, Alignment>::loadl(a0);
}
template <typename SimdVector, typename Alignment, typename A0>
SimdVector load2(A0 a0) {
return detail::load_helper<SimdVector, Alignment>::load2(a0);
}
template <typename SimdVector, typename Alignment, typename A0>
SimdVector load3(A0 a0) {
return detail::load_helper<SimdVector, Alignment>::load3(a0);
}
template <typename SimdVector, typename Alignment, typename A0>
SimdVector load4(A0 a0) {
return detail::load_helper<SimdVector, Alignment>::load4(a0);
}
template <typename SimdVector, typename Alignment, typename A0, typename A1>
SimdVector store(A0 a0, A1 a1) {
detail::store_helper<SimdVector, Alignment>::store(a0, a1);
}
template <typename SimdVector, typename Alignment, typename A0, typename A1>
SimdVector storel(A0 a0, A1 a1) {
return detail::store_helper<SimdVector, Alignment>::storel(a0, a1);
}
template <typename SimdVector, typename Alignment, typename A0, typename A1,
typename A2>
SimdVector store2(A0 a0, A1 a1, A2 a2) {
return detail::store_helper<SimdVector, Alignment>::store2(a0, a1, a2);
}
template <typename SimdVector, typename Alignment, typename A0, typename A1,
typename A2, typename A3>
SimdVector store3(A0 a0, A1 a1, A2 a2, A3 a3) {
return detail::store_helper<SimdVector, Alignment>::store3(a0, a1, a2, a3);
}
template <typename SimdVector, typename Alignment, typename A0, typename A1,
typename A2, typename A3, typename A4>
SimdVector store4(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
return detail::store_helper<SimdVector, Alignment>::store4(a0, a1, a2, a3,
a4);
}
// ----------------------------------------------------------------------------
template <typename T> T native_register(T a) { return a; }
template <typename T, typename SimdExt>
typename pack<T, 1, SimdExt>::simd_vector
native_register(pack<T, 1, SimdExt> const &a) {
return a.car;
}
} // namespace nsimd
#endif
| 16,716 | 6,493 |
//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_genparams.hpp
* @brief iris unit test parameter generator
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2011-2021, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_GENPARAMS_HPP_7845F59A_825C_426A_B451_573245408998_
#define INCG_IRIS_IUTEST_GENPARAMS_HPP_7845F59A_825C_426A_B451_573245408998_
#if IUTEST_HAS_PARAM_TEST
namespace iutest {
namespace detail
{
//======================================================================
// declare
#if IUTEST_HAS_CONCAT
template<typename Generator1, typename Generator2>class iuConcatParamHolder;
#endif
//======================================================================
// class
/**
* @brief パラメータ生成器インターフェイス
*/
template<typename T>
class iuIParamGenerator
{
public:
typedef T type;
public:
typedef iuIParamGenerator<T>* (*Generator)();
public:
virtual ~iuIParamGenerator() {}
public:
virtual void Begin() = 0; //!< パラメータリストの先頭に移動
virtual T GetCurrent() const = 0; //!< 現在のパラメータを取得
virtual void Next() = 0; //!< パラメータを取得して次に移動
virtual bool IsEnd() const = 0; //!< パラメータリストの終端にいるかどうか
};
/**
* @brief パラメータ生成器保持クラス
*/
template<typename T>
class iuParamGenerator IUTEST_CXX_FINAL : public iuIParamGenerator<T>
{
typedef iuIParamGenerator<T> _Interface;
typedef iuParamGenerator<T> _Myt;
public:
typedef T type;
public:
iuParamGenerator(_Interface* pInterface=NULL) : m_pInterface(pInterface) {} // NOLINT
public:
operator iuIParamGenerator<T>* () const { return m_pInterface; }
public:
#if IUTEST_HAS_CONCAT
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
#endif
public:
virtual void Begin() IUTEST_CXX_OVERRIDE { m_pInterface->Begin(); }
virtual T GetCurrent() const IUTEST_CXX_OVERRIDE { return m_pInterface->GetCurrent(); }
virtual void Next() IUTEST_CXX_OVERRIDE { m_pInterface->Next(); }
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return m_pInterface->IsEnd(); }
private:
_Interface* m_pInterface;
};
/**
* @brief 範囲パラメータ生成器
* @tparam T = パラメータ型
*/
template<typename T>
class iuRangeParamsGenerator IUTEST_CXX_FINAL : public iuIParamGenerator<T>
{
T m_begin;
T m_end;
T m_step;
T m_cur;
public:
/**
* @brief コンストラクタ
* @param [in] begin = 開始値
* @param [in] end = 終了値
* @param [in] step = 増値
*/
iuRangeParamsGenerator(T begin, T end, T step)
: m_begin(begin)
, m_end(end)
, m_step(step)
, m_cur(begin)
{
}
public:
virtual void Begin() IUTEST_CXX_OVERRIDE { m_cur = m_begin; }
virtual T GetCurrent() const IUTEST_CXX_OVERRIDE { return m_cur; }
virtual void Next() IUTEST_CXX_OVERRIDE { m_cur = static_cast<T>(m_cur + m_step); }
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return !(m_cur < m_end); }
};
/**
* @brief 真偽値パラメータ生成器
*/
class iuBoolParamsGenerator IUTEST_CXX_FINAL : public iuIParamGenerator<bool>
{
int m_n;
bool m_cur;
public:
iuBoolParamsGenerator()
: m_n(0)
, m_cur(false)
{}
public:
virtual void Begin() IUTEST_CXX_OVERRIDE { m_cur = false; m_n = 0; }
virtual bool GetCurrent() const IUTEST_CXX_OVERRIDE { return m_cur; }
virtual void Next() IUTEST_CXX_OVERRIDE { ++m_n; m_cur = !m_cur; }
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return m_n >= 2; }
};
/**
* @brief 値配列パラメータ生成器
* @tparam T = パラメータ型
*/
template<typename T>
class iuValuesInParamsGenerator : public iuIParamGenerator<T>
{
typedef ::std::vector<T> params_t;
params_t m_values;
typename params_t::const_iterator m_it;
public:
explicit iuValuesInParamsGenerator(const params_t& values)
: m_values(values) {}
template<typename Container>
explicit iuValuesInParamsGenerator(const Container& values)
{
m_values.insert(m_values.end(), values.begin(), values.end());
}
#if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING)
template<typename TT, size_t SIZE>
explicit iuValuesInParamsGenerator(const TT (&values)[SIZE])
{
m_values.insert(m_values.end(), values, values + SIZE);
}
#endif
template<typename Ite>
iuValuesInParamsGenerator(Ite begin, Ite end)
{
m_values.insert(m_values.end(), begin, end);
}
#if IUTEST_HAS_INITIALIZER_LIST
iuValuesInParamsGenerator(::std::initializer_list<T> l)
{
m_values.insert(m_values.end(), l.begin(), l.end());
}
#endif
public:
virtual void Begin() IUTEST_CXX_OVERRIDE { m_it = m_values.begin(); }
virtual T GetCurrent() const IUTEST_CXX_OVERRIDE { return *m_it; }
virtual void Next() IUTEST_CXX_OVERRIDE { ++m_it; }
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE { return (m_it == m_values.end()); }
};
#if IUTEST_HAS_CONCAT
/**
* @brief パラメータ生成器加算保持クラス
*/
template<typename G1, typename G2>
class iuConcatParamHolder
{
typedef iuConcatParamHolder<G1, G2> _Myt;
public:
iuConcatParamHolder(const G1& g1, const G2& g2)
: m_g1(g1), m_g2(g2) {}
private:
iuConcatParamHolder() IUTEST_CXX_DELETED_FUNCTION;
public:
template<typename T>
operator iuIParamGenerator<T>* ()
{
params_t<T> params;
params.append(m_g1);
params.append(m_g2);
return new iuValuesInParamsGenerator<T>(params.val);
}
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
private:
template<typename T>
struct params_t
{
typedef iuIParamGenerator<T> IParamGenerater;
::std::vector<T> val;
void append(IParamGenerater* gen)
{
detail::scoped_ptr<IParamGenerater> p(gen);
for( p->Begin(); !p->IsEnd(); p->Next() )
{
val.push_back(p->GetCurrent());
}
}
template<typename U>
void append(iuParamGenerator<U>& gen)
{
for( gen.Begin(); !gen.IsEnd(); gen.Next() )
{
val.push_back(static_cast<T>(gen.GetCurrent()));
}
}
};
private:
G1 m_g1;
G2 m_g2;
};
#endif
#if IUTEST_HAS_VARIADIC_VALUES
template<typename... Args>
class iuValueArray
{
typedef tuples::tuple<Args...> _MyTuple;
typedef iuValueArray<Args...> _Myt;
template<typename T>
struct make_array
{
T val[sizeof...(Args)];
template<typename U>
void operator ()(int index, const U& value) { val[index] = value; }
explicit make_array(const _MyTuple& t)
{
tuples::tuple_foreach(t, *this);
}
};
public:
explicit iuValueArray(const Args&... args)
: v(args...)
{}
#if defined(__clang__) && defined(IUTEST_LIBSTDCXX_VERSION) && IUTEST_LIBSTDCXX_VERSION >= 40900
#if IUTEST_HAS_RVALUE_REFS
// https://stackoverflow.com/questions/23374953/why-does-this-exceed-the-maximum-recursive-template-depth
iuValueArray(const iuValueArray& rhs)
: v(rhs.v) {}
iuValueArray(iuValueArray&& rhs)
: v(rhs.v) {}
#endif
#endif
public:
template<typename T>
operator iuIParamGenerator<T>* () const
{
make_array<T> ar(v);
#if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING)
return new iuValuesInParamsGenerator<T>(ar.val);
#else
return new iuValuesInParamsGenerator<T>(ar.val, ar.val + IUTEST_PP_COUNTOF(ar.val));
#endif
}
public:
#if IUTEST_HAS_CONCAT
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
#endif
private:
_MyTuple v;
};
#else
/*
template<typename A1, typename A2>
class iuValueArray2
{
typedef iuValueArray2<A1, A2> _Myt;
public:
iuValueArray2(A1 a1, A2 a2) : v1(a1), v2(a2)
{}
public:
template<typename T>
operator iuIParamGenerator<T>* () const
{
const T val[] = { static_cast<T>(v1), static_cast<T>(v2) };
return new iuValuesInParamsGenerator<T>(val);
}
public:
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
private:
A1 v1; A2 v2;
};
*/
/**
* @private
* @{
*/
#define IIUT_DECL_VALUEARRAY_CONSTRUCT_(i, p1, p2) IUTEST_PP_CAT(p1, i)(IUTEST_PP_CAT(p2, i))
#define IIUT_DECL_VALUEARRAY_STATICCAST_(i, p1, p2) static_cast<p1>(IUTEST_PP_CAT(p2, i))
#define IIUT_DECL_VALUEARRAY_VARIABLE_(i, p1, p2) IUTEST_PP_CAT(p1, i) IUTEST_PP_CAT(p2, i);
#if IUTEST_HAS_CONCAT
# define IIUT_DECL_VALUEARRAY_CONCAT_() \
template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { \
return iuConcatParamHolder<_Myt, Other>(*this, g); }
#else
# define IIUT_DECL_VALUEARRAY_CONCAT_()
#endif
#define IIUT_DECL_VALUEARRAY_(n) \
template< IUTEST_PP_ENUM_PARAMS(n, typename A) > \
class IUTEST_PP_CAT(iuValueArray, n) { \
typedef IUTEST_PP_CAT(iuValueArray, n)< IUTEST_PP_ENUM_PARAMS(n, A) > _Myt; \
public: \
IUTEST_PP_CAT(iuValueArray, n)( IUTEST_PP_ENUM_BINARY_PARAMS(n, A, a) ) \
: IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_VALUEARRAY_CONSTRUCT_, v, a) {} \
template<typename T>operator iuIParamGenerator<T>* () const { \
const T val[] = { IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_VALUEARRAY_STATICCAST_, T, v) }; \
return new iuValuesInParamsGenerator<T>(val); \
} \
IIUT_DECL_VALUEARRAY_CONCAT_() \
private: IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_VALUEARRAY_VARIABLE_, A, v) \
}
/**
* @}
*/
IIUT_DECL_VALUEARRAY_(1);
IIUT_DECL_VALUEARRAY_(2);
IIUT_DECL_VALUEARRAY_(3);
IIUT_DECL_VALUEARRAY_(4);
IIUT_DECL_VALUEARRAY_(5);
IIUT_DECL_VALUEARRAY_(6);
IIUT_DECL_VALUEARRAY_(7);
IIUT_DECL_VALUEARRAY_(8);
IIUT_DECL_VALUEARRAY_(9);
IIUT_DECL_VALUEARRAY_(10);
IIUT_DECL_VALUEARRAY_(11);
IIUT_DECL_VALUEARRAY_(12);
IIUT_DECL_VALUEARRAY_(13);
IIUT_DECL_VALUEARRAY_(14);
IIUT_DECL_VALUEARRAY_(15);
IIUT_DECL_VALUEARRAY_(16);
IIUT_DECL_VALUEARRAY_(17);
IIUT_DECL_VALUEARRAY_(18);
IIUT_DECL_VALUEARRAY_(19);
IIUT_DECL_VALUEARRAY_(20);
IIUT_DECL_VALUEARRAY_(21);
IIUT_DECL_VALUEARRAY_(22);
IIUT_DECL_VALUEARRAY_(23);
IIUT_DECL_VALUEARRAY_(24);
IIUT_DECL_VALUEARRAY_(25);
IIUT_DECL_VALUEARRAY_(26);
IIUT_DECL_VALUEARRAY_(27);
IIUT_DECL_VALUEARRAY_(28);
IIUT_DECL_VALUEARRAY_(29);
IIUT_DECL_VALUEARRAY_(30);
IIUT_DECL_VALUEARRAY_(31);
IIUT_DECL_VALUEARRAY_(32);
IIUT_DECL_VALUEARRAY_(33);
IIUT_DECL_VALUEARRAY_(34);
IIUT_DECL_VALUEARRAY_(35);
IIUT_DECL_VALUEARRAY_(36);
IIUT_DECL_VALUEARRAY_(37);
IIUT_DECL_VALUEARRAY_(38);
IIUT_DECL_VALUEARRAY_(39);
IIUT_DECL_VALUEARRAY_(40);
IIUT_DECL_VALUEARRAY_(41);
IIUT_DECL_VALUEARRAY_(42);
IIUT_DECL_VALUEARRAY_(43);
IIUT_DECL_VALUEARRAY_(44);
IIUT_DECL_VALUEARRAY_(45);
IIUT_DECL_VALUEARRAY_(46);
IIUT_DECL_VALUEARRAY_(47);
IIUT_DECL_VALUEARRAY_(48);
IIUT_DECL_VALUEARRAY_(49);
IIUT_DECL_VALUEARRAY_(50);
#undef IIUT_DECL_VALUEARRAY_CONSTRUCT_
#undef IIUT_DECL_VALUEARRAY_STATICCAST_
#undef IIUT_DECL_VALUEARRAY_VARIABLE_
#undef IIUT_DECL_VALUEARRAY_CONCAT_
#undef IIUT_DECL_VALUEARRAY_
#endif
#if IUTEST_HAS_COMBINE
#if IUTEST_HAS_VARIADIC_COMBINE
template<typename... Args>
class iuCartesianProductGenerator IUTEST_CXX_FINAL : public iuIParamGenerator< tuples::tuple<Args...> >
{
typedef tuples::tuple< iuParamGenerator<Args>... > _MyTuple;
static const int kCount = sizeof...(Args);
struct begin_func
{
template<typename T>
void operator ()(int, T& value) const { value.Begin(); }
};
template<int index, int end, typename Tuple>
bool is_end_foreach(Tuple& t
, typename detail::enable_if<index != end, void>::type*& = detail::enabler::value ) const
{
const bool b = tuples::get<index>(t).IsEnd();
return b && is_end_foreach<index+1, end>(t);
}
template<int index, int end, typename Tuple>
bool is_end_foreach(Tuple&
, typename detail::enable_if<index == end, void>::type*& = detail::enabler::value ) const
{
return true;
}
template<int index, int end, typename Tuple>
void next_foreach(Tuple& t
, typename detail::enable_if<index != end, void>::type*& = detail::enabler::value )
{
next_foreach<index+1, end>(t);
if( is_end_foreach<index+1, end>(t) )
{
tuples::get<index>(t).Next();
if( !tuples::get<index>(t).IsEnd() )
{
tuples::tuple_foreach<index + 1>(t, begin_func());
}
}
}
template<int index, int end, typename Tuple>
void next_foreach(Tuple&
, typename detail::enable_if<index == end, void>::type*& = detail::enabler::value )
{
}
template<int index, int end, typename T1, typename ...TArgs>
tuples::tuple<T1, TArgs...> current_foreach(
typename detail::enable_if<index != end-1, void>::type*& = detail::enabler::value ) const
{
return ::std::tuple_cat( tuples::tuple<T1>(tuples::get<index>(v).GetCurrent())
, current_foreach<index+1, end, TArgs...>());
}
template<int index, int end, typename T1, typename ...TArgs>
tuples::tuple<T1> current_foreach(
typename detail::enable_if<index == end-1, void>::type*& = detail::enabler::value ) const
{
return tuples::tuple<T1>(tuples::get<index>(v).GetCurrent());
}
public:
typedef tuples::tuple<Args...> ParamType;
public:
iuCartesianProductGenerator() {}
public:
virtual void Begin() IUTEST_CXX_OVERRIDE
{
tuples::tuple_foreach(v, begin_func());
}
virtual void Next() IUTEST_CXX_OVERRIDE
{
if( !IsEnd() )
{
next_foreach<0, kCount>(v);
}
}
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE
{
return is_end_foreach<0, kCount>(v);
}
virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE
{
return current_foreach<0, kCount, Args...>();
}
_MyTuple& generators() { return v; }
private:
_MyTuple v;
};
template<typename... Generator>
class iuCartesianProductHolder
{
typedef iuCartesianProductHolder<Generator...> _Myt;
typedef tuples::tuple<const Generator...> _MyTuple;
public:
explicit iuCartesianProductHolder(const Generator&... generators)
: v(generators...) {}
public:
template<typename... Args>
operator iuIParamGenerator< tuples::tuple<Args...> >* () const
{
iuCartesianProductGenerator<Args...>* p = new iuCartesianProductGenerator<Args...>();
tuples::tuple_cast_copy(p->generators(), v);
return p;
}
public:
#if IUTEST_HAS_CONCAT
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
#endif
private:
_Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION;
private:
_MyTuple v;
};
#else
template<typename Generator1, typename Generator2, typename ParamType>
class iuICartesianProductGeneratorBase : public iuIParamGenerator< ParamType >
{
public:
iuICartesianProductGeneratorBase(const Generator1& g1, const Generator2& g2)
: m_g1(g1), m_g2(g2)
{}
public:
virtual void Begin() IUTEST_CXX_OVERRIDE
{
m_g1.Begin();
m_g2.Begin();
}
virtual void Next() IUTEST_CXX_OVERRIDE
{
if( m_g2.IsEnd() )
{
return;
}
m_g2.Next();
if( m_g2.IsEnd() )
{
m_g1.Next();
if( !m_g1.IsEnd() )
{
m_g2.Begin();
}
}
}
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE
{
return m_g1.IsEnd() && m_g2.IsEnd();
}
protected:
Generator1 m_g1;
Generator2 m_g2;
};
template<typename T1, typename T2>
class iuCartesianProductGenerator2
: public iuICartesianProductGeneratorBase<iuParamGenerator<T1>, iuParamGenerator<T2>, tuples::tuple<T1, T2> >
{
typedef iuICartesianProductGeneratorBase<iuParamGenerator<T1>, iuParamGenerator<T2>, tuples::tuple<T1, T2> > _Mybase;
typedef iuParamGenerator<T1> Generator1;
typedef iuParamGenerator<T2> Generator2;
public:
typedef tuples::tuple<T1, T2> ParamType;
public:
iuCartesianProductGenerator2(const Generator1 &g1, const Generator2 &g2)
: _Mybase(g1, g2)
{}
public:
virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE
{
return ParamType(this->m_g1.GetCurrent(), this->m_g2.GetCurrent());
}
};
/*
template<typename T1, typename T2, typename T3>
class iuCartesianProductGenerator3 IUTEST_CXX_FINAL
: public iuICartesianProductGeneratorBase<iuParamGenerator<T1>
, iuCartesianProductGenerator2<T2, T3>
, tuples::tuple<T1, T2, T3> >
{
typedef iuICartesianProductGeneratorBase<iuParamGenerator<T1>, iuCartesianProductGenerator2<T2, T3>, tuples::tuple<T1, T2, T3> > _Mybase;
typedef iuParamGenerator<T1> Generator1;
typedef iuParamGenerator<T2> Generator2;
typedef iuParamGenerator<T3> Generator3;
public:
typedef tuples::tuple<T1, T2, T3> ParamType;
public:
iuCartesianProductGenerator3(const Generator1& g1, const Generator2& g2, const Generator3& g3)
: _Mybase(g1, iuCartesianProductGenerator2<T2, T3>(g2, g3))
{}
public:
virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE
{
tuples::tuple<T2, T3> param(this->m_g2.GetCurrent());
return ParamType(this->m_g1.GetCurrent(), tuples::get<0>(param), tuples::get<1>(param) );
}
};
*/
/**
* @private
* @{
*/
#define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TYPEDEF_(i, p1, p2) \
typedef iuParamGenerator<IUTEST_PP_CAT(p1, i)> IUTEST_PP_CAT(p2, i);
#define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TUPLEGET_(i, param) \
tuples::get<i>(param)
#define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_(n) \
iuICartesianProductGeneratorBase< iuParamGenerator<T0> \
, IUTEST_PP_CAT(iuCartesianProductGenerator, IUTEST_PP_DEC(n))< \
IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), T) > \
, tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > >
#define IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(n) \
template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \
class IUTEST_PP_CAT(iuCartesianProductGenerator, n) \
: public IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_(n) { \
typedef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_(n) _Mybase; \
IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TYPEDEF_, T, Generator) \
public: \
typedef tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > ParamType; \
IUTEST_PP_CAT(iuCartesianProductGenerator, n)( IUTEST_PP_ENUM_BINARY_PARAMS(n, const Generator, &g) ) \
: _Mybase(g0, IUTEST_PP_CAT(iuCartesianProductGenerator, IUTEST_PP_DEC(n))< \
IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), T)> \
( IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), g) ) ) {} \
virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE { \
tuples::tuple< IUTEST_PP_ENUM_SHIFTED_PARAMS(IUTEST_PP_DEC(n), T) > \
params(this->m_g2.GetCurrent()); \
return ParamType(this->m_g1.GetCurrent(), IUTEST_PP_ENUM(IUTEST_PP_DEC(n) \
, IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TUPLEGET_, params) ); \
} \
}
/**
* @}
*/
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(3);
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(4);
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(5);
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(6);
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(7);
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(8);
IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_(9);
#undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TYPEDEF_
#undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_TUPLEGET_
#undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_BASE_
#undef IIUT_DECL_CARTESIAN_PRODUCT_GENERATOR_
// iuCartesianProductHolder
/*
template<typename Generator1, typename Generator2>
class iuCartesianProductHolder2
{
typedef iuCartesianProductHolder2<Generator1, Generator2> _Myt;
public:
iuCartesianProductHolder2(const Generator1& g1, const Generator2& g2)
: m_g1(g1), m_g2(g2) {}
public:
template<typename T1, typename T2>
operator iuIParamGenerator< tuples::tuple<T1, T2> >* () const
{
return new iuCartesianProductGenerator2<T1, T2>(
static_cast< iuIParamGenerator<T1>* >(m_g1)
, static_cast< iuIParamGenerator<T2>* >(m_g2)
);
}
public:
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
private:
_Myt& operator = (const _Myt&);
private:
const Generator1 m_g1;
const Generator2 m_g2;
};
*/
/**
* @private
* @{
*/
#define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONSTRUCT_(i, p1, p2) IUTEST_PP_CAT(p1, i)(IUTEST_PP_CAT(p2, i))
#define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_STATICCAST_(i, p1, p2) \
static_cast< iuIParamGenerator< IUTEST_PP_CAT(p1, i) >* >(IUTEST_PP_CAT(p2, i))
#define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_VARIABLE_(i, p1, p2) IUTEST_PP_CAT(p1, i) IUTEST_PP_CAT(p2, i);
#if IUTEST_HAS_CONCAT
#define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_() \
template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { \
return iuConcatParamHolder<_Myt, Other>(*this, g); }
#else
#define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_()
#endif
#define IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(n) \
template< IUTEST_PP_ENUM_PARAMS(n, typename Generator) > \
class IUTEST_PP_CAT(iuCartesianProductHolder, n) { \
typedef IUTEST_PP_CAT(iuCartesianProductHolder, n)< IUTEST_PP_ENUM_PARAMS(n, Generator) > _Myt; \
public: \
IUTEST_PP_CAT(iuCartesianProductHolder, n)( IUTEST_PP_ENUM_BINARY_PARAMS(n, const Generator, &g) ) \
: IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONSTRUCT_, m_g, g) {} \
template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \
operator iuIParamGenerator< tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > >* () const { \
return new IUTEST_PP_CAT(iuCartesianProductGenerator, n)< IUTEST_PP_ENUM_PARAMS(n, T) >( \
IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_STATICCAST_, T, m_g) ); \
} \
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_() \
private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; \
IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_VARIABLE_, const Generator, m_g) \
}
/**
* @}
*/
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(2);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(3);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(4);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(5);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(6);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(7);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(8);
IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_(9);
#undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONSTRUCT_
#undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_STATICCAST_
#undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_VARIABLE_
#undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_CONCAT_
#undef IIUT_DECL_CARTESIAN_PRODUCT_HOLDER_
#endif
#endif
#if IUTEST_HAS_PAIRWISE
class iuPairwiseGeneratorBase
{
protected:
template<int N>
struct ParamIndexes
{
int index[N];
ParamIndexes() { for( int i=0; i < N; ++i ) index[i] = -1; }
};
private:
struct PairInfo {
PairInfo(int r1, int r2, int i1, int i2)
: raw1(r1), raw2(r2), idx1(i1), idx2(i2) {}
int raw1, raw2; // 列のペア
int idx1, idx2; // インデックスのペア
};
protected:
template<typename T1>
static void MakeParamVector( ::std::vector<T1>& list, iuParamGenerator<T1>& g1)
{
for( g1.Begin(); !g1.IsEnd(); g1.Next() )
{
list.push_back(g1.GetCurrent());
}
}
template<typename T1, typename T2>
static void MakePairList( ::std::vector< ::std::pair<T1, T2> >& list
, iuParamGenerator<T1>& g1, iuParamGenerator<T2>& g2)
{
for( g1.Begin(); !g1.IsEnd(); g1.Next() )
{
T1 t1 = g1.GetCurrent();
for( g2.Begin(); !g2.IsEnd(); g2.Next() )
{
#if IUTEST_HAS_STD_EMPLACE
list.emplace_back(t1, g2.GetCurrent());
#else
list.push_back(::std::pair<T1, T2>(t1, g2.GetCurrent()));
#endif
}
}
}
template<int N>
static void MakeIndexList( ::std::vector< ParamIndexes<N> >& list, int* count_list)
{
typedef typename ::std::vector< ParamIndexes<N> >::iterator list_iterator;
list.clear();
// ペアを列挙
::std::vector<PairInfo> pair_list;
for( int i=0; i < N; ++i )
{
int l = count_list[i];
for( int j=i+1; j < N; ++j )
{
int r = count_list[j];
for( int li=0; li < l; ++li )
{
for( int ri=0; ri < r; ++ri )
{
#if IUTEST_HAS_STD_EMPLACE
pair_list.emplace_back(i, j, li, ri);
#else
PairInfo info( i, j, li, ri );
pair_list.push_back(info);
#endif
}
}
}
}
// シャッフル
iuRandom random;
unsigned int seed = TestEnv::get_random_seed();
if( seed != 0 )
{
random.init(seed);
}
random.shuffle(pair_list.begin(), pair_list.end());
for( ::std::vector<PairInfo>::const_iterator it=pair_list.begin(); it != pair_list.end(); ++it )
{
const PairInfo& pair_info = *it;
list_iterator find = Find(list, pair_info, list.begin());
if( find == list.end() )
{
find = FindFree(list, pair_info, list.begin());
if( find == list.end() )
{
// 空きが無いので作る
ParamIndexes<N> params;
params.index[pair_info.raw1] = pair_info.idx1;
params.index[pair_info.raw2] = pair_info.idx2;
list.push_back(params);
}
else
{
// 埋める
ParamIndexes<N>& params = *find;
params.index[pair_info.raw1] = pair_info.idx1;
params.index[pair_info.raw2] = pair_info.idx2;
}
}
}
//for( list_iterator it=list.begin(), end=list.end(); it != end; ++it )
//{
// for( int i=0; i < N; ++i ) printf("%2d ", it->index[i]);
// printf("\n");
//}
}
template<int N, typename Fn>
static int GetParamIndex(const ParamIndexes<N>& indexes, int raw, int count, Fn& func)
{
return indexes.index[raw] == -1 ? func(count)
: indexes.index[raw];
}
template<int N, typename T>
static T GetParam(const ::std::vector<T>& params, const ParamIndexes<N>& indexes, int raw)
{
iuTypedRandom<int> rnd(TestEnv::genrand()());
const int index = GetParamIndex(indexes, raw, static_cast<int>(params.size()), rnd);
return params[index];
}
private:
template<int N>
static typename ::std::vector< ParamIndexes<N> >::iterator Find( ::std::vector< ParamIndexes<N> >& list
, const PairInfo& pair_info, typename ::std::vector< ParamIndexes<N> >::iterator start)
{
typedef typename ::std::vector< ParamIndexes<N> >::iterator iterator;
for( iterator it = start, end=list.end(); it != end; ++it )
{
ParamIndexes<N>& indexes = *it;
if( indexes.index[pair_info.raw1] == pair_info.idx1
&& indexes.index[pair_info.raw2] == pair_info.idx2 )
{
return it;
}
}
return list.end();
}
template<int N>
static typename ::std::vector< ParamIndexes<N> >::iterator FindFree( ::std::vector< ParamIndexes<N> >& list
, const PairInfo& pair_info, typename ::std::vector< ParamIndexes<N> >::iterator start)
{
// 入れそうなとこを探す
typedef typename ::std::vector< ParamIndexes<N> >::iterator iterator;
iterator find = list.end();
UInt32 max_overlap = static_cast<UInt32>(-1);
for( iterator it = start, end=list.end(); it != end; ++it )
{
ParamIndexes<N>& indexes = *it;
int free_raw = -1;
int free_idx = -1;
if( indexes.index[pair_info.raw1] == -1 && indexes.index[pair_info.raw2] == pair_info.idx2 )
{
free_raw = pair_info.raw1;
free_idx = pair_info.idx1;
}
if( indexes.index[pair_info.raw2] == -1 && indexes.index[pair_info.raw1] == pair_info.idx1 )
{
free_raw = pair_info.raw2;
free_idx = pair_info.idx2;
}
if( free_raw != -1 )
{
// 仮に入ったとして重複がないか調べる
UInt32 overlap = 0;
for( int i=0; i < N; ++i )
{
if( indexes.index[i] == -1 || i == free_raw )
{
continue;
}
PairInfo tmp(i, free_raw, indexes.index[i], free_idx);
iterator it2 = Find(list, tmp, list.begin());
while(it2 != end)
{
++overlap;
++it2;
it2 = Find(list, tmp, it2);
}
}
if( overlap == 0 )
{
return it;
}
if( find == list.end()
|| (overlap < max_overlap) )
{
find = it;
max_overlap = overlap;
}
}
}
if( find != list.end() )
{
return find;
}
typedef typename ::std::vector< ParamIndexes<N> >::iterator iterator;
for( iterator it = start, end=list.end(); it != end; ++it )
{
ParamIndexes<N>& indexes = *it;
if( indexes.index[pair_info.raw1] == -1 && indexes.index[pair_info.raw2] == -1 )
{
return it;
}
}
return list.end();
}
};
#if IUTEST_HAS_VARIADIC_PAIRWISE
template<typename... Args>
class iuPairwiseGenerator : public iuPairwiseGeneratorBase
{
typedef tuples::tuple< Args... > ParamType;
typedef tuples::tuple< iuParamGenerator<Args>... > GeneratorTuple;
static const int kRAW_COUNT = sizeof...(Args);
typedef ParamIndexes<kRAW_COUNT> _MyParamIndexes;
typedef ::std::vector< _MyParamIndexes > ParamIndexesList;
typedef tuples::tuple< ::std::vector<Args>... > ParamsTuple;
public:
static iuIParamGenerator< ParamType >* Create(GeneratorTuple& generators)
{
ParamIndexesList list;
ParamVecotrs param_vectors(generators);
MakeIndexList(list, param_vectors.count_list);
::std::vector<ParamType> params;
for( typename ParamIndexesList::const_iterator it=list.begin(), end=list.end(); it != end; ++it )
{
const _MyParamIndexes& indexes = *it;
params.push_back(MakeParam<0, Args...>(param_vectors.params_list, indexes));
}
return new iuValuesInParamsGenerator< ParamType >(params);
}
private:
template<int N, typename T1, typename... TArgs>
static tuples::tuple<T1, TArgs...> MakeParam(ParamsTuple& list, const _MyParamIndexes& indexes
, typename detail::disable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value)
{
return ::std::tuple_cat( tuples::tuple<T1>(GetParam(tuples::get<N>(list), indexes, N))
, MakeParam<N+1, TArgs...>(list, indexes) );
}
template<int N, typename T1, typename... TArgs>
static tuples::tuple<T1> MakeParam(ParamsTuple& list, const _MyParamIndexes& indexes
, typename detail::enable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value)
{
return tuples::tuple<T1>( GetParam( tuples::get<N>(list), indexes, N) );
}
struct ParamVecotrs
{
ParamsTuple params_list;
int count_list[kRAW_COUNT];
template<int N>
void MakeParamVecotrs(GeneratorTuple& generators
, typename detail::disable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value)
{
MakeParamVector(tuples::get<N>(params_list), tuples::get<N>(generators));
count_list[N] = static_cast<int>(tuples::get<N>(params_list).size());
MakeParamVecotrs<N+1>(generators);
}
template<int N>
void MakeParamVecotrs(GeneratorTuple& generators
, typename detail::enable_if<N == kRAW_COUNT -1, void>::type*& = detail::enabler::value)
{
MakeParamVector(tuples::get<N>(params_list), tuples::get<N>(generators));
count_list[N] = static_cast<int>(tuples::get<N>(params_list).size());
}
explicit ParamVecotrs(GeneratorTuple& generators)
{
MakeParamVecotrs<0>(generators);
}
};
};
template<typename... Generator>
class iuPairwiseHolder
{
typedef iuPairwiseHolder<Generator...> _Myt;
typedef tuples::tuple<const Generator...> _MyTuple;
public:
explicit iuPairwiseHolder(const Generator&... generators)
: v(generators...) {}
public:
template<typename... Args>
operator iuIParamGenerator< tuples::tuple<Args...> >* () const
{
tuples::tuple< iuParamGenerator<Args>... > generators;
tuples::tuple_cast_copy(generators, v);
return iuPairwiseGenerator<Args...>::Create(generators);
}
public:
#if IUTEST_HAS_CONCAT
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
#endif
private:
_Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION;
private:
_MyTuple v;
};
#else
template<typename T1, typename T2>
class iuPairwiseGenerator2 IUTEST_CXX_FINAL : public iuIParamGenerator< tuples::tuple<T1, T2> >
{
typedef iuParamGenerator<T1> Generator1;
typedef iuParamGenerator<T2> Generator2;
public:
typedef tuples::tuple<T1, T2> ParamType;
public:
iuPairwiseGenerator2(const Generator1& g1, const Generator2& g2)
: m_g1(g1), m_g2(g2)
{}
static iuIParamGenerator< ParamType >* Create(const Generator1& g1, const Generator2& g2)
{
return new iuPairwiseGenerator2<T1, T2>(g1, g2);
}
public:
virtual void Begin() IUTEST_CXX_OVERRIDE
{
m_g1.Begin();
m_g2.Begin();
}
virtual void Next() IUTEST_CXX_OVERRIDE
{
if( m_g2.IsEnd() )
{
return;
}
m_g2.Next();
if( m_g2.IsEnd() )
{
m_g1.Next();
if( !m_g1.IsEnd() )
{
m_g2.Begin();
}
}
}
virtual bool IsEnd() const IUTEST_CXX_OVERRIDE
{
return m_g1.IsEnd() && m_g2.IsEnd();
}
virtual ParamType GetCurrent() const IUTEST_CXX_OVERRIDE
{
return ParamType(this->m_g1.GetCurrent(), this->m_g2.GetCurrent());
}
private:
Generator1 m_g1;
Generator2 m_g2;
};
/*
template<typename T1, typename T2, typename T3>
class iuPairwiseGenerator3 : public iuPairwiseGeneratorBase
{
typedef iuParamGenerator<T1> Generator1;
typedef iuParamGenerator<T2> Generator2;
typedef iuParamGenerator<T3> Generator3;
static const int kRAW_COUNT = 3;
typedef ParamIndexes<kRAW_COUNT> _MyParamIndexes;
typedef ::std::vector< _MyParamIndexes > ParamIndexesList;
public:
typedef tuples::tuple<T1, T2, T3> ParamType;
public:
static iuIParamGenerator< ParamType >* Create(Generator1 g1, Generator2 g2, Generator3 g3)
{
ParamIndexesList list;
::std::vector<T1> params1;
::std::vector<T2> params2;
::std::vector<T3> params3;
MakeParamVector(params1, g1);
MakeParamVector(params2, g2);
MakeParamVector(params3, g3);
int count_list[] = {
static_cast<int>(params1.size())
, static_cast<int>(params2.size())
, static_cast<int>(params3.size())
};
MakeIndexList(list, count_list);
::std::vector<ParamType> params;
for( typename ParamIndexesList::const_iterator it=list.begin(), end=list.end(); it != end; ++it )
{
const _MyParamIndexes& indexes = *it;
params.push_back( ParamType(
GetParam(params1, indexes, 0)
, GetParam(params2, indexes, 1)
, GetParam(params3, indexes, 2)
) );
}
return new iuValuesInParamsGenerator< ParamType >(params);
}
};
*/
/**
* @private
* @{
*/
#define IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_(i, p1, p2) \
p1<IUTEST_PP_CAT(T, i)> IUTEST_PP_CAT(p2, i);
#define IIUT_DECL_PAIRWISE_GENERATOR_MAKEPARAM_VECTOR_(i, p1, p2) \
MakeParamVector( IUTEST_PP_CAT(p1, i), IUTEST_PP_CAT(p2, i) );
#define IIUT_DECL_PAIRWISE_GENERATOR_PARAM_SIZE_(i, param) \
static_cast<int>( IUTEST_PP_CAT(param, i).size() )
#define IIUT_DECL_PAIRWISE_GENERATOR_GETPARAM_(i, param) \
GetParam( IUTEST_PP_CAT(param, i), indexes, i)
#define IIUT_DECL_PAIRWISE_GENERATOR_(n) \
template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \
class IUTEST_PP_CAT(iuPairwiseGenerator, n) IUTEST_CXX_FINAL : public iuPairwiseGeneratorBase { \
IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_, typedef iuParamGenerator, Generator) \
typedef ParamIndexes<n> _MyParamIndexes; \
typedef ::std::vector< _MyParamIndexes > ParamIndexesList; \
public: typedef tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > ParamType; \
static iuIParamGenerator< ParamType >* Create( \
IUTEST_PP_ENUM_BINARY_PARAMS(n, Generator, g) ) { \
ParamIndexesList list; \
IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_, ::std::vector, params) \
IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_GENERATOR_MAKEPARAM_VECTOR_, params, g) \
int count_list[] = { IUTEST_PP_ENUM(n, IIUT_DECL_PAIRWISE_GENERATOR_PARAM_SIZE_, params) }; \
MakeIndexList(list, count_list); \
::std::vector<ParamType> params; \
for( typename ParamIndexesList::const_iterator it=list.begin(), end=list.end(); it != end; ++it ) { \
const _MyParamIndexes& indexes = *it; \
params.push_back( ParamType( IUTEST_PP_ENUM(n, IIUT_DECL_PAIRWISE_GENERATOR_GETPARAM_, params) ) ); \
} \
return new iuValuesInParamsGenerator< ParamType >(params); \
} \
}
/**
* @}
*/
IIUT_DECL_PAIRWISE_GENERATOR_(3);
IIUT_DECL_PAIRWISE_GENERATOR_(4);
IIUT_DECL_PAIRWISE_GENERATOR_(5);
IIUT_DECL_PAIRWISE_GENERATOR_(6);
IIUT_DECL_PAIRWISE_GENERATOR_(7);
IIUT_DECL_PAIRWISE_GENERATOR_(8);
IIUT_DECL_PAIRWISE_GENERATOR_(9);
#undef IIUT_DECL_PAIRWISE_GENERATOR_TEMPLATE_T_
#undef IIUT_DECL_PAIRWISE_GENERATOR_MAKEPARAM_VECTOR_
#undef IIUT_DECL_PAIRWISE_GENERATOR_PARAM_SIZE_
#undef IIUT_DECL_PAIRWISE_GENERATOR_GETPARAM_
#undef IIUT_DECL_PAIRWISE_GENERATOR_
/*
template<typename Generator1, typename Generator2>
class iuPairwiseHolder2
{
typedef iuPairwiseHolder2<Generator1, Generator2> _Myt;
public:
iuPairwiseHolder2(const Generator1& g1, const Generator2& g2)
: m_g1(g1), m_g2(g2) {}
public:
template<typename T1, typename T2>
operator iuIParamGenerator< tuples::tuple<T1, T2> >* () const
{
return iuPairwiseGenerator2<T1, T2>::Create(
static_cast< iuIParamGenerator<T1>* >(m_g1)
, static_cast< iuIParamGenerator<T2>* >(m_g2)
);
}
public:
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
private:
_Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION;
private:
const Generator1 m_g1;
const Generator2 m_g2;
};
*/
#define IIUT_DECL_PAIRWISE_HOLDER_CONSTRUCT_(i, p1, p2) IUTEST_PP_CAT(p1, i)(IUTEST_PP_CAT(p2, i))
#define IIUT_DECL_PAIRWISE_HOLDER_STATICCAST_(i, p1, p2) \
static_cast< iuIParamGenerator< IUTEST_PP_CAT(p1, i) >* >(IUTEST_PP_CAT(p2, i))
#define IIUT_DECL_PAIRWISE_HOLDER_VARIABLE_(i, p1, p2) IUTEST_PP_CAT(p1, i) IUTEST_PP_CAT(p2, i);
#if IUTEST_HAS_CONCAT
# define IIUT_DECL_PAIRWISE_HOLDER_CONCAT_() \
template<typename Other> iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const { \
return iuConcatParamHolder<_Myt, Other>(*this, g); }
#else
# define IIUT_DECL_PAIRWISE_HOLDER_CONCAT_()
#endif
#define IIUT_DECL_PAIRWISE_HOLDER_(n) \
template< IUTEST_PP_ENUM_PARAMS(n, typename Generator) > \
class IUTEST_PP_CAT(iuPairwiseHolder, n) { \
typedef IUTEST_PP_CAT(iuPairwiseHolder, n)< IUTEST_PP_ENUM_PARAMS(n, Generator) > _Myt; \
public: IUTEST_PP_CAT(iuPairwiseHolder, n)( \
IUTEST_PP_ENUM_BINARY_PARAMS(n, const Generator, &g) ) \
: IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_PAIRWISE_HOLDER_CONSTRUCT_, m_g, g) {} \
template< IUTEST_PP_ENUM_PARAMS(n, typename T) > \
operator iuIParamGenerator< tuples::tuple< IUTEST_PP_ENUM_PARAMS(n, T) > >* () const { \
return IUTEST_PP_CAT(iuPairwiseGenerator, n)< IUTEST_PP_ENUM_PARAMS(n, T) >::Create( \
IUTEST_PP_ENUM_BINARY(n, IIUT_DECL_PAIRWISE_HOLDER_STATICCAST_, T, m_g) ); \
} \
IIUT_DECL_PAIRWISE_HOLDER_CONCAT_() \
private: _Myt& operator = (const _Myt&) IUTEST_CXX_DELETED_FUNCTION; \
IUTEST_PP_REPEAT_BINARY(n, IIUT_DECL_PAIRWISE_HOLDER_VARIABLE_, const Generator, m_g) \
}
IIUT_DECL_PAIRWISE_HOLDER_(2);
IIUT_DECL_PAIRWISE_HOLDER_(3);
IIUT_DECL_PAIRWISE_HOLDER_(4);
IIUT_DECL_PAIRWISE_HOLDER_(5);
IIUT_DECL_PAIRWISE_HOLDER_(6);
IIUT_DECL_PAIRWISE_HOLDER_(7);
IIUT_DECL_PAIRWISE_HOLDER_(8);
IIUT_DECL_PAIRWISE_HOLDER_(9);
#undef IIUT_DECL_PAIRWISE_HOLDER_CONSTRUCT_
#undef IIUT_DECL_PAIRWISE_HOLDER_STATICCAST_
#undef IIUT_DECL_PAIRWISE_HOLDER_VARIABLE_
#undef IIUT_DECL_PAIRWISE_HOLDER_CONCAT_
#undef IIUT_DECL_PAIRWISE_HOLDER_
#endif
#endif
#if IUTEST_HAS_VALUESGEN
/**
* @brief パラメータ生成器
* @tparam G = パラメータ生成器
*/
template<typename StdGenerator>
class iuValuesParamsGeneratorHolder
{
typedef iuValuesParamsGeneratorHolder<StdGenerator> _Myt;
public:
iuValuesParamsGeneratorHolder(size_t num, const StdGenerator& g)
: m_num(num), m_g(g)
{}
public:
template<typename T>
operator iuIParamGenerator<T>* () const
{
::std::vector<T> params(m_num);
::std::generate(params.begin(), params.end(), m_g);
return new iuValuesInParamsGenerator<T>( params );
}
public:
#if IUTEST_HAS_CONCAT
template<typename Other>
iuConcatParamHolder<_Myt, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<_Myt, Other>(*this, g);
}
#endif
private:
size_t m_num;
StdGenerator m_g;
};
/**
* @brief 乱数ジェネレータ
*/
template<typename T, typename F>
class iuRandomFilterParamGenerator
{
typedef T type;
public:
iuRandomFilterParamGenerator(const F& fn, unsigned int seed)
: m_fn(fn), m_rnd(seed) {}
type operator ()()
{
type val = m_rnd.genrand();
for( ; !(m_fn)(val); val = m_rnd.genrand() ) {}
return val;
}
private:
F m_fn;
iuTypedRandom<type> m_rnd;
};
#endif
#if IUTEST_HAS_RANDOMVALUES
/**
* @brief 乱数パラメータ生成器
*/
class iuRandomParamsHolder
{
public:
explicit iuRandomParamsHolder(size_t num, unsigned int seed=0) IUTEST_CXX_NOEXCEPT_SPEC
: m_num(num), m_seed(seed) {}
public:
template<typename T>
operator iuIParamGenerator<T>* () const
{
unsigned int seed = m_seed;
if( seed == 0 )
{
seed = GetIndefiniteValue();
}
iuValuesParamsGeneratorHolder< iuTypedRandom<T> > gen( m_num, iuTypedRandom<T>(seed) );
return gen;
}
public:
#if IUTEST_HAS_CONCAT
template<typename Other>
iuConcatParamHolder<iuRandomParamsHolder, Other> operator + (const Other& g) const
{
return iuConcatParamHolder<iuRandomParamsHolder, Other>(*this, g);
}
#endif
private:
size_t m_num;
unsigned int m_seed;
};
#endif
} // end of namespace detail
} // end of namespace iutest
#endif
#endif // INCG_IRIS_IUTEST_GENPARAMS_HPP_7845F59A_825C_426A_B451_573245408998_
| 46,815 | 17,611 |
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/cppalliance/json
//
// Test that header file is self-contained.
#include <boost/json/string.hpp>
#include <boost/json/parse.hpp>
#include <numeric>
#include <sstream>
#include <string>
#include <stdint.h>
#include <unordered_set>
#include "test.hpp"
#include "test_suite.hpp"
BOOST_JSON_NS_BEGIN
class string_test
{
public:
#if BOOST_JSON_ARCH == 64
# define INIT1 { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n' }
# define INIT2 { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' }
#elif BOOST_JSON_ARCH == 32
# define INIT1 { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' }
# define INIT2 { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K' }
#else
# error Unknown architecture
#endif
struct test_vectors
{
// fit in sbo
string_view v1; // "abc...
// dynamic alloc
string_view v2; // "ABC...
std::string const s1;
std::string const s2;
test_vectors()
: s1([&]
{
std::string s;
s.resize(string{}.capacity());
std::iota(s.begin(), s.end(), 'a');
return s;
}())
, s2([&]
{
std::string s;
s.resize(string{}.capacity() + 1);
std::iota(s.begin(), s.end(), 'A');
return s;
}())
{
v1 = s1;
v2 = s2;
BOOST_TEST(std::string(INIT1) == s1);
BOOST_TEST(std::string(INIT2) == s2);
}
};
static
string_view
last_of(
string_view s,
std::size_t n)
{
return s.substr(s.size() - n);
}
void
testConstruction()
{
test_vectors const t;
// string()
{
string s;
}
// string(storage_ptr)
{
auto const sp =
make_counted_resource<unique_resource>();
string s(sp);
BOOST_TEST(s.empty());
BOOST_TEST(*s.storage() == *sp.get());
}
// string(size_type, char, storage_ptr)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
BOOST_TEST(s == std::string(t.v1.size(), '*'));
});
{
string s(t.v2.size(), '*');
BOOST_TEST(s == std::string(t.v2.size(), '*'));
}
}
// string(char const*, storage_ptr)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.s1.c_str(), sp);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.s2.c_str(), sp);
BOOST_TEST(s == t.v2);
});
{
string s(t.s1.c_str());
BOOST_TEST(s == t.v1);
}
{
string s(t.s2.c_str());
BOOST_TEST(s == t.v2);
}
}
// string(char const*, size_type, storage_ptr)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.s1.c_str(), 3, sp);
BOOST_TEST(s == "abc");
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.s2.c_str(), 3, sp);
BOOST_TEST(s == "ABC");
});
{
string s(t.s1.c_str(), 3);
BOOST_TEST(s == "abc");
}
{
string s(t.s2.c_str(), 3);
BOOST_TEST(s == "ABC");
}
}
// string(InputIt, InputIt, storage_ptr)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.begin(), t.v1.end(), sp);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.begin(), t.v2.end(), sp);
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(
make_input_iterator(t.v1.begin()),
make_input_iterator(t.v1.end()), sp);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(
make_input_iterator(t.v2.begin()),
make_input_iterator(t.v2.end()), sp);
BOOST_TEST(s == t.v2);
});
{
string s(t.v1.begin(), t.v1.end());
BOOST_TEST(s == t.v1);
}
{
string s(t.v2.begin(), t.v2.end());
BOOST_TEST(s == t.v2);
}
{
string s(
make_input_iterator(t.v1.begin()),
make_input_iterator(t.v1.end()));
BOOST_TEST(s == t.v1);
}
{
string s(
make_input_iterator(t.v2.begin()),
make_input_iterator(t.v2.end()));
BOOST_TEST(s == t.v2);
}
}
// string(string)
{
{
string const s0(t.v1);
string s(s0);
BOOST_TEST(s == t.v1);
}
{
string const s0(t.v2);
string s(s0);
BOOST_TEST(s == t.v2);
}
}
// string(string, storage_ptr)
{
fail_loop([&](storage_ptr const& sp)
{
string const s0(t.v1);
string s(s0, sp);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string const s0(t.v2);
string s(s0, sp);
BOOST_TEST(s == t.v2);
});
}
// string(pilfered<string>)
{
{
string s1(t.v1);
string s2(pilfer(s1));
BOOST_TEST(s2 == t.v1);
BOOST_TEST(s1.empty());
BOOST_TEST(
s1.storage() == storage_ptr());
}
{
string s1(t.v2);
string s2(pilfer(s1));
BOOST_TEST(s2 == t.v2);
BOOST_TEST(s1.empty());
BOOST_TEST(
s1.storage() == storage_ptr());
}
}
// string(string&&)
{
{
string s1(t.v1);
string s2(std::move(s1));
BOOST_TEST(s2 == t.v1);
BOOST_TEST(s1.empty());
BOOST_TEST(
*s1.storage() ==
*s2.storage());
}
{
string s1(t.v2);
string s2(std::move(s1));
BOOST_TEST(s2 == t.v2);
BOOST_TEST(s1.empty());
BOOST_TEST(
*s1.storage() ==
*s2.storage());
}
}
// string(string&&, storage_ptr)
{
// same storage
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v1, sp);
string s2(std::move(s1), sp);
BOOST_TEST(s2 == t.v1);
BOOST_TEST(s1.empty());
BOOST_TEST(
*s1.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v2, sp);
string s2(std::move(s1));
BOOST_TEST(s2 == t.v2);
BOOST_TEST(s1.empty());
BOOST_TEST(
*s1.storage() ==
*s2.storage());
});
// different storage
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v1);
string s2(std::move(s1), sp);
BOOST_TEST(s2 == t.v1);
BOOST_TEST(s1 == t.v1);
BOOST_TEST(
*s1.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v2);
string s2(std::move(s1), sp);
BOOST_TEST(s2 == t.v2);
BOOST_TEST(s1 == t.v2);
BOOST_TEST(
*s1.storage() !=
*s2.storage());
});
}
// string(string_view, storage_ptr)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
BOOST_TEST(s == t.v2);
});
{
string s(t.v1);
BOOST_TEST(s == t.v1);
}
{
string s(t.v2);
BOOST_TEST(s == t.v2);
}
}
}
void
testAssignment()
{
test_vectors const t;
// operator=(string)
{
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string const s2(t.v1);
s = s2;
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string const s2(t.v1);
s = s2;
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string const s2(t.v2);
s = s2;
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string const s2(t.v2);
s = s2;
BOOST_TEST(s == t.v2);
});
}
// operator=(string&&)
{
// same storage
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v1, sp);
s = std::move(s2);
BOOST_TEST(s == t.v1);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v1, sp);
s = std::move(s2);
BOOST_TEST(s == t.v1);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v2, sp);
s = std::move(s2);
BOOST_TEST(s == t.v2);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v2, sp);
s = std::move(s2);
BOOST_TEST(s == t.v2);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
// different storage
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v1);
s = std::move(s2);
BOOST_TEST(s == t.v1);
BOOST_TEST(s2 == t.v1);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v1);
s = std::move(s2);
BOOST_TEST(s == t.v1);
BOOST_TEST(s2 == t.v1);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v2);
s = std::move(s2);
BOOST_TEST(s == t.v2);
BOOST_TEST(s2 == t.v2);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v2);
s = std::move(s2);
BOOST_TEST(s == t.v2);
BOOST_TEST(s2 == t.v2);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
}
// operator=(char const*)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s = t.s1.c_str();
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s = t.s1.c_str();
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s = t.s2.c_str();
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s = t.s2.c_str();
BOOST_TEST(s == t.v2);
});
}
// operator=(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s = t.v1;
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s = t.v1;
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s = t.v2;
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s = t.v2;
BOOST_TEST(s == t.v2);
});
}
}
void
testAssign()
{
test_vectors const t;
// assign(size_type, char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), 'x', sp);
s.assign(t.v1.size(), '*');
BOOST_TEST(
s == std::string(t.v1.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), 'x', sp);
s.assign(t.v1.size(), '*');
BOOST_TEST(
s == std::string(t.v1.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), 'x', sp);
s.assign(t.v2.size(), '*');
BOOST_TEST(
s == std::string(t.v2.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), 'x', sp);
s.assign(t.v2.size(), '*');
BOOST_TEST(
s == std::string(t.v2.size(), '*'));
});
}
// assign(string)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), 'x', sp);
s.assign(string(t.v1.size(), '*'));
BOOST_TEST(
s == std::string(t.v1.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), 'x', sp);
s.assign(string(t.v1.size(), '*'));
BOOST_TEST(
s == std::string(t.v1.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), 'x', sp);
s.assign(string(t.v2.size(), '*'));
BOOST_TEST(
s == std::string(t.v2.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), 'x', sp);
s.assign(string(t.v2.size(), '*'));
BOOST_TEST(
s == std::string(t.v2.size(), '*'));
});
// self-assign
{
string s(t.v1);
s = static_cast<string const&>(s);
BOOST_TEST(s == t.v1);
}
}
// assign(string&&)
{
// same storage
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v1, sp);
s.assign(std::move(s2));
BOOST_TEST(s == t.v1);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v1, sp);
s.assign(std::move(s2));
BOOST_TEST(s == t.v1);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v2, sp);
s.assign(std::move(s2));
BOOST_TEST(s == t.v2);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v2, sp);
s.assign(std::move(s2));
BOOST_TEST(s == t.v2);
BOOST_TEST(s2.empty());
BOOST_TEST(
*s.storage() ==
*s2.storage());
});
// different storage
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v1);
s.assign(std::move(s2));
BOOST_TEST(s == t.v1);
BOOST_TEST(s2 == t.v1);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v1);
s.assign(std::move(s2));
BOOST_TEST(s == t.v1);
BOOST_TEST(s2 == t.v1);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v1.size(), '*');
string s(c, sp);
string s2(t.v2);
s.assign(std::move(s2));
BOOST_TEST(s == t.v2);
BOOST_TEST(s2 == t.v2);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
fail_loop([&](storage_ptr const& sp)
{
std::string c(t.v2.size(), '*');
string s(c, sp);
string s2(t.v2);
s.assign(std::move(s2));
BOOST_TEST(s == t.v2);
BOOST_TEST(s2 == t.v2);
BOOST_TEST(
*s.storage() !=
*s2.storage());
});
}
// assign(char const*, size_type)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.s1.c_str(), 3);
BOOST_TEST(s == "abc");
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.s1.c_str(), 3);
BOOST_TEST(s == "abc");
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.s2.c_str(), 3);
BOOST_TEST(s == "ABC");
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.s2.c_str(), 3);
BOOST_TEST(s == "ABC");
});
};
// assign(char const* s)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.s1.c_str());
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.s1.c_str());
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.s2.c_str());
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.s2.c_str());
BOOST_TEST(s == t.v2);
});
}
// assign(InputIt, InputIt)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.s1.begin(), t.s1.end());
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.s1.begin(), t.s1.end());
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(
make_input_iterator(t.s1.begin()),
make_input_iterator(t.s1.end()));
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(
make_input_iterator(t.s1.begin()),
make_input_iterator(t.s1.end()));
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.s2.begin(), t.s2.end());
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.s2.begin(), t.s2.end());
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(
make_input_iterator(t.s2.begin()),
make_input_iterator(t.s2.end()));
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(
make_input_iterator(t.s2.begin()),
make_input_iterator(t.s2.end()));
BOOST_TEST(s == t.v2);
});
// empty range
{
string s(t.v1);
s.assign(t.s1.begin(), t.s1.begin());
BOOST_TEST(s.empty());
}
// empty range
{
string s(t.v1);
s.assign(
make_input_iterator(t.s1.begin()),
make_input_iterator(t.s1.begin()));
BOOST_TEST(s.empty());
}
}
// assign(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.v1);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.v1);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1.size(), '*', sp);
s.assign(t.v2);
BOOST_TEST(s == t.v2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2.size(), '*', sp);
s.assign(t.v2);
BOOST_TEST(s == t.v2);
});
}
}
void
testElementAccess()
{
test_vectors const t;
string s1(t.v1);
string s2(t.v2);
auto const& cs1(s1);
auto const& cs2(s2);
// at(size_type)
{
BOOST_TEST(s1.at(1) == 'b');
s1.at(1) = '*';
BOOST_TEST(s1.at(1) == '*');
s1.at(1) = 'b';
BOOST_TEST(s1.at(1) == 'b');
BOOST_TEST(s2.at(1) == 'B');
s2.at(1) = '*';
BOOST_TEST(s2.at(1) == '*');
s2.at(1) = 'B';
BOOST_TEST(s2.at(1) == 'B');
BOOST_TEST_THROWS(s1.at(s2.size()),
std::out_of_range);
}
// at(size_type) const
{
BOOST_TEST(cs1.at(1) == 'b');
BOOST_TEST(cs2.at(1) == 'B');
BOOST_TEST_THROWS(cs1.at(cs2.size()),
std::out_of_range);
}
// operator[&](size_type)
{
BOOST_TEST(s1[1] == 'b');
s1[1] = '*';
BOOST_TEST(s1[1] == '*');
s1[1] = 'b';
BOOST_TEST(s1[1] == 'b');
BOOST_TEST(s2[1] == 'B');
s2[1] = '*';
BOOST_TEST(s2[1] == '*');
s2[1] = 'B';
BOOST_TEST(s2[1] == 'B');
}
// operator[&](size_type) const
{
BOOST_TEST(cs1[1] == 'b');
BOOST_TEST(cs2[1] == 'B');
}
// front()
{
BOOST_TEST(s1.front() == 'a');
s1.front() = '*';
BOOST_TEST(s1.front() == '*');
s1.front() = 'a';
BOOST_TEST(s1.front() == 'a');
BOOST_TEST(s2.front() == 'A');
s2.front() = '*';
BOOST_TEST(s2.front() == '*');
s2.front() = 'A';
BOOST_TEST(s2.front() == 'A');
}
// front() const
{
BOOST_TEST(cs1.front() == 'a');
BOOST_TEST(cs2.front() == 'A');
}
// back()
{
auto const ch1 = s1.at(s1.size()-1);
auto const ch2 = s2.at(s2.size()-1);
BOOST_TEST(s1.back() == ch1);
s1.back() = '*';
BOOST_TEST(s1.back() == '*');
s1.back() = ch1;
BOOST_TEST(s1.back() == ch1);
BOOST_TEST(s2.back() == ch2);
s2.back() = '*';
BOOST_TEST(s2.back() == '*');
s2.back() = ch2;
BOOST_TEST(s2.back() == ch2);
}
// back() const
{
auto const ch1 = s1.at(s1.size()-1);
auto const ch2 = s2.at(s2.size()-1);
BOOST_TEST(cs1.back() == ch1);
BOOST_TEST(cs2.back() == ch2);
}
// data()
{
BOOST_TEST(
string_view(s1.data()) == t.v1);
BOOST_TEST(
string_view(s2.data()) == t.v2);
}
// data() const
{
BOOST_TEST(
string_view(cs1.data()) == t.v1);
BOOST_TEST(
string_view(cs2.data()) == t.v2);
}
// c_str()
{
BOOST_TEST(
string_view(cs1.c_str()) == t.v1);
BOOST_TEST(
string_view(cs2.c_str()) == t.v2);
}
// operator string_view()
{
BOOST_TEST(
string_view(cs1) == t.v1);
BOOST_TEST(
string_view(cs2) == t.v2);
}
}
void
testIterators()
{
string s = "abc";
auto const& ac(s);
{
auto it = s.begin();
BOOST_TEST(*it == 'a'); ++it;
BOOST_TEST(*it == 'b'); it++;
BOOST_TEST(*it == 'c'); ++it;
BOOST_TEST(it == s.end());
}
{
auto it = s.cbegin();
BOOST_TEST(*it == 'a'); ++it;
BOOST_TEST(*it == 'b'); it++;
BOOST_TEST(*it == 'c'); ++it;
BOOST_TEST(it == s.cend());
}
{
auto it = ac.begin();
BOOST_TEST(*it == 'a'); ++it;
BOOST_TEST(*it == 'b'); it++;
BOOST_TEST(*it == 'c'); ++it;
BOOST_TEST(it == ac.end());
}
{
auto it = s.end();
--it; BOOST_TEST(*it == 'c');
it--; BOOST_TEST(*it == 'b');
--it; BOOST_TEST(*it == 'a');
BOOST_TEST(it == s.begin());
}
{
auto it = s.cend();
--it; BOOST_TEST(*it == 'c');
it--; BOOST_TEST(*it == 'b');
--it; BOOST_TEST(*it == 'a');
BOOST_TEST(it == s.cbegin());
}
{
auto it = ac.end();
--it; BOOST_TEST(*it == 'c');
it--; BOOST_TEST(*it == 'b');
--it; BOOST_TEST(*it == 'a');
BOOST_TEST(it == ac.begin());
}
{
auto it = s.rbegin();
BOOST_TEST(*it == 'c'); ++it;
BOOST_TEST(*it == 'b'); it++;
BOOST_TEST(*it == 'a'); ++it;
BOOST_TEST(it == s.rend());
}
{
auto it = s.crbegin();
BOOST_TEST(*it == 'c'); ++it;
BOOST_TEST(*it == 'b'); it++;
BOOST_TEST(*it == 'a'); ++it;
BOOST_TEST(it == s.crend());
}
{
auto it = ac.rbegin();
BOOST_TEST(*it == 'c'); ++it;
BOOST_TEST(*it == 'b'); it++;
BOOST_TEST(*it == 'a'); ++it;
BOOST_TEST(it == ac.rend());
}
{
auto it = s.rend();
--it; BOOST_TEST(*it == 'a');
it--; BOOST_TEST(*it == 'b');
--it; BOOST_TEST(*it == 'c');
BOOST_TEST(it == s.rbegin());
}
{
auto it = s.crend();
--it; BOOST_TEST(*it == 'a');
it--; BOOST_TEST(*it == 'b');
--it; BOOST_TEST(*it == 'c');
BOOST_TEST(it == s.crbegin());
}
{
auto it = ac.rend();
--it; BOOST_TEST(*it == 'a');
it--; BOOST_TEST(*it == 'b');
--it; BOOST_TEST(*it == 'c');
BOOST_TEST(it == ac.rbegin());
}
{
string s2;
string const& cs2(s2);
BOOST_TEST(std::distance(
s2.begin(), s2.end()) == 0);
BOOST_TEST(std::distance(
cs2.begin(), cs2.end()) == 0);
BOOST_TEST(std::distance(
s2.rbegin(), s2.rend()) == 0);
BOOST_TEST(std::distance(
cs2.rbegin(), cs2.rend()) == 0);
}
}
void
testCapacity()
{
test_vectors const t;
// empty()
{
{
string s;
BOOST_TEST(s.empty());
}
{
string s = "abc";
BOOST_TEST(! s.empty());
}
}
// size()
// max_size()
{
string s = "abc";
BOOST_TEST(s.size() == 3);
BOOST_TEST(s.max_size() < string::npos);
}
// reserve(size_type)
{
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.append(t.v1);
s.append(t.v2);
s.reserve(0);
BOOST_TEST(s.size() ==
t.v1.size() + t.v2.size());
s.reserve(t.v1.size() + t.v2.size());
BOOST_TEST(s.size() ==
t.v1.size() + t.v2.size());
s.reserve(s.size() * 2);
BOOST_TEST(s.capacity() >
t.v1.size() + t.v2.size());
s.resize(t.v1.size());
s.reserve(t.v1.size());
BOOST_TEST(s == t.v1);
});
}
// capacity()
{
// implied
}
// shrink_to_fit()
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
string::size_type cap;
cap = s.capacity();
s.shrink_to_fit();
BOOST_TEST(s.capacity() == cap);
s.reserve(s.capacity() + 1);
s.shrink_to_fit();
BOOST_TEST(s.capacity() == cap);
s.resize(cap * 3, '*');
cap = s.capacity();
s.resize(cap - 1);
s.shrink_to_fit();
BOOST_TEST(s.capacity() == cap);
s.resize(cap / 2);
BOOST_TEST(s.capacity() == cap);
s.shrink_to_fit();
BOOST_TEST(s.capacity() < cap);
});
}
void
testClear()
{
test_vectors const t;
// clear()
{
{
string s(t.v1);
s.clear();
BOOST_TEST(s.empty());
BOOST_TEST(s.size() == 0);
BOOST_TEST(s.capacity() > 0);
}
{
string s(t.v2);
s.clear();
BOOST_TEST(s.empty());
BOOST_TEST(s.size() == 0);
BOOST_TEST(s.capacity() > 0);
}
}
}
void
testInsert()
{
test_vectors const t;
// insert(size_type, size_type, char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(1, 3, '*');
BOOST_TEST(s == std::string(
t.v1).insert(1, 3, '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(1, 3, '*');
BOOST_TEST(s == std::string(
t.v2).insert(1, 3, '*'));
});
// pos out of range
{
string s(t.v1);
BOOST_TEST_THROWS(
(s.insert(s.size() + 2, 1, '*')),
std::out_of_range);
}
// size > max_size
{
string s(t.v1);
BOOST_TEST_THROWS(
(s.insert(1, s.max_size(), 'a')),
std::length_error);
}
}
// insert(size_type, char const*)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(1, "***");
BOOST_TEST(s == std::string(
t.v1).insert(1, "***"));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(1, "***");
BOOST_TEST(s == std::string(
t.v2).insert(1, "***"));
});
// pos out of range
{
string s(t.v1);
BOOST_TEST_THROWS(
(s.insert(s.size() + 2, "*")),
std::out_of_range);
}
}
// insert(size_type, char const*, size_type)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(1, "*****");
BOOST_TEST(s == std::string(
t.v1).insert(1, "*****"));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(1, "*****");
BOOST_TEST(s == std::string(
t.v2).insert(1, "*****"));
});
}
// insert(size_type, string const&)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(1, string(t.v2));
BOOST_TEST(s == std::string(
t.v1).insert(1, t.s2));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(1, string(t.v1));
BOOST_TEST(s == std::string(
t.v2).insert(1, t.s1));
});
}
//// KRYSTIAN These tests are superseded by the new string_view overloads
//// insert(size_type, string const&, size_type, size_type)
//{
// fail_loop([&](storage_ptr const& sp)
// {
// string s(t.v1, sp);
// s.insert(1, string(t.v2), 1, 3);
// BOOST_TEST(s == std::string(
// t.v1).insert(1, t.s2, 1, 3));
// });
// fail_loop([&](storage_ptr const& sp)
// {
// string s(t.v2, sp);
// s.insert(1, string(t.v1), 1, 3);
// BOOST_TEST(s == std::string(
// t.v2).insert(1, t.s1, 1, 3));
// });
// fail_loop([&](storage_ptr const& sp)
// {
// string s(t.v1, sp);
// s.insert(1, string(t.v2), 1);
// BOOST_TEST(s == std::string(
// t.v1).insert(1, t.s2, 1, std::string::npos));
// });
// fail_loop([&](storage_ptr const& sp)
// {
// string s(t.v2, sp);
// s.insert(1, string(t.v1), 1);
// BOOST_TEST(s == std::string(
// t.v2).insert(1, t.s1, 1, std::string::npos));
// });
//}
// insert(size_type, char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
BOOST_TEST(
s.insert(2, '*')[2] == '*');
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
BOOST_TEST(
s.insert(2, '*')[2] == '*');
});
}
// insert(const_iterator, size_type, char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
BOOST_TEST(string_view(
&(s.insert(2, 3, '*')[2]), 5) ==
"***cd");
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
BOOST_TEST(string_view(
&(s.insert(2, 3, '*')[2]), 5) ==
"***CD");
});
}
// insert(const_iterator, InputIt, InputIt)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(2, t.s2.begin(), t.s2.end());
std::string cs(t.s1);
cs.insert(2, &t.s2[0], t.s2.size());
BOOST_TEST(s == cs);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(2, t.s1.begin(), t.s1.end());
std::string cs(t.s2);
cs.insert(2, &t.s1[0], t.s1.size());
BOOST_TEST(s == cs);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(2,
make_input_iterator(t.s2.begin()),
make_input_iterator(t.s2.end()));
std::string cs(t.s1);
cs.insert(2, &t.s2[0], t.s2.size());
BOOST_TEST(s == cs);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(2,
make_input_iterator(t.s1.begin()),
make_input_iterator(t.s1.end()));
std::string cs(t.s2);
cs.insert(2, &t.s1[0], t.s1.size());
BOOST_TEST(s == cs);
});
}
// insert(const_iterator, string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(2, string_view(t.v2));
std::string cs(t.v1);
cs.insert(2, t.s2);
BOOST_TEST(s == cs);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(2, string_view(t.v1));
std::string cs(t.v2);
cs.insert(2, t.s1);
BOOST_TEST(s == cs);
});
}
// insert(const_iterator, string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(2, string_view(t.v2).substr(2, 3));
std::string cs(t.v1);
cs.insert(2, t.s2, 2, 3);
BOOST_TEST(s == cs);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(2, string_view(t.v1).substr(2, 3));
std::string cs(t.v2);
cs.insert(2, t.s1, 2, 3);
BOOST_TEST(s == cs);
});
}
// insert(size_type, char const*)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.insert(1, "***");
BOOST_TEST(s == std::string(
t.v1).insert(1, "***"));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.insert(1, "***");
BOOST_TEST(s == std::string(
t.v2).insert(1, "***"));
});
// pos out of range
{
string s(t.v1);
BOOST_TEST_THROWS(
(s.insert(s.size() + 2, "*")),
std::out_of_range);
}
}
// insert tests for when source is within destination
{
// start before splice point
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.reserve(s.size() + 10);
s.insert(4, s.subview(0, 3));
std::string cs(t.v1);
cs.insert(4, cs.substr(0, 3));
BOOST_TEST(s == cs);
});
// start after splice point
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.reserve(s.size() + 10);
s.insert(0, s.subview(3, 3));
std::string cs(t.v1);
cs.insert(0, cs.substr(3, 3));
BOOST_TEST(s == cs);
});
// insert pos bisects the inserted string
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.reserve(s.size() + 10);
s.insert(2, s.subview(0, 5));
std::string cs(t.v1);
cs.insert(2, cs.substr(0, 5));
BOOST_TEST(s == cs);
});
}
// insert reallocation test
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
std::string cs(t.v2);
const auto view = t.v2.substr(0, 4);
s.append(s);
cs.append(cs);
s.insert(2, view);
cs.insert(2, view.data(), view.size());
BOOST_TEST(s == cs);
});
}
}
void
testErase()
{
test_vectors const t;
// erase(size_type, size_type)
{
{
string s(t.v1);
s.erase(1, 3);
BOOST_TEST(s ==
std::string(t.v1).erase(1, 3));
}
{
string s(t.v2);
s.erase(1, 3);
BOOST_TEST(s ==
std::string(t.v2).erase(1, 3));
}
{
string s(t.v1);
s.erase(3);
BOOST_TEST(s ==
std::string(t.v1).erase(3));
}
{
string s(t.v2);
s.erase(3);
BOOST_TEST(s ==
std::string(t.v2).erase(3));
}
{
string s(t.v1);
s.erase();
BOOST_TEST(s ==
std::string(t.v1).erase());
}
{
string s(t.v2);
s.erase();
BOOST_TEST(s ==
std::string(t.v2).erase());
}
{
string s(t.v1);
BOOST_TEST_THROWS(
(s.erase(t.v1.size() + 1, 1)),
std::out_of_range);
}
}
// iterator erase(const_iterator)
{
{
string s(t.v1);
std::string s2(t.v1);
s.erase(s.begin() + 3);
s2.erase(s2.begin() + 3);
BOOST_TEST(s == s2);
}
{
string s(t.v2);
std::string s2(t.v2);
s.erase(s.begin() + 3);
s2.erase(s2.begin() + 3);
BOOST_TEST(s == s2);
}
}
// iterator erase(const_iterator, const_iterator)
{
string s(t.v1);
std::string s2(t.v1);
s.erase(s.begin() + 1, s.begin() + 3);
s2.erase(s2.begin() + 1, s2.begin() + 3);
BOOST_TEST(s == s2);
}
}
void
testPushPop()
{
test_vectors const t;
// push_back(char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
for(auto ch : t.v1)
s.push_back(ch);
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
for(auto ch : t.v2)
s.push_back(ch);
BOOST_TEST(s == t.v2);
});
}
// pop_back(char)
{
{
string s(t.v1);
while(! s.empty())
s.pop_back();
BOOST_TEST(s.empty());
BOOST_TEST(s.capacity() > 0);
}
{
string s(t.v2);
while(! s.empty())
s.pop_back();
BOOST_TEST(s.empty());
BOOST_TEST(s.capacity() > 0);
}
}
}
void
testAppend()
{
test_vectors const t;
// append(size_type, char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(t.v2.size(), '*');
BOOST_TEST(s == t.s1 +
std::string(t.v2.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(t.v1.size(), '*');
BOOST_TEST(s == t.s2 +
std::string(t.v1.size(), '*'));
});
}
// append(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(string(t.v2));
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(string(t.v1));
BOOST_TEST(s == t.s2 + t.s1);
});
}
// append(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(string(t.v2).subview(3));
BOOST_TEST(s == t.s1 + t.s2.substr(3));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(string(t.v1).subview(3));
BOOST_TEST(s == t.s2 + t.s1.substr(3));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(string(t.v2).subview(2, 3));
BOOST_TEST(s == t.s1 + t.s2.substr(2, 3));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(string(t.v1).subview(2, 3));
BOOST_TEST(s == t.s2 + t.s1.substr(2, 3));
});
}
// append(char const*)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(t.s2.c_str());
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(t.s1.c_str());
BOOST_TEST(s == t.s2 + t.s1);
});
}
// append(InputIt, InputIt)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(t.s2.begin(), t.s2.end());
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(t.s1.begin(), t.s1.end());
BOOST_TEST(s == t.s2 + t.s1);
});
// Fails on Visual Studio 2017 C++2a Strict
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(
make_input_iterator(t.s2.begin()),
make_input_iterator(t.s2.end()));
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(
make_input_iterator(t.s1.begin()),
make_input_iterator(t.s1.end()));
BOOST_TEST(s == t.s2 + t.s1);
});
}
// append(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(t.v2);
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(t.v1);
BOOST_TEST(s == t.s2 + t.s1);
});
}
// append(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(t.v2.substr(2));
BOOST_TEST(s == t.s1 + t.s2.substr(2));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(t.v1.substr(2));
BOOST_TEST(s == t.s2 + t.s1.substr(2));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s.append(t.v2.substr(2, 3));
BOOST_TEST(s == t.s1 + t.s2.substr(2, 3));
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s.append(t.v1.substr(2, 3));
BOOST_TEST(s == t.s2 + t.s1.substr(2, 3));
});
}
}
void
testPlusEquals()
{
test_vectors const t;
// operator+=(string)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s += string(t.v2);
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s += string(t.v1);
BOOST_TEST(s == t.s2 + t.s1);
});
}
// operator+=(char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
for(auto ch : t.v1)
s += ch;
BOOST_TEST(s == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
for(auto ch : t.v2)
s += ch;
BOOST_TEST(s == t.v2);
});
}
// operator+=(char const*)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s += t.s2.c_str();
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s += t.s1.c_str();
BOOST_TEST(s == t.s2 + t.s1);
});
}
// operator+=(string_view)
{
fail_loop([&](storage_ptr const& sp)
{
string s(t.v1, sp);
s += t.v2;
BOOST_TEST(s == t.s1 + t.s2);
});
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
s += t.v1;
BOOST_TEST(s == t.s2 + t.s1);
});
}
}
void
testCompare()
{
test_vectors const t;
string const v1 = t.v1;
// compare(string)
BOOST_TEST(v1.compare(string("aaaaaaa")) > 0);
BOOST_TEST(v1.compare(string(t.v1)) == 0);
BOOST_TEST(v1.compare(string("bbbbbbb")) < 0);
// compare(char const*)
BOOST_TEST(v1.compare("aaaaaaa") > 0);
BOOST_TEST(v1.compare(t.s1.c_str()) == 0);
BOOST_TEST(v1.compare("bbbbbbb") < 0);
// compare(string_view s)
BOOST_TEST(v1.compare(string_view("aaaaaaa")) > 0);
BOOST_TEST(v1.compare(t.v1) == 0);
BOOST_TEST(v1.compare(string_view("bbbbbbb")) < 0);
}
void
testStartEndsWith()
{
test_vectors const t;
string const v1 = t.v1;
string const v2 = t.v2;
// starts_with(string_view)
{
BOOST_TEST(v1.starts_with(string_view("abc")));
BOOST_TEST(v2.starts_with(string_view("ABC")));
BOOST_TEST(! v1.starts_with(string_view("xyz")));
BOOST_TEST(! v2.starts_with(string_view("XYZ")));
}
// starts_with(char)
{
BOOST_TEST(v1.starts_with('a'));
BOOST_TEST(v2.starts_with('A'));
BOOST_TEST(! v1.starts_with('x'));
BOOST_TEST(! v2.starts_with('X'));
}
// starts_with(char const*)
{
BOOST_TEST(v1.starts_with("abc"));
BOOST_TEST(v2.starts_with("ABC"));
BOOST_TEST(! v1.starts_with("xyz"));
BOOST_TEST(! v2.starts_with("XYZ"));
}
// ends_with(string_view)
{
BOOST_TEST(v1.ends_with(last_of(t.s1,3)));
BOOST_TEST(v2.ends_with(last_of(t.s2,3)));
BOOST_TEST(! v1.ends_with(string_view("abc")));
BOOST_TEST(! v2.ends_with(string_view("ABC")));
}
// ends_with(char)
{
BOOST_TEST(v1.ends_with(last_of(t.s1, 1)[0]));
BOOST_TEST(v2.ends_with(last_of(t.s2, 1)[0]));
BOOST_TEST(! v1.ends_with('a'));
BOOST_TEST(! v2.ends_with('A'));
}
// ends_with(char const*)
{
BOOST_TEST(v1.ends_with(last_of(t.s1, 3).data()));
BOOST_TEST(v2.ends_with(last_of(t.s2, 3).data()));
BOOST_TEST(! v1.ends_with("abc"));
BOOST_TEST(! v2.ends_with("ABC"));
}
}
void
testReplace()
{
test_vectors const t;
// replace(std::size_t, std::size_t, string_view)
{
// pos out of range
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
BOOST_TEST_THROWS(s.replace(s.size() + 1, 1, t.v2),
std::out_of_range);
});
// outside, shrink
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(0, 4, t.v2.substr(4, 2)) ==
s1.replace(0, 4, t.v2.data() + 4, 2));
});
// outside, grow
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(0, 1, t.v2.substr(0)) ==
s1.replace(0, 1, t.v2.data(), t.v2.size()));
});
// outside, grow, reallocate
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
s1.append(s1);
s2.append(s2);
BOOST_TEST(s2.replace(0, 1, t.v2.substr(0)) ==
s1.replace(0, 1, t.v2.data(), t.v2.size()));
});
// outside, same
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(0, 2, t.v2.substr(0, 2)) ==
s1.replace(0, 2, t.v2.data(), 2));
});
// replace tests for full coverage
// inside, no effect
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(0, 4, s2.subview(0, 4)) ==
s1.replace(0, 4, s1.data() + 0, 4));
});
// inside, shrink, split
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(1, 4, s2.subview(4, 2)) ==
s1.replace(1, 4, s1.data() + 4, 2));
});
// inside, grow no reallocate, split
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(1, 1, s2.subview(0)) ==
s1.replace(1, 1, s1.data(), s1.size()));
});
// inside, reallocate, split
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
s1.append(s1);
s2.append(s2);
BOOST_TEST(s2.replace(1, 1, s2.subview(0)) ==
s1.replace(1, 1, s1.data(), s1.size()));
});
// inside, same, split
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(1, 2, s2.subview(0, 2)) ==
s1.replace(1, 2, s1.data(), 2));
});
}
// replace(const_iterator, const_iterator, string_view)
{
// outside, shrink
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(
s2.begin(),
s2.begin() + 4,
t.v2.substr(4, 2)) ==
s1.replace(0,
4, t.v2.data() + 4,
2));
});
// outside, grow
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(
s2.begin(),
s2.begin() + 1,
t.v2.substr(0)) ==
s1.replace(0,
1, t.v2.data(),
t.v2.size()));
});
// outside, same
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(
s2.begin(),
s2.begin() + 2,
t.v2.substr(0, 2)) ==
s1.replace(
0, 2,
t.v2.data(),
2));
});
// inside, shrink
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(
s2.begin() + 1,
s2.begin() + 5,
s2.subview(4, 2)) ==
s1.replace(
1, 4,
s1.data() + 4,
2));
});
// inside, grow
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(
s2.begin() + 1,
s2.begin() + 2,
s2.subview(0)) ==
s1.replace(
1, 1,
s1.data(),
s1.size()));
});
// inside, same
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(
s2.begin() + 1,
s2.begin() + 3,
s2.subview(0, 2)) ==
s1.replace(
1, 2,
s1.data(),
2));
});
}
// replace(std::size_t, std::size_t, std::size_t, char)
{
// grow, no realloc
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(0, 4, 10, 'a') ==
s1.replace(0, 4, 10, 'a'));
});
// grow, realloc
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
const auto grow = (std::max)(s1.capacity(), s2.capacity());
BOOST_TEST(s2.replace(0, 4, grow, 'a') ==
s1.replace(0, 4, grow, 'a'));
});
// no change in size
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(s2.replace(0, 1, 1, 'a') ==
s1.replace(0, 1, 1, 'a'));
});
// pos out of range
fail_loop([&](storage_ptr const& sp)
{
string s(t.v2, sp);
BOOST_TEST_THROWS(s.replace(s.size() + 1, 1, 1, 'a'),
std::out_of_range);
});
}
// replace(const_iterator, const_iterator, std::size_t, char)
{
fail_loop([&](storage_ptr const& sp)
{
std::string s1(t.v2.data(), t.v2.size());
string s2(t.v2, sp);
BOOST_TEST(
s2.replace(s2.begin(), s2.begin() + 4, 10, 'a') ==
s1.replace(0, 4, 10, 'a'));
});
}
}
void
testSubStr()
{
test_vectors const t;
string const s1 = t.v1;
string const s2 = t.v2;
// subview(size_type, size_type)
BOOST_TEST(s1.subview() == t.v1);
BOOST_TEST(s1.subview(1) == t.v1.substr(1));
BOOST_TEST(s1.subview(1, 3) == t.v1.substr(1, 3));
BOOST_TEST(s2.subview() == t.v2);
BOOST_TEST(s2.subview(1) == t.v2.substr(1));
BOOST_TEST(s2.subview(1, 3) == t.v2.substr(1, 3));
}
void
testCopy()
{
test_vectors const t;
// copy(char*, count, pos)
{
{
string s(t.v1);
std::string d;
d.resize(s.size());
s.copy(&d[0], d.size(), 0);
BOOST_TEST(d == t.v1);
}
{
string s(t.v1);
std::string d;
d.resize(s.size());
s.copy(&d[0], d.size());
BOOST_TEST(d == t.v1);
}
}
}
void
testResize()
{
test_vectors const t;
// resize(size_type)
{
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.resize(t.v1.size());
BOOST_TEST(s.size() == t.v1.size());
BOOST_TEST(s == string(t.v1.size(), '\0'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.resize(t.v2.size());
BOOST_TEST(s.size() == t.v2.size());
BOOST_TEST(s == string(t.v2.size(), '\0'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.resize(t.v1.size());
s.resize(t.v2.size());
BOOST_TEST(s == string(t.v2.size(), '\0'));
s.resize(t.v1.size());
BOOST_TEST(s == string(t.v1.size(), '\0'));
});
}
// resize(size_type, char)
{
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.resize(t.v1.size(), '*');
BOOST_TEST(s.size() == t.v1.size());
BOOST_TEST(s == string(t.v1.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.resize(t.v2.size(), '*');
BOOST_TEST(s.size() == t.v2.size());
BOOST_TEST(s == string(t.v2.size(), '*'));
});
fail_loop([&](storage_ptr const& sp)
{
string s(sp);
s.resize(t.v1.size(), '*');
s.resize(t.v2.size(), '*');
BOOST_TEST(s == string(t.v2.size(), '*'));
s.resize(t.v1.size());
BOOST_TEST(s == string(t.v1.size(), '*'));
});
}
}
void
testSwap()
{
test_vectors const t;
// swap
{
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v1, sp);
string s2(t.v2, sp);
s1.swap(s2);
BOOST_TEST(s1 == t.v2);
BOOST_TEST(s2 == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v1, sp);
string s2(t.v2, sp);
swap(s1, s2);
BOOST_TEST(s1 == t.v2);
BOOST_TEST(s2 == t.v1);
});
fail_loop([&](storage_ptr const& sp)
{
string s1(t.v1);
string s2(t.v2, sp);
s1.swap(s2);
BOOST_TEST(s1 == t.v2);
BOOST_TEST(s2 == t.v1);
});
}
}
void
testFind()
{
test_vectors const t;
string const s1 = t.v1;
// find(string_view, size_type)
BOOST_TEST(s1.find("bcd") == 1);
BOOST_TEST(s1.find("cde") == 2);
BOOST_TEST(s1.find("bcd", 0) == 1);
BOOST_TEST(s1.find("cde", 1) == 2);
BOOST_TEST(s1.find("efg", 5) == string::npos);
// find(char, size_type)
BOOST_TEST(s1.find('b') == 1);
BOOST_TEST(s1.find('c', 1) == 2);
BOOST_TEST(s1.find('e', 5) == string::npos);
}
void
testRfind()
{
test_vectors const t;
string const s1 = t.v1;
// rfind(string_view, size_type)
BOOST_TEST(s1.rfind("bcd") == 1);
BOOST_TEST(s1.rfind("cde") == 2);
BOOST_TEST(s1.rfind("bcd", 1) == 1);
BOOST_TEST(s1.rfind("cde", 2) == 2);
BOOST_TEST(s1.rfind("efg", 3) == string::npos);
// rfind(char, size_type)
BOOST_TEST(s1.rfind('b') == 1);
BOOST_TEST(s1.rfind('c', 2) == 2);
BOOST_TEST(s1.rfind('e', 3) == string::npos);
}
void
testFindFirstOf()
{
test_vectors const t;
string const s1 = t.v1;
// find_first_of(string_view, size_type)
BOOST_TEST(s1.find_first_of("bcd") == 1);
BOOST_TEST(s1.find_first_of("cde") == 2);
BOOST_TEST(s1.find_first_of("bcd", 0) == 1);
BOOST_TEST(s1.find_first_of("cde", 1) == 2);
BOOST_TEST(s1.find_first_of("efg", 7) == string::npos);
}
void
testFindFirstNotOf()
{
test_vectors const t;
string const s1 = t.v1;
// find_first_not_of(string_view, size_type)
BOOST_TEST(s1.find_first_not_of("abc") == 3);
BOOST_TEST(s1.find_first_not_of("cde") == 0);
BOOST_TEST(s1.find_first_not_of("bcd", 0) == 0);
BOOST_TEST(s1.find_first_not_of("cde", 2) == 5);
// find_first_not_of(char, size_type)
BOOST_TEST(s1.find_first_not_of('b') == 0);
BOOST_TEST(s1.find_first_not_of('a', 0) == 1);
BOOST_TEST(s1.find_first_not_of('e', 4) == 5);
}
void
testFindLastOf()
{
test_vectors const t;
string const s1 = t.v1;
// find_last_of(string_view, size_type)
BOOST_TEST(s1.find_last_of("bcd") == 3);
BOOST_TEST(s1.find_last_of("cde") == 4);
BOOST_TEST(s1.find_last_of("bcd", 3) == 3);
BOOST_TEST(s1.find_last_of("cde", 5) == 4);
BOOST_TEST(s1.find_last_of("efg", 3) == string::npos);
}
void
testFindLastNotOf()
{
test_vectors const t;
string const s1 = t.v1;
// find_last_not_of(string_view, size_type)
BOOST_TEST(s1.find_last_not_of("abc", 3) == 3);
BOOST_TEST(s1.find_last_not_of("bcd", 3) == 0);
BOOST_TEST(s1.find_last_not_of("efg", 4) == 3);
BOOST_TEST(s1.find_last_not_of("abc", 2) == string::npos);
// find_first_not_of(char, size_type)
BOOST_TEST(s1.find_last_not_of('a', 3) == 3);
BOOST_TEST(s1.find_last_not_of('e', 4) == 3);
BOOST_TEST(s1.find_last_not_of('a', 0) == string::npos);
}
void
testNonMembers()
{
test_vectors const t;
string const s1(t.v1);
string const s2(t.v2);
auto const v1(t.v1);
auto const v2(t.v2);
auto const c1 = t.s1.c_str();
auto const c2 = t.s2.c_str();
BOOST_TEST(! operator< (s1, s2));
BOOST_TEST(! operator< (s1, v2));
BOOST_TEST(! operator< (s1, c2));
BOOST_TEST(! operator<=(s1, s2));
BOOST_TEST(! operator<=(s1, v2));
BOOST_TEST(! operator<=(s1, c2));
BOOST_TEST(! operator==(s1, s2));
BOOST_TEST(! operator==(s1, v2));
BOOST_TEST(! operator==(s1, c2));
BOOST_TEST( operator!=(s1, s2));
BOOST_TEST( operator!=(s1, v2));
BOOST_TEST( operator!=(s1, c2));
BOOST_TEST( operator>=(s1, s2));
BOOST_TEST( operator>=(s1, v2));
BOOST_TEST( operator>=(s1, c2));
BOOST_TEST( operator> (s1, s2));
BOOST_TEST( operator> (s1, v2));
BOOST_TEST( operator> (s1, c2));
BOOST_TEST( operator< (s2, s1));
BOOST_TEST( operator< (s2, v1));
BOOST_TEST( operator< (s2, c1));
BOOST_TEST( operator<=(s2, s1));
BOOST_TEST( operator<=(s2, v1));
BOOST_TEST( operator<=(s2, c1));
BOOST_TEST( operator!=(s2, s1));
BOOST_TEST( operator!=(s2, v1));
BOOST_TEST( operator!=(s2, c1));
BOOST_TEST(! operator==(s2, s1));
BOOST_TEST(! operator==(s2, v1));
BOOST_TEST(! operator==(s2, c1));
BOOST_TEST(! operator>=(s2, s1));
BOOST_TEST(! operator>=(s2, v1));
BOOST_TEST(! operator>=(s2, c1));
BOOST_TEST(! operator> (s2, s1));
BOOST_TEST(! operator> (s2, v1));
BOOST_TEST(! operator> (s2, c1));
BOOST_TEST( operator< (s2, s1));
BOOST_TEST( operator< (v2, s1));
BOOST_TEST( operator< (c2, s1));
BOOST_TEST( operator<=(s2, s1));
BOOST_TEST( operator<=(v2, s1));
BOOST_TEST( operator<=(c2, s1));
BOOST_TEST( operator!=(s2, s1));
BOOST_TEST( operator!=(v2, s1));
BOOST_TEST( operator!=(c2, s1));
BOOST_TEST(! operator==(s2, s1));
BOOST_TEST(! operator==(v2, s1));
BOOST_TEST(! operator==(c2, s1));
BOOST_TEST(! operator>=(s2, s1));
BOOST_TEST(! operator>=(v2, s1));
BOOST_TEST(! operator>=(c2, s1));
BOOST_TEST(! operator> (s2, s1));
BOOST_TEST(! operator> (v2, s1));
BOOST_TEST(! operator> (c2, s1));
BOOST_TEST(! operator< (s1, s2));
BOOST_TEST(! operator< (v1, s2));
BOOST_TEST(! operator< (c1, s2));
BOOST_TEST(! operator<=(s1, s2));
BOOST_TEST(! operator<=(v1, s2));
BOOST_TEST(! operator<=(c1, s2));
BOOST_TEST(! operator==(s1, s2));
BOOST_TEST(! operator==(v1, s2));
BOOST_TEST(! operator==(c1, s2));
BOOST_TEST( operator!=(s1, s2));
BOOST_TEST( operator!=(v1, s2));
BOOST_TEST( operator!=(c1, s2));
BOOST_TEST( operator>=(s1, s2));
BOOST_TEST( operator>=(v1, s2));
BOOST_TEST( operator>=(c1, s2));
BOOST_TEST( operator> (s1, s2));
BOOST_TEST( operator> (v1, s2));
BOOST_TEST( operator> (c1, s2));
}
void
testHash()
{
// libstdc++ 4.8 bug
#if !defined(__GNUC__) || (__GNUC__ > 4 || \
(__GNUC__ == 4 && __GNUC_MINOR__ > 8))
{
std::unordered_set<string> us;
us.emplace("first");
us.emplace("second");
}
{
std::unordered_set<string>(
0,
std::hash<string>(32));
}
#endif
{
std::hash<string> h1(32);
std::hash<string> h2(h1);
std::hash<string> h3(59);
h1 = h3;
h2 = h3;
(void)h2;
}
}
void
run()
{
testConstruction();
testAssignment();
testAssign();
testElementAccess();
testIterators();
testCapacity();
testClear();
testInsert();
testErase();
testPushPop();
testAppend();
testPlusEquals();
testCompare();
testStartEndsWith();
testReplace();
testSubStr();
testCopy();
testResize();
testSwap();
testFind();
testRfind();
testFindFirstOf();
testFindFirstNotOf();
testFindLastOf();
testFindLastNotOf();
testNonMembers();
testHash();
}
};
TEST_SUITE(string_test, "boost.json.string");
BOOST_JSON_NS_END
| 79,166 | 26,231 |
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Classes for monitoring contacts of tracked vehicle subsystems.
//
// =============================================================================
#include "chrono/physics/ChLoadsBody.h"
#include "chrono_vehicle/tracked_vehicle/ChTrackContactManager.h"
#include "chrono_vehicle/tracked_vehicle/ChTrackedVehicle.h"
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
ChTrackContactManager::ChTrackContactManager()
: m_initialized(false), m_flags(0), m_collect(false), m_shoe_index_L(0), m_shoe_index_R(0) {
}
void ChTrackContactManager::Process(ChTrackedVehicle* vehicle) {
// Initialize the manager if not already done.
if (!m_initialized) {
m_chassis = vehicle->GetChassis();
m_sprocket_L = vehicle->GetTrackAssembly(LEFT)->GetSprocket();
m_sprocket_R = vehicle->GetTrackAssembly(RIGHT)->GetSprocket();
if (vehicle->GetTrackAssembly(LEFT)->GetNumTrackShoes() > m_shoe_index_L &&
vehicle->GetTrackAssembly(RIGHT)->GetNumTrackShoes() > m_shoe_index_R) {
m_shoe_L = vehicle->GetTrackAssembly(LEFT)->GetTrackShoe(m_shoe_index_L);
m_shoe_R = vehicle->GetTrackAssembly(RIGHT)->GetTrackShoe(m_shoe_index_R);
}
m_idler_L = vehicle->GetTrackAssembly(LEFT)->GetIdler();
m_idler_R = vehicle->GetTrackAssembly(RIGHT)->GetIdler();
m_initialized = true;
}
if (m_flags == 0)
return;
// Clear lists
m_chassis_contacts.clear();
m_sprocket_L_contacts.clear();
m_sprocket_R_contacts.clear();
m_shoe_L_contacts.clear();
m_shoe_R_contacts.clear();
m_idler_L_contacts.clear();
m_idler_R_contacts.clear();
// Traverse all system contacts and extract information.
std::shared_ptr<ChTrackContactManager> shared_this(this, [](ChTrackContactManager*) {});
vehicle->GetSystem()->GetContactContainer()->ReportAllContacts(shared_this);
// Collect contact information data.
// Print current time, and number of contacts involving the chassis, left/right sprockets,
// left/right idlers, left/right track shoes, followed by the location of the contacts, in the
// same order as above, expressed in the local frame of the respective body.
if (m_collect) {
// Get number of contacts in all lists;
size_t n_chassis = m_chassis_contacts.size();
size_t n_sprocket_L = m_sprocket_L_contacts.size();
size_t n_sprocket_R = m_sprocket_R_contacts.size();
size_t n_idler_L = m_idler_L_contacts.size();
size_t n_idler_R = m_idler_R_contacts.size();
size_t n_shoe_L = m_shoe_L_contacts.size();
size_t n_shoe_R = m_shoe_R_contacts.size();
// Only collect data at this time if there is at least one monitored contact
size_t n_contacts = n_chassis + n_sprocket_L + n_sprocket_R + n_idler_L + n_idler_R + n_shoe_L + n_shoe_R;
if (n_contacts != 0) {
// Current simulation time
m_csv << vehicle->GetChTime();
// Number of contacts on vehicle parts
m_csv << m_chassis_contacts.size();
m_csv << m_sprocket_L_contacts.size();
m_csv << m_sprocket_R_contacts.size();
m_csv << m_idler_L_contacts.size();
m_csv << m_idler_R_contacts.size();
m_csv << m_shoe_L_contacts.size();
m_csv << m_shoe_R_contacts.size();
// Chassis contact points
for (const auto& c : m_chassis_contacts) {
m_csv << m_chassis->GetBody()->TransformPointParentToLocal(c.m_point);
}
for (const auto& c : m_sprocket_L_contacts) {
m_csv << m_sprocket_L->GetGearBody()->TransformPointParentToLocal(c.m_point);
}
// Right sprocket contact points
for (const auto& c : m_sprocket_R_contacts) {
m_csv << m_sprocket_R->GetGearBody()->TransformPointParentToLocal(c.m_point);
}
// Left idler contact points
for (const auto& c : m_idler_L_contacts) {
m_csv << m_idler_L->GetWheelBody()->TransformPointParentToLocal(c.m_point);
}
// Right idler contact points
for (const auto& c : m_idler_R_contacts) {
m_csv << m_idler_R->GetWheelBody()->TransformPointParentToLocal(c.m_point);
}
// Left track shoe contact points
if (m_shoe_L) {
for (const auto& c : m_shoe_L_contacts) {
m_csv << m_shoe_L->GetShoeBody()->TransformPointParentToLocal(c.m_point);
}
}
// Right track shoe contact points
if (m_shoe_R) {
for (const auto& c : m_shoe_R_contacts) {
m_csv << m_shoe_R->GetShoeBody()->TransformPointParentToLocal(c.m_point);
}
}
m_csv << std::endl;
}
}
}
// -----------------------------------------------------------------------------
bool ChTrackContactManager::InContact(TrackedCollisionFlag::Enum part) const {
switch (part) {
case TrackedCollisionFlag::CHASSIS:
return m_chassis_contacts.size() != 0;
case TrackedCollisionFlag::SPROCKET_LEFT:
return m_sprocket_L_contacts.size() != 0;
case TrackedCollisionFlag::SPROCKET_RIGHT:
return m_sprocket_R_contacts.size() != 0;
case TrackedCollisionFlag::IDLER_LEFT:
return m_idler_L_contacts.size() != 0;
case TrackedCollisionFlag::IDLER_RIGHT:
return m_idler_R_contacts.size() != 0;
case TrackedCollisionFlag::SHOES_LEFT:
return m_shoe_L_contacts.size() != 0;
case TrackedCollisionFlag::SHOES_RIGHT:
return m_shoe_R_contacts.size() != 0;
default:
return false;
}
}
// -----------------------------------------------------------------------------
ChVector<> ChTrackContactManager::GetSprocketResistiveTorque(VehicleSide side) const {
const auto& contacts = (side == VehicleSide::LEFT) ? m_sprocket_L_contacts : m_sprocket_R_contacts;
const auto& spoint =
(side == VehicleSide::LEFT) ? m_sprocket_L->GetGearBody()->GetPos() : m_sprocket_R->GetGearBody()->GetPos();
ChVector<> torque(0);
for (auto& c : contacts) {
ChVector<> F = c.m_csys * c.m_force;
ChVector<> T = c.m_csys * c.m_torque;
torque += (c.m_point - spoint).Cross(F) + T;
}
return torque;
}
// -----------------------------------------------------------------------------
bool ChTrackContactManager::OnReportContact(const ChVector<>& pA,
const ChVector<>& pB,
const ChMatrix33<>& plane_coord,
const double& distance,
const double& eff_radius,
const ChVector<>& react_forces,
const ChVector<>& react_torques,
ChContactable* modA,
ChContactable* modB) {
ContactInfo info;
// Ignore contacts with zero force or positive separation.
if (distance > 0 || react_forces.IsNull())
return true;
// Extract contacts on chassis.
if (IsFlagSet(TrackedCollisionFlag::CHASSIS)) {
if (modA == m_chassis->GetBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_chassis_contacts.push_back(info);
}
if (modB == m_chassis->GetBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_chassis_contacts.push_back(info);
}
}
// Extract contacts on sprockets.
if (IsFlagSet(TrackedCollisionFlag::SPROCKET_LEFT)) {
if (modA == m_sprocket_L->GetGearBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_sprocket_L_contacts.push_back(info);
}
if (modB == m_sprocket_L->GetGearBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_sprocket_L_contacts.push_back(info);
}
}
if (IsFlagSet(TrackedCollisionFlag::SPROCKET_RIGHT)) {
if (modA == m_sprocket_R->GetGearBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_sprocket_R_contacts.push_back(info);
}
if (modB == m_sprocket_R->GetGearBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_sprocket_R_contacts.push_back(info);
}
}
// Extract contacts on track shoes (discard contacts with sprockets)
if (IsFlagSet(TrackedCollisionFlag::SHOES_LEFT)) {
if (modA == m_shoe_L->GetShoeBody().get() && modB != m_sprocket_L->GetGearBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_shoe_L_contacts.push_back(info);
}
if (modB == m_shoe_L->GetShoeBody().get() && modA != m_sprocket_L->GetGearBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_shoe_L_contacts.push_back(info);
}
}
if (IsFlagSet(TrackedCollisionFlag::SHOES_RIGHT)) {
if (modA == m_shoe_R->GetShoeBody().get() && modB != m_sprocket_R->GetGearBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_shoe_R_contacts.push_back(info);
}
if (modB == m_shoe_R->GetShoeBody().get() && modA != m_sprocket_R->GetGearBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_shoe_R_contacts.push_back(info);
}
}
// Extract contacts on idler wheels.
if (IsFlagSet(TrackedCollisionFlag::IDLER_LEFT)) {
if (modA == m_idler_L->GetWheelBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_idler_L_contacts.push_back(info);
}
if (modB == m_idler_L->GetWheelBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_idler_L_contacts.push_back(info);
}
}
if (IsFlagSet(TrackedCollisionFlag::IDLER_RIGHT)) {
if (modA == m_idler_R->GetWheelBody().get()) {
info.m_point = pA;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_idler_R_contacts.push_back(info);
}
if (modB == m_idler_R->GetWheelBody().get()) {
info.m_point = pB;
info.m_csys = plane_coord;
info.m_force = react_forces;
info.m_torque = react_torques;
m_idler_R_contacts.push_back(info);
}
}
// Continue scanning contacts
return true;
}
void ChTrackContactManager::WriteContacts(const std::string& filename) {
if (m_collect && m_flags != 0)
m_csv.write_to_file(filename);
}
// -----------------------------------------------------------------------------
ChTrackCollisionManager::ChTrackCollisionManager(ChTrackedVehicle* vehicle) : m_idler_shoe(true), m_wheel_shoe(true) {}
void ChTrackCollisionManager::Reset() {
// Empty collision lists
m_collisions_idler.clear();
m_collisions_wheel.clear();
}
static const double nrm_threshold = 0.8;
bool ChTrackCollisionManager::OnNarrowphase(collision::ChCollisionInfo& contactinfo) {
ChBody* bodyA = dynamic_cast<ChBody*>(contactinfo.modelA->GetContactable());
ChBody* bodyB = dynamic_cast<ChBody*>(contactinfo.modelB->GetContactable());
if (!bodyA || !bodyB)
return true;
// Body B is a track shoe body
if (bodyB->GetIdentifier() == BodyID::SHOE_BODY) {
// Express collision normal in body A (wheel) frame
auto nrm = bodyA->TransformDirectionParentToLocal(contactinfo.vN);
// Identify "lateral" contacts (assumed to be with a guiding pin) and let Chrono generate contacts
if (std::abs(nrm.y()) > nrm_threshold) {
return true;
}
// Intercept and cache collisions between wheels and track pad.
// Do not generate Chrono contact for such collisions.
if (m_idler_shoe && bodyA->GetIdentifier() == BodyID::IDLER_BODY) {
m_collisions_idler.push_back(contactinfo);
return false;
}
if (m_wheel_shoe && bodyA->GetIdentifier() == BodyID::WHEEL_BODY) {
m_collisions_wheel.push_back(contactinfo);
return false;
}
}
// Body A is a track shoe body
if (bodyA->GetIdentifier() == BodyID::SHOE_BODY) {
// Express collision normal in body B (wheel) frame
auto nrm = bodyB->TransformDirectionParentToLocal(contactinfo.vN);
// Identify "lateral" contacts (assumed to be with a guiding pin) and let Chrono generate contacts
if (std::abs(nrm.y()) > nrm_threshold) {
return true;
}
// Intercept and cache collisions between wheels and track pad.
// Do not generate Chrono contact for such collisions.
if (m_idler_shoe && bodyB->GetIdentifier() == BodyID::IDLER_BODY) {
auto contactinfoS = contactinfo;
contactinfoS.SwapModels();
m_collisions_idler.push_back(contactinfoS);
return false;
}
if (m_wheel_shoe && bodyB->GetIdentifier() == BodyID::WHEEL_BODY) {
auto contactinfoS = contactinfo;
contactinfoS.SwapModels();
m_collisions_wheel.push_back(contactinfoS);
return false;
}
}
// Let Chrono generate contact for any other collision
return true;
}
// -----------------------------------------------------------------------------
void ChTrackCustomContact::Setup() {
// Calculate contact forces for all current wheel-shoe collisions, calling the user-supplied callback
ApplyForces();
// Perform a full update of the load container
ChLoadContainer::Update(ChTime, false);
}
void ChTrackCustomContact::Update(double mytime, bool update_assets) {
// Note: since Update could be called multiple times per time step, we do not invoke the
// callback function here to calculate custom contact forces (since they are based on collision
// detection information which only occurs once per time step). Instead, we do this in Setup.
// We still override this function to prevent unnecessary calculations in the base class Update.
ChTime = mytime;
}
void ChTrackCustomContact::ApplyForces() {
// Reset the load list for this load container
GetLoadList().clear();
////std::cout << "Idler-shoe collisions: " << m_collision_manager->m_collisions_idler.size() << std::endl;
////std::cout << "Wheel-shoe collisions: " << m_collision_manager->m_collisions_wheel.size() << std::endl;
ChVector<> forceB;
for (auto& cInfo : m_collision_manager->m_collisions_idler) {
std::shared_ptr<ChBody> bodyA(static_cast<ChBody*>(cInfo.modelA->GetContactable()), [](ChBody*) {});
std::shared_ptr<ChBody> bodyB(static_cast<ChBody*>(cInfo.modelB->GetContactable()), [](ChBody*) {});
// Call user-provided force calculation
ComputeForce(cInfo, bodyA, bodyB, true, forceB);
// Apply equal and opposite forces on the two bodies (road wheel and track shoe) in contact
auto loadA = chrono_types::make_shared<ChLoadBodyForce>(bodyA, -forceB, false, cInfo.vpA, false);
auto loadB = chrono_types::make_shared<ChLoadBodyForce>(bodyB, +forceB, false, cInfo.vpB, false);
Add(loadA);
Add(loadB);
}
for (auto& cInfo : m_collision_manager->m_collisions_wheel) {
std::shared_ptr<ChBody> bodyA(static_cast<ChBody*>(cInfo.modelA->GetContactable()), [](ChBody*) {});
std::shared_ptr<ChBody> bodyB(static_cast<ChBody*>(cInfo.modelB->GetContactable()), [](ChBody*) {});
// Call user-provided force calculation
ComputeForce(cInfo, bodyA, bodyB, false, forceB);
// Apply equal and opposite forces on the two bodies (wheel and track shoe) in contact
auto loadA = chrono_types::make_shared<ChLoadBodyForce>(bodyA, -forceB, false, cInfo.vpA, false);
auto loadB = chrono_types::make_shared<ChLoadBodyForce>(bodyB, +forceB, false, cInfo.vpB, false);
Add(loadA);
Add(loadB);
}
}
} // end namespace vehicle
} // end namespace chrono
| 18,256 | 5,852 |
#include "GroundTileMap.hpp"
#include "Obstacle.hpp"
#include "Collectable.hpp"
namespace fs::scene
{
void GroundTileMap::create(io::InputManager& inputManager, physics::PhysicsManager& physicsManager,
graphics::SpriteSheet& tilesSpriteSheet, graphics::SpriteSheet& itemsSpriteSheet)
{
GroundTileMap::tilesSpriteSheet = &tilesSpriteSheet;
GroundTileMap::itemsSpriteSheet = &itemsSpriteSheet;
createSprites();
core::Vector2i size{40, 20};
core::Vector2f tileSize{grassLeftSprite->getWidthUnits(), grassLeftSprite->getHeightUnits()};
TileMapSceneNode::create(inputManager, size, tileSize);
setTileBuilderCallback([&](core::fs_int32 id) -> SceneNode*
{
const graphics::Sprite* sprite = nullptr;
if (id == leftId)
{
return createGroundBrick(grassLeftSprite, physicsManager);
}
else if (id == midId)
{
return createGroundBrick(grassMidSprite, physicsManager);
}
else if (id == rightId)
{
return createGroundBrick(grassRightSprite, physicsManager);
}
else if (id == plantId)
{
auto* spriteSceneNode = new SpriteSceneNode();
spriteSceneNode->create(inputManager, *plantSprite);
return spriteSceneNode;
}
else if (id == weightId)
{
auto* obstacleSceneNode = new Obstacle();
obstacleSceneNode->create(inputManager, *weightSprite, physicsManager);
return obstacleSceneNode;
}
else if (id == coinId)
{
auto* collectableSceneNode = new Collectable();
collectableSceneNode->create(inputManager, *coinSprite, physicsManager);
return collectableSceneNode;
}
else
{
throw std::runtime_error("Undefined ground brick");
}
});
//@formatter:off
std::vector<std::vector<core::fs_int32>> ids =
{
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, plantId, -1, coinId, -1, plantId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, midId, midId, midId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, coinId, coinId, coinId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, coinId, plantId, coinId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, weightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, plantId, coinId, plantId, -1, -1, -1, -1, -1, -1, -1, -1, -1, coinId, coinId, coinId, coinId, -1, -1, coinId, -1, plantId, -1, coinId, -1, plantId, -1, -1, weightId, coinId, -1, -1, coinId, coinId, coinId, coinId},
{leftId, midId, rightId, -1, leftId, midId, midId, midId, rightId, -1, -1, -1, -1, -1, -1, -1, -1, leftId, midId, midId, rightId, -1, -1, leftId, midId, midId, midId, midId, midId, midId, midId, midId, midId, rightId, -1, -1, leftId, midId, midId, rightId},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
//@formatter:on
setTilesIds(ids);
}
GroundBrick*
GroundTileMap::createGroundBrick(const graphics::Sprite* sprite, physics::PhysicsManager& physicsManager) const
{
auto* groundBrick = new GroundBrick();
groundBrick->create(*inputManager, *sprite, physicsManager);
return groundBrick;
}
void GroundTileMap::createSprites()
{
grassLeftSprite = tilesSpriteSheet->addSprite({504, 648, 70, 70});
grassMidSprite = tilesSpriteSheet->addSprite({504, 576, 70, 70});
grassRightSprite = tilesSpriteSheet->addSprite({504, 504, 70, 70});
plantSprite = itemsSpriteSheet->addSprite({0, 363, 70, 70});
cactusSprite = itemsSpriteSheet->addSprite({360, 216, 70, 70});
weightSprite = itemsSpriteSheet->addSprite({490, 144, 70, 70});
coinSprite = itemsSpriteSheet->addSprite({288, 360, 70, 70});
}
void GroundTileMap::destroy()
{
TileMapSceneNode::destroy();
}
void GroundTileMap::setTilesIds(const std::vector<std::vector<core::fs_int32>>& vector)
{
for (core::fs_int64 y = 0; y < vector.size(); ++y)
{
for (core::fs_int64 x = 0; x < vector[y].size(); ++x)
{
setTileId(core::Vector2i{x, y}, vector[y][x]);
}
}
}
}
| 10,381 | 4,217 |
/*
* Edict is a blackboard messaging system -- have fun!
* Copyright (c) 2018 Alex Raymond, Kier Dugan.
*/
#include <edict/edict.h>
using namespace edict;
#include <iostream>
#include <regex>
using namespace std;
void helloHandler(const string &message_)
{
cout << message_ << ", Handler!" << endl;
}
void printer(const string &message_)
{
cout << "printer: " << message_ << endl;
}
int main(int argc, char **argv)
{
edict::Broadcaster broadcaster;
broadcaster.subscribe("/edict/hello", &helloHandler);
broadcaster.subscribe("/edict/hello", &printer);
broadcaster.subscribe(regex("(\\+|-)?[[:digit:]]+"), &helloHandler);
broadcaster.subscribe([](const string &topic_) { return topic_.size() < 6; }, &printer);
broadcaster.publish("/edict/hello", "Hello");
broadcaster.publish("1234", "Bye");
return 0;
}
| 853 | 299 |
// Day03.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "TriangleTest.h"
int main()
{
signed ValidRowTriangles = 0;
signed ValidColumnTriangles = 0;
StringVectorVector Lines = GetFileLineParts("Input.txt");
TriangleTest RowTest;
std::array<TriangleTest, 3> ColumnTest;
for (const StringVector & Line : Lines)
{
for (int i = 0; i < Line.size(); i++)
{
signed Side = std::atoi(Line[i].c_str());
if (RowTest.PushSide(Side))
{
ValidRowTriangles++;
}
if (ColumnTest[i].PushSide(Side))
{
ValidColumnTriangles++;
}
}
}
std::cout << "Valid Row Triangels: " << ValidRowTriangles << std::endl;
std::cout << "Valid Column Triangels: " << ValidColumnTriangles << std::endl;
system("pause");
}
| 782 | 315 |
#include <RendererCorePCH.h>
#include <Core/Graphics/Geometry.h>
#include <Core/World/World.h>
#include <Foundation/Configuration/Startup.h>
#include <RendererCore/Debug/DebugRenderer.h>
#include <RendererCore/Debug/SimpleASCIIFont.h>
#include <RendererCore/Meshes/MeshBufferResource.h>
#include <RendererCore/Pipeline/ViewData.h>
#include <RendererCore/RenderContext/RenderContext.h>
#include <RendererCore/RenderWorld/RenderWorld.h>
#include <RendererCore/Shader/ShaderResource.h>
#include <RendererCore/Textures/Texture2DResource.h>
//////////////////////////////////////////////////////////////////////////
ezDebugRendererContext::ezDebugRendererContext(const ezWorld* pWorld)
: m_Id(pWorld != nullptr ? pWorld->GetIndex() : 0)
{
}
ezDebugRendererContext::ezDebugRendererContext(const ezViewHandle& hView)
: m_Id(hView.GetInternalID().m_Data)
{
}
//////////////////////////////////////////////////////////////////////////
namespace
{
struct EZ_ALIGN_16(Vertex)
{
ezVec3 m_position;
ezColorLinearUB m_color;
};
EZ_CHECK_AT_COMPILETIME(sizeof(Vertex) == 16);
struct EZ_ALIGN_16(TexVertex)
{
ezVec3 m_position;
ezColorLinearUB m_color;
ezVec2 m_texCoord;
float padding[2];
};
EZ_CHECK_AT_COMPILETIME(sizeof(TexVertex) == 32);
struct EZ_ALIGN_16(BoxData)
{
ezShaderTransform m_transform;
ezColor m_color;
};
EZ_CHECK_AT_COMPILETIME(sizeof(BoxData) == 64);
struct EZ_ALIGN_16(GlyphData)
{
ezVec2 m_topLeftCorner;
ezColorLinearUB m_color;
ezUInt16 m_glyphIndex;
ezUInt16 m_sizeInPixel;
};
EZ_CHECK_AT_COMPILETIME(sizeof(GlyphData) == 16);
struct TextLineData2D
{
ezString m_text;
ezVec2 m_topLeftCorner;
ezColorLinearUB m_color;
ezUInt32 m_uiSizeInPixel;
};
struct TextLineData3D : public TextLineData2D
{
ezVec3 m_position;
};
struct PerContextData
{
ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_lineVertices;
ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_triangleVertices;
ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_triangle2DVertices;
ezDynamicArray<Vertex, ezAlignedAllocatorWrapper> m_line2DVertices;
ezDynamicArray<BoxData, ezAlignedAllocatorWrapper> m_lineBoxes;
ezDynamicArray<BoxData, ezAlignedAllocatorWrapper> m_solidBoxes;
ezMap<ezTexture2DResourceHandle, ezDynamicArray<TexVertex, ezAlignedAllocatorWrapper>> m_texTriangle2DVertices;
ezMap<ezTexture2DResourceHandle, ezDynamicArray<TexVertex, ezAlignedAllocatorWrapper>> m_texTriangle3DVertices;
ezDynamicArray<TextLineData2D> m_textLines2D;
ezDynamicArray<TextLineData3D> m_textLines3D;
ezDynamicArray<GlyphData, ezAlignedAllocatorWrapper> m_glyphs;
};
struct DoubleBufferedPerContextData
{
DoubleBufferedPerContextData()
{
m_uiLastRenderedFrame = 0;
m_pData[0] = nullptr;
m_pData[1] = nullptr;
}
ezUInt64 m_uiLastRenderedFrame;
ezUniquePtr<PerContextData> m_pData[2];
};
static ezHashTable<ezDebugRendererContext, DoubleBufferedPerContextData> s_PerContextData;
static ezMutex s_Mutex;
static PerContextData& GetDataForExtraction(const ezDebugRendererContext& context)
{
DoubleBufferedPerContextData& doubleBufferedData = s_PerContextData[context];
const ezUInt32 uiDataIndex = ezRenderWorld::IsRenderingThread() && (doubleBufferedData.m_uiLastRenderedFrame != ezRenderWorld::GetFrameCounter()) ? ezRenderWorld::GetDataIndexForRendering() : ezRenderWorld::GetDataIndexForExtraction();
ezUniquePtr<PerContextData>& pData = doubleBufferedData.m_pData[uiDataIndex];
if (pData == nullptr)
{
doubleBufferedData.m_pData[uiDataIndex] = EZ_DEFAULT_NEW(PerContextData);
}
return *pData;
}
static void ClearRenderData()
{
EZ_LOCK(s_Mutex);
for (auto it = s_PerContextData.GetIterator(); it.IsValid(); ++it)
{
PerContextData* pData = it.Value().m_pData[ezRenderWorld::GetDataIndexForRendering()].Borrow();
if (pData)
{
pData->m_lineVertices.Clear();
pData->m_line2DVertices.Clear();
pData->m_lineBoxes.Clear();
pData->m_solidBoxes.Clear();
pData->m_triangleVertices.Clear();
pData->m_triangle2DVertices.Clear();
pData->m_texTriangle2DVertices.Clear();
pData->m_texTriangle3DVertices.Clear();
pData->m_textLines2D.Clear();
pData->m_textLines3D.Clear();
}
}
}
static void OnRenderEvent(const ezRenderWorldRenderEvent& e)
{
if (e.m_Type == ezRenderWorldRenderEvent::Type::EndRender)
{
ClearRenderData();
}
}
struct BufferType
{
enum Enum
{
Lines,
LineBoxes,
SolidBoxes,
Triangles3D,
Triangles2D,
TexTriangles2D,
TexTriangles3D,
Glyphs,
Lines2D,
Count
};
};
static ezGALBufferHandle s_hDataBuffer[BufferType::Count];
static ezMeshBufferResourceHandle s_hLineBoxMeshBuffer;
static ezMeshBufferResourceHandle s_hSolidBoxMeshBuffer;
static ezVertexDeclarationInfo s_VertexDeclarationInfo;
static ezVertexDeclarationInfo s_TexVertexDeclarationInfo;
static ezTexture2DResourceHandle s_hDebugFontTexture;
static ezShaderResourceHandle s_hDebugGeometryShader;
static ezShaderResourceHandle s_hDebugPrimitiveShader;
static ezShaderResourceHandle s_hDebugTexturedPrimitiveShader;
static ezShaderResourceHandle s_hDebugTextShader;
enum
{
DEBUG_BUFFER_SIZE = 1024 * 256,
BOXES_PER_BATCH = DEBUG_BUFFER_SIZE / sizeof(BoxData),
LINE_VERTICES_PER_BATCH = DEBUG_BUFFER_SIZE / sizeof(Vertex),
TRIANGLE_VERTICES_PER_BATCH = (DEBUG_BUFFER_SIZE / sizeof(Vertex) / 3) * 3,
TEX_TRIANGLE_VERTICES_PER_BATCH = (DEBUG_BUFFER_SIZE / sizeof(TexVertex) / 3) * 3,
GLYPHS_PER_BATCH = DEBUG_BUFFER_SIZE / sizeof(GlyphData),
};
static void CreateDataBuffer(BufferType::Enum bufferType, ezUInt32 uiStructSize)
{
if (s_hDataBuffer[bufferType].IsInvalidated())
{
ezGALBufferCreationDescription desc;
desc.m_uiStructSize = uiStructSize;
desc.m_uiTotalSize = DEBUG_BUFFER_SIZE;
desc.m_BufferType = ezGALBufferType::Generic;
desc.m_bUseAsStructuredBuffer = true;
desc.m_bAllowShaderResourceView = true;
desc.m_ResourceAccess.m_bImmutable = false;
s_hDataBuffer[bufferType] = ezGALDevice::GetDefaultDevice()->CreateBuffer(desc);
}
}
static void CreateVertexBuffer(BufferType::Enum bufferType, ezUInt32 uiVertexSize)
{
if (s_hDataBuffer[bufferType].IsInvalidated())
{
ezGALBufferCreationDescription desc;
desc.m_uiStructSize = uiVertexSize;
desc.m_uiTotalSize = DEBUG_BUFFER_SIZE;
desc.m_BufferType = ezGALBufferType::VertexBuffer;
desc.m_ResourceAccess.m_bImmutable = false;
s_hDataBuffer[bufferType] = ezGALDevice::GetDefaultDevice()->CreateBuffer(desc);
}
}
static void DestroyBuffer(BufferType::Enum bufferType)
{
ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice();
if (!s_hDataBuffer[bufferType].IsInvalidated())
{
pDevice->DestroyBuffer(s_hDataBuffer[bufferType]);
s_hDataBuffer[bufferType].Invalidate();
}
}
template <typename AddFunc>
static void AddTextLines(const ezDebugRendererContext& context, ezStringView text, const ezVec2I32& positionInPixel, float fSizeInPixel, ezDebugRenderer::HorizontalAlignment::Enum horizontalAlignment, ezDebugRenderer::VerticalAlignment::Enum verticalAlignment, AddFunc func)
{
if (text.IsEmpty())
return;
ezHybridArray<ezStringView, 8> lines;
ezUInt32 maxLineLength = 0;
ezStringBuilder sb;
if (text.FindSubString("\n"))
{
sb = text;
sb.Split(false, lines, "\n");
for (auto& line : lines)
{
maxLineLength = ezMath::Max(maxLineLength, line.GetElementCount());
}
}
else
{
lines.PushBack(text);
maxLineLength = text.GetElementCount();
}
// Glyphs only use 8x10 pixels in their 16x16 pixel block, thus we don't advance by full size here.
const float fGlyphWidth = ezMath::Ceil(fSizeInPixel * (8.0f / 16.0f));
const float fLineHeight = ezMath::Ceil(fSizeInPixel * (20.0f / 16.0f));
float screenPosX = (float)positionInPixel.x;
if (horizontalAlignment == ezDebugRenderer::HorizontalAlignment::Right)
screenPosX -= maxLineLength * fGlyphWidth;
float screenPosY = (float)positionInPixel.y;
if (verticalAlignment == ezDebugRenderer::VerticalAlignment::Center)
screenPosY -= ezMath::Ceil(lines.GetCount() * fLineHeight * 0.5f);
else if (verticalAlignment == ezDebugRenderer::VerticalAlignment::Bottom)
screenPosY -= lines.GetCount() * fLineHeight;
{
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
ezVec2 currentPos(screenPosX, screenPosY);
for (ezStringView line : lines)
{
currentPos.x = screenPosX;
if (horizontalAlignment == ezDebugRenderer::HorizontalAlignment::Center)
currentPos.x -= ezMath::Ceil(line.GetElementCount() * fGlyphWidth * 0.5f);
func(data, line, currentPos);
currentPos.y += fLineHeight;
}
}
}
static void AppendGlyphs(ezDynamicArray<GlyphData, ezAlignedAllocatorWrapper>& glyphs, const TextLineData2D& textLine)
{
ezVec2 currentPos = textLine.m_topLeftCorner;
const float fGlyphWidth = ezMath::Ceil(textLine.m_uiSizeInPixel * (8.0f / 16.0f));
for (ezUInt32 uiCharacter : textLine.m_text)
{
auto& glyphData = glyphs.ExpandAndGetRef();
glyphData.m_topLeftCorner = currentPos;
glyphData.m_color = textLine.m_color;
glyphData.m_glyphIndex = uiCharacter < 128 ? uiCharacter : 0;
glyphData.m_sizeInPixel = (ezUInt16)textLine.m_uiSizeInPixel;
currentPos.x += fGlyphWidth;
}
}
} // namespace
// clang-format off
EZ_BEGIN_SUBSYSTEM_DECLARATION(RendererCore, DebugRenderer)
BEGIN_SUBSYSTEM_DEPENDENCIES
"Foundation",
"Core"
END_SUBSYSTEM_DEPENDENCIES
ON_HIGHLEVELSYSTEMS_STARTUP
{
ezDebugRenderer::OnEngineStartup();
}
ON_HIGHLEVELSYSTEMS_SHUTDOWN
{
ezDebugRenderer::OnEngineShutdown();
}
EZ_END_SUBSYSTEM_DECLARATION;
// clang-format on
// static
void ezDebugRenderer::DrawLines(const ezDebugRendererContext& context, ezArrayPtr<const Line> lines, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/)
{
if (lines.IsEmpty())
return;
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
for (auto& line : lines)
{
const ezVec3* pPositions = &line.m_start;
const ezColor* pColors = &line.m_startColor;
for (ezUInt32 i = 0; i < 2; ++i)
{
auto& vertex = data.m_lineVertices.ExpandAndGetRef();
vertex.m_position = transform.TransformPosition(pPositions[i]);
vertex.m_color = pColors[i] * color;
}
}
}
void ezDebugRenderer::Draw2DLines(const ezDebugRendererContext& context, ezArrayPtr<const Line> lines, const ezColor& color)
{
if (lines.IsEmpty())
return;
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
for (auto& line : lines)
{
const ezVec3* pPositions = &line.m_start;
for (ezUInt32 i = 0; i < 2; ++i)
{
auto& vertex = data.m_line2DVertices.ExpandAndGetRef();
vertex.m_position = pPositions[i];
vertex.m_color = color;
}
}
}
// static
void ezDebugRenderer::DrawCross(const ezDebugRendererContext& context, const ezVec3& globalPosition, float fLineLength, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/)
{
if (fLineLength <= 0.0f)
return;
const float fHalfLineLength = fLineLength * 0.5f;
const ezVec3 xAxis = ezVec3::UnitXAxis() * fHalfLineLength;
const ezVec3 yAxis = ezVec3::UnitYAxis() * fHalfLineLength;
const ezVec3 zAxis = ezVec3::UnitZAxis() * fHalfLineLength;
Line lines[3] = {{transform.TransformPosition(globalPosition - xAxis), transform.TransformPosition(globalPosition + xAxis)}, {transform.TransformPosition(globalPosition - yAxis), transform.TransformPosition(globalPosition + yAxis)},
{transform.TransformPosition(globalPosition - zAxis), transform.TransformPosition(globalPosition + zAxis)}};
DrawLines(context, lines, color);
}
// static
void ezDebugRenderer::DrawLineBox(const ezDebugRendererContext& context, const ezBoundingBox& box, const ezColor& color, const ezTransform& transform)
{
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
auto& boxData = data.m_lineBoxes.ExpandAndGetRef();
ezTransform boxTransform(box.GetCenter(), ezQuat::IdentityQuaternion(), box.GetHalfExtents());
boxData.m_transform = transform * boxTransform;
boxData.m_color = color;
}
// static
void ezDebugRenderer::DrawLineBoxCorners(const ezDebugRendererContext& context, const ezBoundingBox& box, float fCornerFraction, const ezColor& color, const ezTransform& transform)
{
fCornerFraction = ezMath::Clamp(fCornerFraction, 0.0f, 1.0f) * 0.5f;
ezVec3 corners[8];
box.GetCorners(corners);
for (ezUInt32 i = 0; i < 8; ++i)
{
corners[i] = transform * corners[i];
}
ezVec3 edgeEnds[12];
edgeEnds[0] = corners[1]; // 0 -> 1
edgeEnds[1] = corners[3]; // 1 -> 3
edgeEnds[2] = corners[0]; // 2 -> 0
edgeEnds[3] = corners[2]; // 3 -> 2
edgeEnds[4] = corners[5]; // 4 -> 5
edgeEnds[5] = corners[7]; // 5 -> 7
edgeEnds[6] = corners[4]; // 6 -> 4
edgeEnds[7] = corners[6]; // 7 -> 6
edgeEnds[8] = corners[4]; // 0 -> 4
edgeEnds[9] = corners[5]; // 1 -> 5
edgeEnds[10] = corners[6]; // 2 -> 6
edgeEnds[11] = corners[7]; // 3 -> 7
Line lines[24];
for (ezUInt32 i = 0; i < 12; ++i)
{
ezVec3 edgeStart = corners[i % 8];
ezVec3 edgeEnd = edgeEnds[i];
ezVec3 edgeDir = edgeEnd - edgeStart;
lines[i * 2 + 0].m_start = edgeStart;
lines[i * 2 + 0].m_end = edgeStart + edgeDir * fCornerFraction;
lines[i * 2 + 1].m_start = edgeEnd;
lines[i * 2 + 1].m_end = edgeEnd - edgeDir * fCornerFraction;
}
DrawLines(context, lines, color);
}
// static
void ezDebugRenderer::DrawLineSphere(const ezDebugRendererContext& context, const ezBoundingSphere& sphere, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/)
{
enum
{
NUM_SEGMENTS = 32
};
const ezVec3 vCenter = sphere.m_vCenter;
const float fRadius = sphere.m_fRadius;
const ezAngle stepAngle = ezAngle::Degree(360.0f / NUM_SEGMENTS);
Line lines[NUM_SEGMENTS * 3];
for (ezUInt32 s = 0; s < NUM_SEGMENTS; ++s)
{
const float fS1 = (float)s;
const float fS2 = (float)(s + 1);
const float fCos1 = ezMath::Cos(fS1 * stepAngle);
const float fCos2 = ezMath::Cos(fS2 * stepAngle);
const float fSin1 = ezMath::Sin(fS1 * stepAngle);
const float fSin2 = ezMath::Sin(fS2 * stepAngle);
lines[s * 3 + 0].m_start = transform * (vCenter + ezVec3(0.0f, fCos1, fSin1) * fRadius);
lines[s * 3 + 0].m_end = transform * (vCenter + ezVec3(0.0f, fCos2, fSin2) * fRadius);
lines[s * 3 + 1].m_start = transform * (vCenter + ezVec3(fCos1, 0.0f, fSin1) * fRadius);
lines[s * 3 + 1].m_end = transform * (vCenter + ezVec3(fCos2, 0.0f, fSin2) * fRadius);
lines[s * 3 + 2].m_start = transform * (vCenter + ezVec3(fCos1, fSin1, 0.0f) * fRadius);
lines[s * 3 + 2].m_end = transform * (vCenter + ezVec3(fCos2, fSin2, 0.0f) * fRadius);
}
DrawLines(context, lines, color);
}
void ezDebugRenderer::DrawLineCapsuleZ(const ezDebugRendererContext& context, float fLength, float fRadius, const ezColor& color, const ezTransform& transform /*= ezTransform::IdentityTransform()*/)
{
enum
{
NUM_SEGMENTS = 32,
NUM_HALF_SEGMENTS = 16,
NUM_LINES = NUM_SEGMENTS + NUM_SEGMENTS + NUM_SEGMENTS + NUM_SEGMENTS + 4,
};
const ezAngle stepAngle = ezAngle::Degree(360.0f / NUM_SEGMENTS);
Line lines[NUM_LINES];
const float fOffsetZ = fLength * 0.5f;
ezUInt32 curLine = 0;
// render 4 straight lines
lines[curLine].m_start = transform * ezVec3(-fRadius, 0, fOffsetZ);
lines[curLine].m_end = transform * ezVec3(-fRadius, 0, -fOffsetZ);
++curLine;
lines[curLine].m_start = transform * ezVec3(+fRadius, 0, fOffsetZ);
lines[curLine].m_end = transform * ezVec3(+fRadius, 0, -fOffsetZ);
++curLine;
lines[curLine].m_start = transform * ezVec3(0, -fRadius, fOffsetZ);
lines[curLine].m_end = transform * ezVec3(0, -fRadius, -fOffsetZ);
++curLine;
lines[curLine].m_start = transform * ezVec3(0, +fRadius, fOffsetZ);
lines[curLine].m_end = transform * ezVec3(0, +fRadius, -fOffsetZ);
++curLine;
// render top and bottom circle
for (ezUInt32 s = 0; s < NUM_SEGMENTS; ++s)
{
const float fS1 = (float)s;
const float fS2 = (float)(s + 1);
const float fCos1 = ezMath::Cos(fS1 * stepAngle);
const float fCos2 = ezMath::Cos(fS2 * stepAngle);
const float fSin1 = ezMath::Sin(fS1 * stepAngle);
const float fSin2 = ezMath::Sin(fS2 * stepAngle);
lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, fSin1 * fRadius, fOffsetZ);
lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, fSin2 * fRadius, fOffsetZ);
++curLine;
lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, fSin1 * fRadius, -fOffsetZ);
lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, fSin2 * fRadius, -fOffsetZ);
++curLine;
}
// render top and bottom half circles
for (ezUInt32 s = 0; s < NUM_HALF_SEGMENTS; ++s)
{
const float fS1 = (float)s;
const float fS2 = (float)(s + 1);
const float fCos1 = ezMath::Cos(fS1 * stepAngle);
const float fCos2 = ezMath::Cos(fS2 * stepAngle);
const float fSin1 = ezMath::Sin(fS1 * stepAngle);
const float fSin2 = ezMath::Sin(fS2 * stepAngle);
// top two bows
lines[curLine].m_start = transform * ezVec3(0.0f, fCos1 * fRadius, fSin1 * fRadius + fOffsetZ);
lines[curLine].m_end = transform * ezVec3(0.0f, fCos2 * fRadius, fSin2 * fRadius + fOffsetZ);
++curLine;
lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, 0.0f, fSin1 * fRadius + fOffsetZ);
lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, 0.0f, fSin2 * fRadius + fOffsetZ);
++curLine;
// bottom two bows
lines[curLine].m_start = transform * ezVec3(0.0f, fCos1 * fRadius, -fSin1 * fRadius - fOffsetZ);
lines[curLine].m_end = transform * ezVec3(0.0f, fCos2 * fRadius, -fSin2 * fRadius - fOffsetZ);
++curLine;
lines[curLine].m_start = transform * ezVec3(fCos1 * fRadius, 0.0f, -fSin1 * fRadius - fOffsetZ);
lines[curLine].m_end = transform * ezVec3(fCos2 * fRadius, 0.0f, -fSin2 * fRadius - fOffsetZ);
++curLine;
}
EZ_ASSERT_DEBUG(curLine == NUM_LINES, "Invalid line count");
DrawLines(context, lines, color);
}
// static
void ezDebugRenderer::DrawLineFrustum(const ezDebugRendererContext& context, const ezFrustum& frustum, const ezColor& color, bool bDrawPlaneNormals /*= false*/)
{
ezVec3 cornerPoints[8];
frustum.ComputeCornerPoints(cornerPoints);
Line lines[12] = {
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft]),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft]),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight]),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight]),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft]),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft]),
};
DrawLines(context, lines, color);
if (bDrawPlaneNormals)
{
ezColor normalColor = color + ezColor(0.4f, 0.4f, 0.4f);
float fDrawLength = 0.5f;
const ezVec3 nearPlaneNormal = frustum.GetPlane(0).m_vNormal * fDrawLength;
const ezVec3 farPlaneNormal = frustum.GetPlane(1).m_vNormal * fDrawLength;
const ezVec3 leftPlaneNormal = frustum.GetPlane(2).m_vNormal * fDrawLength;
const ezVec3 rightPlaneNormal = frustum.GetPlane(3).m_vNormal * fDrawLength;
const ezVec3 bottomPlaneNormal = frustum.GetPlane(4).m_vNormal * fDrawLength;
const ezVec3 topPlaneNormal = frustum.GetPlane(5).m_vNormal * fDrawLength;
Line normalLines[24] = {
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft] + nearPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight] + nearPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft] + nearPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight] + nearPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft] + farPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight] + farPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft] + farPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight] + farPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft] + leftPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft] + leftPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft] + leftPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft] + leftPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight] + rightPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight] + rightPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight] + rightPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight] + rightPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft], cornerPoints[ezFrustum::FrustumCorner::NearBottomLeft] + bottomPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearBottomRight], cornerPoints[ezFrustum::FrustumCorner::NearBottomRight] + bottomPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft], cornerPoints[ezFrustum::FrustumCorner::FarBottomLeft] + bottomPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarBottomRight], cornerPoints[ezFrustum::FrustumCorner::FarBottomRight] + bottomPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopLeft], cornerPoints[ezFrustum::FrustumCorner::NearTopLeft] + topPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::NearTopRight], cornerPoints[ezFrustum::FrustumCorner::NearTopRight] + topPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopLeft], cornerPoints[ezFrustum::FrustumCorner::FarTopLeft] + topPlaneNormal),
Line(cornerPoints[ezFrustum::FrustumCorner::FarTopRight], cornerPoints[ezFrustum::FrustumCorner::FarTopRight] + topPlaneNormal),
};
DrawLines(context, normalLines, normalColor);
}
}
// static
void ezDebugRenderer::DrawSolidBox(const ezDebugRendererContext& context, const ezBoundingBox& box, const ezColor& color, const ezTransform& transform)
{
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
auto& boxData = data.m_solidBoxes.ExpandAndGetRef();
ezTransform boxTransform(box.GetCenter(), ezQuat::IdentityQuaternion(), box.GetHalfExtents());
boxData.m_transform = transform * boxTransform;
boxData.m_color = color;
}
// static
void ezDebugRenderer::DrawSolidTriangles(const ezDebugRendererContext& context, ezArrayPtr<Triangle> triangles, const ezColor& color)
{
if (triangles.IsEmpty())
return;
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
for (auto& triangle : triangles)
{
for (ezUInt32 i = 0; i < 3; ++i)
{
auto& vertex = data.m_triangleVertices.ExpandAndGetRef();
vertex.m_position = triangle.m_position[i];
vertex.m_color = color;
}
}
}
void ezDebugRenderer::DrawTexturedTriangles(const ezDebugRendererContext& context, ezArrayPtr<TexturedTriangle> triangles, const ezColor& color, const ezTexture2DResourceHandle& hTexture)
{
if (triangles.IsEmpty())
return;
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context).m_texTriangle3DVertices[hTexture];
for (auto& triangle : triangles)
{
for (ezUInt32 i = 0; i < 3; ++i)
{
auto& vertex = data.ExpandAndGetRef();
vertex.m_position = triangle.m_position[i];
vertex.m_texCoord = triangle.m_texcoord[i];
vertex.m_color = color;
}
}
}
void ezDebugRenderer::Draw2DRectangle(const ezDebugRendererContext& context, const ezRectFloat& rectInPixel, float fDepth, const ezColor& color)
{
Vertex vertices[6];
vertices[0].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth);
vertices[1].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth);
vertices[2].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Bottom(), fDepth);
vertices[3].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth);
vertices[4].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Top(), fDepth);
vertices[5].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth);
for (ezUInt32 i = 0; i < EZ_ARRAY_SIZE(vertices); ++i)
{
vertices[i].m_color = color;
}
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
data.m_triangle2DVertices.PushBackRange(ezMakeArrayPtr(vertices));
}
void ezDebugRenderer::Draw2DRectangle(const ezDebugRendererContext& context, const ezRectFloat& rectInPixel, float fDepth, const ezColor& color, const ezTexture2DResourceHandle& hTexture)
{
TexVertex vertices[6];
vertices[0].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth);
vertices[0].m_texCoord = ezVec2(0, 0);
vertices[1].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth);
vertices[1].m_texCoord = ezVec2(1, 1);
vertices[2].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Bottom(), fDepth);
vertices[2].m_texCoord = ezVec2(0, 1);
vertices[3].m_position = ezVec3(rectInPixel.Left(), rectInPixel.Top(), fDepth);
vertices[3].m_texCoord = ezVec2(0, 0);
vertices[4].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Top(), fDepth);
vertices[4].m_texCoord = ezVec2(1, 0);
vertices[5].m_position = ezVec3(rectInPixel.Right(), rectInPixel.Bottom(), fDepth);
vertices[5].m_texCoord = ezVec2(1, 1);
for (ezUInt32 i = 0; i < EZ_ARRAY_SIZE(vertices); ++i)
{
vertices[i].m_color = color;
}
EZ_LOCK(s_Mutex);
auto& data = GetDataForExtraction(context);
data.m_texTriangle2DVertices[hTexture].PushBackRange(ezMakeArrayPtr(vertices));
}
void ezDebugRenderer::Draw2DText(const ezDebugRendererContext& context, const ezStringView& text, const ezVec2I32& positionInPixel, const ezColor& color, ezUInt32 uiSizeInPixel /*= 16*/, HorizontalAlignment::Enum horizontalAlignment /*= HorizontalAlignment::Left*/,
VerticalAlignment::Enum verticalAlignment /*= VerticalAlignment::Top*/)
{
AddTextLines(context, text, positionInPixel, (float)uiSizeInPixel, horizontalAlignment, verticalAlignment, [=](PerContextData& data, ezStringView line, ezVec2 topLeftCorner) {
auto& textLine = data.m_textLines2D.ExpandAndGetRef();
textLine.m_text = line;
textLine.m_topLeftCorner = topLeftCorner;
textLine.m_color = color;
textLine.m_uiSizeInPixel = uiSizeInPixel;
});
}
void ezDebugRenderer::Draw3DText(const ezDebugRendererContext& context, const ezStringView& text, const ezVec3& globalPosition, const ezColor& color, ezUInt32 uiSizeInPixel /*= 16*/, HorizontalAlignment::Enum horizontalAlignment /*= HorizontalAlignment::Left*/,
VerticalAlignment::Enum verticalAlignment /*= VerticalAlignment::Top*/)
{
AddTextLines(context, text, ezVec2I32(0), (float)uiSizeInPixel, horizontalAlignment, verticalAlignment, [=](PerContextData& data, ezStringView line, ezVec2 topLeftCorner) {
auto& textLine = data.m_textLines3D.ExpandAndGetRef();
textLine.m_text = line;
textLine.m_topLeftCorner = topLeftCorner;
textLine.m_color = color;
textLine.m_uiSizeInPixel = uiSizeInPixel;
textLine.m_position = globalPosition;
});
}
// static
void ezDebugRenderer::Render(const ezRenderViewContext& renderViewContext)
{
if (renderViewContext.m_pWorldDebugContext != nullptr)
{
RenderInternal(*renderViewContext.m_pWorldDebugContext, renderViewContext);
}
if (renderViewContext.m_pViewDebugContext != nullptr)
{
RenderInternal(*renderViewContext.m_pViewDebugContext, renderViewContext);
}
}
// static
void ezDebugRenderer::RenderInternal(const ezDebugRendererContext& context, const ezRenderViewContext& renderViewContext)
{
DoubleBufferedPerContextData* pDoubleBufferedContextData = nullptr;
if (!s_PerContextData.TryGetValue(context, pDoubleBufferedContextData))
{
return;
}
pDoubleBufferedContextData->m_uiLastRenderedFrame = ezRenderWorld::GetFrameCounter();
PerContextData* pData = pDoubleBufferedContextData->m_pData[ezRenderWorld::GetDataIndexForRendering()].Borrow();
if (pData == nullptr)
{
return;
}
ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice();
ezGALCommandEncoder* pGALCommandEncoder = renderViewContext.m_pRenderContext->GetCommandEncoder();
// SolidBoxes
{
ezUInt32 uiNumSolidBoxes = pData->m_solidBoxes.GetCount();
if (uiNumSolidBoxes != 0)
{
CreateDataBuffer(BufferType::SolidBoxes, sizeof(BoxData));
renderViewContext.m_pRenderContext->BindShader(s_hDebugGeometryShader);
renderViewContext.m_pRenderContext->BindBuffer("boxData", pDevice->GetDefaultResourceView(s_hDataBuffer[BufferType::SolidBoxes]));
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hSolidBoxMeshBuffer);
const BoxData* pSolidBoxData = pData->m_solidBoxes.GetData();
while (uiNumSolidBoxes > 0)
{
const ezUInt32 uiNumSolidBoxesInBatch = ezMath::Min<ezUInt32>(uiNumSolidBoxes, BOXES_PER_BATCH);
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::SolidBoxes], 0, ezMakeArrayPtr(pSolidBoxData, uiNumSolidBoxesInBatch).ToByteArray());
unsigned int uiRenderedInstances = uiNumSolidBoxesInBatch;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumSolidBoxes -= uiNumSolidBoxesInBatch;
pSolidBoxData += BOXES_PER_BATCH;
}
}
}
// Triangles
{
ezUInt32 uiNumTriangleVertices = pData->m_triangleVertices.GetCount();
if (uiNumTriangleVertices != 0)
{
CreateVertexBuffer(BufferType::Triangles3D, sizeof(Vertex));
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "FALSE");
renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader);
const Vertex* pTriangleData = pData->m_triangleVertices.GetData();
while (uiNumTriangleVertices > 0)
{
const ezUInt32 uiNumTriangleVerticesInBatch = ezMath::Min<ezUInt32>(uiNumTriangleVertices, TRIANGLE_VERTICES_PER_BATCH);
EZ_ASSERT_DEV(uiNumTriangleVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3.");
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Triangles3D], 0, ezMakeArrayPtr(pTriangleData, uiNumTriangleVerticesInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Triangles3D], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNumTriangleVerticesInBatch / 3);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumTriangleVertices -= uiNumTriangleVerticesInBatch;
pTriangleData += TRIANGLE_VERTICES_PER_BATCH;
}
}
}
// 3D Lines
{
ezUInt32 uiNumLineVertices = pData->m_lineVertices.GetCount();
if (uiNumLineVertices != 0)
{
CreateVertexBuffer(BufferType::Lines, sizeof(Vertex));
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "FALSE");
renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader);
const Vertex* pLineData = pData->m_lineVertices.GetData();
while (uiNumLineVertices > 0)
{
const ezUInt32 uiNumLineVerticesInBatch = ezMath::Min<ezUInt32>(uiNumLineVertices, LINE_VERTICES_PER_BATCH);
EZ_ASSERT_DEV(uiNumLineVerticesInBatch % 2 == 0, "Vertex count must be a multiple of 2.");
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Lines], 0, ezMakeArrayPtr(pLineData, uiNumLineVerticesInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Lines], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Lines, uiNumLineVerticesInBatch / 2);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumLineVertices -= uiNumLineVerticesInBatch;
pLineData += LINE_VERTICES_PER_BATCH;
}
}
}
// 2D Lines
{
ezUInt32 uiNumLineVertices = pData->m_line2DVertices.GetCount();
if (uiNumLineVertices != 0)
{
CreateVertexBuffer(BufferType::Lines2D, sizeof(Vertex));
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "TRUE");
renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader);
const Vertex* pLineData = pData->m_line2DVertices.GetData();
while (uiNumLineVertices > 0)
{
const ezUInt32 uiNumLineVerticesInBatch = ezMath::Min<ezUInt32>(uiNumLineVertices, LINE_VERTICES_PER_BATCH);
EZ_ASSERT_DEV(uiNumLineVerticesInBatch % 2 == 0, "Vertex count must be a multiple of 2.");
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Lines2D], 0, ezMakeArrayPtr(pLineData, uiNumLineVerticesInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Lines2D], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Lines, uiNumLineVerticesInBatch / 2);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumLineVertices -= uiNumLineVerticesInBatch;
pLineData += LINE_VERTICES_PER_BATCH;
}
}
}
// LineBoxes
{
ezUInt32 uiNumLineBoxes = pData->m_lineBoxes.GetCount();
if (uiNumLineBoxes != 0)
{
CreateDataBuffer(BufferType::LineBoxes, sizeof(BoxData));
renderViewContext.m_pRenderContext->BindShader(s_hDebugGeometryShader);
renderViewContext.m_pRenderContext->BindBuffer("boxData", pDevice->GetDefaultResourceView(s_hDataBuffer[BufferType::LineBoxes]));
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hLineBoxMeshBuffer);
const BoxData* pLineBoxData = pData->m_lineBoxes.GetData();
while (uiNumLineBoxes > 0)
{
const ezUInt32 uiNumLineBoxesInBatch = ezMath::Min<ezUInt32>(uiNumLineBoxes, BOXES_PER_BATCH);
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::LineBoxes], 0, ezMakeArrayPtr(pLineBoxData, uiNumLineBoxesInBatch).ToByteArray());
unsigned int uiRenderedInstances = uiNumLineBoxesInBatch;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumLineBoxes -= uiNumLineBoxesInBatch;
pLineBoxData += BOXES_PER_BATCH;
}
}
}
// 2D Rectangles
{
ezUInt32 uiNum2DVertices = pData->m_triangle2DVertices.GetCount();
if (uiNum2DVertices != 0)
{
CreateVertexBuffer(BufferType::Triangles2D, sizeof(Vertex));
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "TRUE");
renderViewContext.m_pRenderContext->BindShader(s_hDebugPrimitiveShader);
const Vertex* pTriangleData = pData->m_triangle2DVertices.GetData();
while (uiNum2DVertices > 0)
{
const ezUInt32 uiNum2DVerticesInBatch = ezMath::Min<ezUInt32>(uiNum2DVertices, TRIANGLE_VERTICES_PER_BATCH);
EZ_ASSERT_DEV(uiNum2DVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3.");
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Triangles2D], 0, ezMakeArrayPtr(pTriangleData, uiNum2DVerticesInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::Triangles2D], ezGALBufferHandle(), &s_VertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNum2DVerticesInBatch / 3);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNum2DVertices -= uiNum2DVerticesInBatch;
pTriangleData += TRIANGLE_VERTICES_PER_BATCH;
}
}
}
// Textured 2D triangles
{
for (auto itTex = pData->m_texTriangle2DVertices.GetIterator(); itTex.IsValid(); ++itTex)
{
renderViewContext.m_pRenderContext->BindTexture2D("BaseTexture", itTex.Key());
const auto& verts = itTex.Value();
ezUInt32 uiNum2DVertices = verts.GetCount();
if (uiNum2DVertices != 0)
{
CreateVertexBuffer(BufferType::TexTriangles2D, sizeof(TexVertex));
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "TRUE");
renderViewContext.m_pRenderContext->BindShader(s_hDebugTexturedPrimitiveShader);
const TexVertex* pTriangleData = verts.GetData();
while (uiNum2DVertices > 0)
{
const ezUInt32 uiNum2DVerticesInBatch = ezMath::Min<ezUInt32>(uiNum2DVertices, TEX_TRIANGLE_VERTICES_PER_BATCH);
EZ_ASSERT_DEV(uiNum2DVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3.");
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::TexTriangles2D], 0, ezMakeArrayPtr(pTriangleData, uiNum2DVerticesInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::TexTriangles2D], ezGALBufferHandle(), &s_TexVertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNum2DVerticesInBatch / 3);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNum2DVertices -= uiNum2DVerticesInBatch;
pTriangleData += TEX_TRIANGLE_VERTICES_PER_BATCH;
}
}
}
}
// Textured 3D triangles
{
for (auto itTex = pData->m_texTriangle3DVertices.GetIterator(); itTex.IsValid(); ++itTex)
{
renderViewContext.m_pRenderContext->BindTexture2D("BaseTexture", itTex.Key());
const auto& verts = itTex.Value();
ezUInt32 uiNumVertices = verts.GetCount();
if (uiNumVertices != 0)
{
CreateVertexBuffer(BufferType::TexTriangles3D, sizeof(TexVertex));
renderViewContext.m_pRenderContext->SetShaderPermutationVariable("PRE_TRANSFORMED_VERTICES", "FALSE");
renderViewContext.m_pRenderContext->BindShader(s_hDebugTexturedPrimitiveShader);
const TexVertex* pTriangleData = verts.GetData();
while (uiNumVertices > 0)
{
const ezUInt32 uiNumVerticesInBatch = ezMath::Min<ezUInt32>(uiNumVertices, TEX_TRIANGLE_VERTICES_PER_BATCH);
EZ_ASSERT_DEV(uiNumVerticesInBatch % 3 == 0, "Vertex count must be a multiple of 3.");
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::TexTriangles3D], 0, ezMakeArrayPtr(pTriangleData, uiNumVerticesInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(s_hDataBuffer[BufferType::TexTriangles3D], ezGALBufferHandle(), &s_TexVertexDeclarationInfo, ezGALPrimitiveTopology::Triangles, uiNumVerticesInBatch / 3);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumVertices -= uiNumVerticesInBatch;
pTriangleData += TEX_TRIANGLE_VERTICES_PER_BATCH;
}
}
}
}
// Text
{
pData->m_glyphs.Clear();
for (auto& textLine : pData->m_textLines3D)
{
ezVec3 screenPos;
if (renderViewContext.m_pViewData->ComputeScreenSpacePos(textLine.m_position, screenPos).Succeeded() && screenPos.z > 0.0f)
{
textLine.m_topLeftCorner.x += ezMath::Round(screenPos.x);
textLine.m_topLeftCorner.y += ezMath::Round(screenPos.y);
AppendGlyphs(pData->m_glyphs, textLine);
}
}
for (auto& textLine : pData->m_textLines2D)
{
AppendGlyphs(pData->m_glyphs, textLine);
}
ezUInt32 uiNumGlyphs = pData->m_glyphs.GetCount();
if (uiNumGlyphs != 0)
{
CreateDataBuffer(BufferType::Glyphs, sizeof(GlyphData));
renderViewContext.m_pRenderContext->BindShader(s_hDebugTextShader);
renderViewContext.m_pRenderContext->BindBuffer("glyphData", pDevice->GetDefaultResourceView(s_hDataBuffer[BufferType::Glyphs]));
renderViewContext.m_pRenderContext->BindTexture2D("FontTexture", s_hDebugFontTexture);
const GlyphData* pGlyphData = pData->m_glyphs.GetData();
while (uiNumGlyphs > 0)
{
const ezUInt32 uiNumGlyphsInBatch = ezMath::Min<ezUInt32>(uiNumGlyphs, GLYPHS_PER_BATCH);
pGALCommandEncoder->UpdateBuffer(s_hDataBuffer[BufferType::Glyphs], 0, ezMakeArrayPtr(pGlyphData, uiNumGlyphsInBatch).ToByteArray());
renderViewContext.m_pRenderContext->BindMeshBuffer(ezGALBufferHandle(), ezGALBufferHandle(), nullptr, ezGALPrimitiveTopology::Triangles, uiNumGlyphsInBatch * 2);
unsigned int uiRenderedInstances = 1;
if (renderViewContext.m_pCamera->IsStereoscopic())
uiRenderedInstances *= 2;
renderViewContext.m_pRenderContext->DrawMeshBuffer(0xFFFFFFFF, 0, uiRenderedInstances).IgnoreResult();
uiNumGlyphs -= uiNumGlyphsInBatch;
pGlyphData += GLYPHS_PER_BATCH;
}
}
}
}
void ezDebugRenderer::OnEngineStartup()
{
{
ezGeometry geom;
geom.AddLineBox(ezVec3(2.0f), ezColor::White);
ezMeshBufferResourceDescriptor desc;
desc.AddStream(ezGALVertexAttributeSemantic::Position, ezGALResourceFormat::XYZFloat);
desc.AllocateStreamsFromGeometry(geom, ezGALPrimitiveTopology::Lines);
s_hLineBoxMeshBuffer = ezResourceManager::CreateResource<ezMeshBufferResource>("DebugLineBox", std::move(desc), "Mesh for Rendering Debug Line Boxes");
}
{
ezGeometry geom;
geom.AddBox(ezVec3(2.0f), ezColor::White);
ezMeshBufferResourceDescriptor desc;
desc.AddStream(ezGALVertexAttributeSemantic::Position, ezGALResourceFormat::XYZFloat);
desc.AllocateStreamsFromGeometry(geom, ezGALPrimitiveTopology::Triangles);
s_hSolidBoxMeshBuffer = ezResourceManager::CreateResource<ezMeshBufferResource>("DebugSolidBox", std::move(desc), "Mesh for Rendering Debug Solid Boxes");
}
{
// reset, if already used before
s_VertexDeclarationInfo.m_VertexStreams.Clear();
{
ezVertexStreamInfo& si = s_VertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef();
si.m_Semantic = ezGALVertexAttributeSemantic::Position;
si.m_Format = ezGALResourceFormat::XYZFloat;
si.m_uiOffset = 0;
si.m_uiElementSize = 12;
}
{
ezVertexStreamInfo& si = s_VertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef();
si.m_Semantic = ezGALVertexAttributeSemantic::Color0;
si.m_Format = ezGALResourceFormat::RGBAUByteNormalized;
si.m_uiOffset = 12;
si.m_uiElementSize = 4;
}
}
{
// reset, if already used before
s_TexVertexDeclarationInfo.m_VertexStreams.Clear();
{
ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef();
si.m_Semantic = ezGALVertexAttributeSemantic::Position;
si.m_Format = ezGALResourceFormat::XYZFloat;
si.m_uiOffset = 0;
si.m_uiElementSize = 12;
}
{
ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef();
si.m_Semantic = ezGALVertexAttributeSemantic::Color0;
si.m_Format = ezGALResourceFormat::RGBAUByteNormalized;
si.m_uiOffset = 12;
si.m_uiElementSize = 4;
}
{
ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef();
si.m_Semantic = ezGALVertexAttributeSemantic::TexCoord0;
si.m_Format = ezGALResourceFormat::XYFloat;
si.m_uiOffset = 16;
si.m_uiElementSize = 8;
}
{
ezVertexStreamInfo& si = s_TexVertexDeclarationInfo.m_VertexStreams.ExpandAndGetRef();
si.m_Semantic = ezGALVertexAttributeSemantic::TexCoord1; // padding
si.m_Format = ezGALResourceFormat::XYFloat;
si.m_uiOffset = 24;
si.m_uiElementSize = 8;
}
}
{
ezImage debugFontImage;
ezGraphicsUtils::CreateSimpleASCIIFontTexture(debugFontImage);
ezGALSystemMemoryDescription memoryDesc;
memoryDesc.m_pData = debugFontImage.GetPixelPointer<ezUInt8>();
memoryDesc.m_uiRowPitch = static_cast<ezUInt32>(debugFontImage.GetRowPitch());
memoryDesc.m_uiSlicePitch = static_cast<ezUInt32>(debugFontImage.GetDepthPitch());
ezTexture2DResourceDescriptor desc;
desc.m_DescGAL.m_uiWidth = debugFontImage.GetWidth();
desc.m_DescGAL.m_uiHeight = debugFontImage.GetHeight();
desc.m_DescGAL.m_Format = ezGALResourceFormat::RGBAUByteNormalized;
desc.m_InitialContent = ezMakeArrayPtr(&memoryDesc, 1);
s_hDebugFontTexture = ezResourceManager::CreateResource<ezTexture2DResource>("DebugFontTexture", std::move(desc));
}
s_hDebugGeometryShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugGeometry.ezShader");
s_hDebugPrimitiveShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugPrimitive.ezShader");
s_hDebugTexturedPrimitiveShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugTexturedPrimitive.ezShader");
s_hDebugTextShader = ezResourceManager::LoadResource<ezShaderResource>("Shaders/Debug/DebugText.ezShader");
ezRenderWorld::GetRenderEvent().AddEventHandler(&OnRenderEvent);
}
void ezDebugRenderer::OnEngineShutdown()
{
ezRenderWorld::GetRenderEvent().RemoveEventHandler(&OnRenderEvent);
for (ezUInt32 i = 0; i < BufferType::Count; ++i)
{
DestroyBuffer(static_cast<BufferType::Enum>(i));
}
s_hLineBoxMeshBuffer.Invalidate();
s_hSolidBoxMeshBuffer.Invalidate();
s_hDebugFontTexture.Invalidate();
s_hDebugGeometryShader.Invalidate();
s_hDebugPrimitiveShader.Invalidate();
s_hDebugTexturedPrimitiveShader.Invalidate();
s_hDebugTextShader.Invalidate();
s_PerContextData.Clear();
}
EZ_STATICLINK_FILE(RendererCore, RendererCore_Debug_Implementation_DebugRenderer);
| 49,241 | 17,618 |
#include "mpc_local_planner/AcadosSolver.h"
#include <ros/ros.h>
namespace mpc {
namespace Acados {
void Solver::reInit(const State &state) {
freeAllocated();
init();
setInitGuess(state);
return;
}
void Solver::setInitCondition(const State &state) {
// initial condition
auto x0 = state.toArray();
std::vector<int> idxbx0(x0.size());
// int idxbx0[x0.size()];
for (int i = 0; i < x0.size(); i++) {
idxbx0[i] = i;
}
ocp_nlp_constraints_model_set(config_, dims_, in_, 0, "idxbx", &idxbx0[0]);
ocp_nlp_constraints_model_set(config_, dims_, in_, 0, "lbx", &x0[0]);
ocp_nlp_constraints_model_set(config_, dims_, in_, 0, "ubx", &x0[0]);
}
MPCReturn Solver::solve(const State &state, const Params ¶ms) {
auto start = std::chrono::high_resolution_clock::now();
int N = dims_->N;
setInitCondition(state);
setParams(params);
// prepare evaluation
int NTIMINGS = 1;
std::vector<double> xtraj(nx_ * (N + 1));
std::vector<double> utraj(nx_ * (N));
// solve ocp in loop
int rti_phase = 0;
int status;
for (int ii = 0; ii < NTIMINGS; ii++) {
ocp_nlp_solver_opts_set(config_, opts_, "rti_phase", &rti_phase);
status = acadosSolve();
}
// get the solution
for (int ii = 0; ii <= dims_->N; ii++)
ocp_nlp_out_get(config_, dims_, out_, ii, "x", &xtraj[ii * nx_]);
for (int ii = 0; ii < dims_->N; ii++)
ocp_nlp_out_get(config_, dims_, out_, ii, "u", &utraj[ii * nu_]);
if (status != ACADOS_SUCCESS) {
ROS_ERROR("acados_solve() failed with status %d.\n", status);
reInit(state);
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
MPCReturn ret;
ret.mpcHorizon.resize(N);
for (int i = 0; i < N; i++) {
State state(&xtraj[nx_ * i], nx_);
Input input(&utraj[nu_ * i], nu_);
ret.mpcHorizon.at(i) = OptVariables{state, input};
}
ret.u0 = ret.mpcHorizon.at(0).u;
ret.cost = -1;
ret.success = status == ACADOS_SUCCESS;
ret.computeTime = duration.count();
return ret;
}
void Solver::setInitGuess(const State &state) {
auto x_init = state.toArray();
assert(x_init.size() == nx_);
// initial value for control input
std::vector<double> u0(nu_);
for (int i = 0; i < nu_; i++) {
u0[0] = 0;
}
// initialize solution
for (int i = 0; i <= dims_->N; i++) {
ocp_nlp_out_set(config_, dims_, out_, i, "x", &x_init[0]);
ocp_nlp_out_set(config_, dims_, out_, i, "u", &u0[0]);
}
}
} // namespace Acados
} // namespace mpc | 2,697 | 1,079 |
#include "zeek/analyzer/protocol/pia/PIA.h"
#include "zeek/DebugLogger.h"
#include "zeek/Event.h"
#include "zeek/IP.h"
#include "zeek/NetVar.h"
#include "zeek/Reporter.h"
#include "zeek/RuleMatcher.h"
#include "zeek/RunState.h"
#include "zeek/analyzer/protocol/tcp/TCP_Flags.h"
#include "zeek/analyzer/protocol/tcp/TCP_Reassembler.h"
namespace zeek::analyzer::pia
{
PIA::PIA(analyzer::Analyzer* arg_as_analyzer)
: state(INIT), as_analyzer(arg_as_analyzer), conn(), current_packet()
{
}
PIA::~PIA()
{
ClearBuffer(&pkt_buffer);
}
void PIA::ClearBuffer(Buffer* buffer)
{
DataBlock* next = nullptr;
for ( DataBlock* b = buffer->head; b; b = next )
{
next = b->next;
delete b->ip;
delete[] b->data;
delete b;
}
buffer->head = buffer->tail = nullptr;
buffer->size = 0;
}
void PIA::AddToBuffer(Buffer* buffer, uint64_t seq, int len, const u_char* data, bool is_orig,
const IP_Hdr* ip)
{
u_char* tmp = nullptr;
if ( data )
{
tmp = new u_char[len];
memcpy(tmp, data, len);
}
DataBlock* b = new DataBlock;
b->ip = ip ? ip->Copy() : nullptr;
b->data = tmp;
b->is_orig = is_orig;
b->len = len;
b->seq = seq;
b->next = nullptr;
if ( buffer->tail )
{
buffer->tail->next = b;
buffer->tail = b;
}
else
buffer->head = buffer->tail = b;
if ( data )
buffer->size += len;
}
void PIA::AddToBuffer(Buffer* buffer, int len, const u_char* data, bool is_orig, const IP_Hdr* ip)
{
AddToBuffer(buffer, -1, len, data, is_orig, ip);
}
void PIA::ReplayPacketBuffer(analyzer::Analyzer* analyzer)
{
DBG_LOG(DBG_ANALYZER, "PIA replaying %d total packet bytes", pkt_buffer.size);
for ( DataBlock* b = pkt_buffer.head; b; b = b->next )
analyzer->DeliverPacket(b->len, b->data, b->is_orig, -1, b->ip, 0);
}
void PIA::PIA_Done()
{
FinishEndpointMatcher();
}
void PIA::PIA_DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq,
const IP_Hdr* ip, int caplen, bool clear_state)
{
if ( pkt_buffer.state == SKIPPING )
return;
current_packet.data = data;
current_packet.len = len;
current_packet.seq = seq;
current_packet.is_orig = is_orig;
State new_state = pkt_buffer.state;
if ( pkt_buffer.state == INIT )
new_state = BUFFERING;
if ( (pkt_buffer.state == BUFFERING || new_state == BUFFERING) && len > 0 )
{
AddToBuffer(&pkt_buffer, seq, len, data, is_orig, ip);
if ( pkt_buffer.size > zeek::detail::dpd_buffer_size )
new_state = zeek::detail::dpd_match_only_beginning ? SKIPPING : MATCHING_ONLY;
}
// FIXME: I'm not sure why it does not work with eol=true...
DoMatch(data, len, is_orig, true, false, false, ip);
if ( clear_state )
zeek::detail::RuleMatcherState::ClearMatchState(is_orig);
pkt_buffer.state = new_state;
current_packet.data = nullptr;
}
void PIA::Match(zeek::detail::Rule::PatternType type, const u_char* data, int len, bool is_orig,
bool bol, bool eol, bool clear_state)
{
if ( ! MatcherInitialized(is_orig) )
InitEndpointMatcher(AsAnalyzer(), nullptr, 0, is_orig, this);
zeek::detail::RuleMatcherState::Match(type, data, len, is_orig, bol, eol, clear_state);
}
void PIA::DoMatch(const u_char* data, int len, bool is_orig, bool bol, bool eol, bool clear_state,
const IP_Hdr* ip)
{
if ( ! zeek::detail::rule_matcher )
return;
if ( ! zeek::detail::rule_matcher->HasNonFileMagicRule() )
return;
if ( ! MatcherInitialized(is_orig) )
InitEndpointMatcher(AsAnalyzer(), ip, len, is_orig, this);
zeek::detail::RuleMatcherState::Match(zeek::detail::Rule::PAYLOAD, data, len, is_orig, bol, eol,
clear_state);
}
void PIA_UDP::ActivateAnalyzer(analyzer::Tag tag, const zeek::detail::Rule* rule)
{
if ( pkt_buffer.state == MATCHING_ONLY )
{
DBG_LOG(DBG_ANALYZER, "analyzer found but buffer already exceeded");
// FIXME: This is where to check whether an analyzer
// supports partial connections once we get such.
if ( protocol_late_match )
{
// Queue late match event
if ( ! tag )
tag = GetAnalyzerTag();
const auto& tval = tag.AsVal();
event_mgr.Enqueue(protocol_late_match, ConnVal(), tval);
}
pkt_buffer.state = zeek::detail::dpd_late_match_stop ? SKIPPING : MATCHING_ONLY;
return;
}
if ( Parent()->HasChildAnalyzer(tag) )
return;
analyzer::Analyzer* a = Parent()->AddChildAnalyzer(tag);
if ( ! a )
return;
a->SetSignature(rule);
ReplayPacketBuffer(a);
}
void PIA_UDP::DeactivateAnalyzer(analyzer::Tag tag)
{
reporter->InternalError("PIA_UDP::Deact not implemented yet");
}
//// TCP PIA
PIA_TCP::~PIA_TCP()
{
ClearBuffer(&stream_buffer);
}
void PIA_TCP::Init()
{
analyzer::tcp::TCP_ApplicationAnalyzer::Init();
if ( Parent()->IsAnalyzer("TCP") )
{
auto* tcp = static_cast<packet_analysis::TCP::TCPSessionAdapter*>(Parent());
SetTCP(tcp);
tcp->SetPIA(this);
}
}
void PIA_TCP::FirstPacket(bool is_orig, const IP_Hdr* ip)
{
static char dummy_packet[sizeof(struct ip) + sizeof(struct tcphdr)];
static struct ip* ip4 = nullptr;
static struct tcphdr* tcp4 = nullptr;
static IP_Hdr* ip4_hdr = nullptr;
DBG_LOG(DBG_ANALYZER, "PIA_TCP[%d] FirstPacket(%s)", GetID(), (is_orig ? "T" : "F"));
if ( ! ip )
{
// Create a dummy packet. Not very elegant, but everything
// else would be *really* ugly ...
if ( ! ip4_hdr )
{
ip4 = (struct ip*)dummy_packet;
tcp4 = (struct tcphdr*)(dummy_packet + sizeof(struct ip));
ip4->ip_len = sizeof(struct ip) + sizeof(struct tcphdr);
ip4->ip_hl = sizeof(struct ip) >> 2;
ip4->ip_p = IPPROTO_TCP;
// Cast to const so that it doesn't delete it.
ip4_hdr = new IP_Hdr(ip4, false);
}
// Locals used to avoid potentil alignment problems
// with some archs/compilers when grabbing the address
// of the struct member directly in the following.
in_addr tmp_src;
in_addr tmp_dst;
if ( is_orig )
{
Conn()->OrigAddr().CopyIPv4(&tmp_src);
Conn()->RespAddr().CopyIPv4(&tmp_dst);
tcp4->th_sport = htons(Conn()->OrigPort());
tcp4->th_dport = htons(Conn()->RespPort());
}
else
{
Conn()->RespAddr().CopyIPv4(&tmp_src);
Conn()->OrigAddr().CopyIPv4(&tmp_dst);
tcp4->th_sport = htons(Conn()->RespPort());
tcp4->th_dport = htons(Conn()->OrigPort());
}
ip4->ip_src = tmp_src;
ip4->ip_dst = tmp_dst;
ip = ip4_hdr;
}
if ( ! MatcherInitialized(is_orig) )
DoMatch((const u_char*)"", 0, is_orig, true, false, false, ip);
}
void PIA_TCP::DeliverStream(int len, const u_char* data, bool is_orig)
{
analyzer::tcp::TCP_ApplicationAnalyzer::DeliverStream(len, data, is_orig);
if ( stream_buffer.state == SKIPPING )
return;
stream_mode = true;
State new_state = stream_buffer.state;
if ( stream_buffer.state == INIT )
{
// FIXME: clear payload-matching state here...
new_state = BUFFERING;
}
if ( stream_buffer.state == BUFFERING || new_state == BUFFERING )
{
AddToBuffer(&stream_buffer, len, data, is_orig);
if ( stream_buffer.size > zeek::detail::dpd_buffer_size )
new_state = zeek::detail::dpd_match_only_beginning ? SKIPPING : MATCHING_ONLY;
}
DoMatch(data, len, is_orig, false, false, false, nullptr);
stream_buffer.state = new_state;
}
void PIA_TCP::Undelivered(uint64_t seq, int len, bool is_orig)
{
analyzer::tcp::TCP_ApplicationAnalyzer::Undelivered(seq, len, is_orig);
if ( stream_buffer.state == BUFFERING )
// We use data=nil to mark an undelivered.
AddToBuffer(&stream_buffer, seq, len, nullptr, is_orig);
// No check for buffer overrun here. I think that's ok.
}
void PIA_TCP::ActivateAnalyzer(analyzer::Tag tag, const zeek::detail::Rule* rule)
{
if ( stream_buffer.state == MATCHING_ONLY )
{
DBG_LOG(DBG_ANALYZER, "analyzer found but buffer already exceeded");
// FIXME: This is where to check whether an analyzer supports
// partial connections once we get such.
if ( protocol_late_match )
{
// Queue late match event
if ( ! tag )
tag = GetAnalyzerTag();
const auto& tval = tag.AsVal();
event_mgr.Enqueue(protocol_late_match, ConnVal(), tval);
}
stream_buffer.state = zeek::detail::dpd_late_match_stop ? SKIPPING : MATCHING_ONLY;
return;
}
analyzer::Analyzer* a = Parent()->AddChildAnalyzer(tag);
if ( ! a )
return;
a->SetSignature(rule);
// We have two cases here:
//
// (a) We have already got stream input.
// => Great, somebody's already reassembling and we can just
// replay our stream buffer to the new analyzer.
if ( stream_mode )
{
ReplayStreamBuffer(a);
return;
}
// (b) We have only got packet input so far (or none at all).
// => We have to switch from packet-mode to stream-mode.
//
// Here's what we do:
//
// (1) We create new tcp::TCP_Reassemblers and feed them the buffered
// packets.
//
// (2) The reassembler will give us their results via the
// stream-interface and we buffer it as usual.
//
// (3) We replay the now-filled stream-buffer to the analyzer.
//
// (4) We hand the two reassemblers to the TCP Analyzer (our parent),
// turning reassembly now on for all subsequent data.
DBG_LOG(DBG_ANALYZER, "PIA_TCP switching from packet-mode to stream-mode");
stream_mode = true;
// FIXME: The reassembler will query the endpoint for state. Not sure
// if this is works in all cases...
if ( ! Parent()->IsAnalyzer("TCP") )
{
// Our parent is not the TCP analyzer, which can only mean
// we have been inserted somewhere further down in the
// analyzer tree. In this case, we will never have seen
// any input at this point (because we don't get packets).
assert(! pkt_buffer.head);
assert(! stream_buffer.head);
return;
}
auto* tcp = static_cast<packet_analysis::TCP::TCPSessionAdapter*>(Parent());
auto* reass_orig =
new tcp::TCP_Reassembler(this, tcp, tcp::TCP_Reassembler::Direct, tcp->Orig());
auto* reass_resp =
new tcp::TCP_Reassembler(this, tcp, tcp::TCP_Reassembler::Direct, tcp->Resp());
uint64_t orig_seq = 0;
uint64_t resp_seq = 0;
for ( DataBlock* b = pkt_buffer.head; b; b = b->next )
{
// We don't have the TCP flags here during replay. We could
// funnel them through, but it's non-trivial and doesn't seem
// worth the effort.
if ( b->is_orig )
reass_orig->DataSent(run_state::network_time, orig_seq = b->seq, b->len, b->data,
tcp::TCP_Flags(), true);
else
reass_resp->DataSent(run_state::network_time, resp_seq = b->seq, b->len, b->data,
tcp::TCP_Flags(), true);
}
// We also need to pass the current packet on.
DataBlock* current = CurrentPacket();
if ( current->data )
{
if ( current->is_orig )
reass_orig->DataSent(run_state::network_time, orig_seq = current->seq, current->len,
current->data, analyzer::tcp::TCP_Flags(), true);
else
reass_resp->DataSent(run_state::network_time, resp_seq = current->seq, current->len,
current->data, analyzer::tcp::TCP_Flags(), true);
}
ClearBuffer(&pkt_buffer);
ReplayStreamBuffer(a);
reass_orig->AckReceived(orig_seq);
reass_resp->AckReceived(resp_seq);
reass_orig->SetType(tcp::TCP_Reassembler::Forward);
reass_resp->SetType(tcp::TCP_Reassembler::Forward);
tcp->SetReassembler(reass_orig, reass_resp);
}
void PIA_TCP::DeactivateAnalyzer(analyzer::Tag tag)
{
reporter->InternalError("PIA_TCP::Deact not implemented yet");
}
void PIA_TCP::ReplayStreamBuffer(analyzer::Analyzer* analyzer)
{
DBG_LOG(DBG_ANALYZER, "PIA_TCP replaying %d total stream bytes", stream_buffer.size);
for ( DataBlock* b = stream_buffer.head; b; b = b->next )
{
if ( b->data )
analyzer->NextStream(b->len, b->data, b->is_orig);
else
analyzer->NextUndelivered(b->seq, b->len, b->is_orig);
}
}
} // namespace zeek::analyzer::pia
| 11,816 | 4,834 |
/*
* Copyright (c) 2009 Carnegie Mellon University.
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef OBJECT_REQUEST_ISSUE_HPP
#define OBJECT_REQUEST_ISSUE_HPP
#include <sstream>
#include <iostream>
#include <string>
#include <graphlab/serialization/serialization_includes.hpp>
#include <graphlab/rpc/dc_types.hpp>
#include <graphlab/rpc/dc_internal_types.hpp>
#include <graphlab/rpc/reply_increment_counter.hpp>
#include <graphlab/rpc/object_request_dispatch.hpp>
#include <graphlab/rpc/function_ret_type.hpp>
#include <graphlab/rpc/mem_function_arg_types_def.hpp>
#include <graphlab/rpc/request_future.hpp>
#include <graphlab/rpc/archive_memory_pool.hpp>
#include <graphlab/rpc/dc_compile_parameters.hpp>
#include <boost/preprocessor.hpp>
namespace graphlab {
namespace dc_impl {
#define GENARGS(Z,N,_) BOOST_PP_CAT(const T, N) BOOST_PP_CAT(&i, N)
#define GENT(Z,N,_) BOOST_PP_CAT(T, N)
#define GENARC(Z,N,_) arc << BOOST_PP_CAT(i, N);
/**
\internal
\ingroup rpc
\file object_request_issue.hpp
This is an internal function and should not be used directly
This is the marshall function for the an object member function call.
This is very similar to the standard function request issue in request_issue.hpp
, with the only difference that an object id has to be transmitted
An annoyingly long sequence of type manipulations are needed to identify the return type.
\code
template<typename T,
typename F ,
typename T0> class object_request_issue1
{
public:
static request_future<typename function_ret_type<
typename boost::remove_const<
typename boost::remove_reference<
typename boost::function<
typename boost::remove_member_pointer<F>
::type>::result_type>::type>::type>::type (void)>
exec(dc_send* sender, unsigned char flags, procid_t target,size_t objid, F remote_function , const T0 &i0 )
{
oarchive arc;
arc.advance(sizeof(packet_hdr));
reply_ret_type reply(1);
dispatch_type d = dc_impl::OBJECT_NONINTRUSIVE_REQUESTDISPATCH1<distributed_control,T,F , T0 >;
arc << reinterpret_cast<size_t>(d);
serialize(arc, (char*)(&remote_function), sizeof(remote_function));
arc << objid;
arc << reinterpret_cast<size_t>(reply.reply.get());
arc << i0;
sender->send_data(target, flags, arc.buf, arc.off);
reply.wait();
iarchive iarc(reply.val.c, reply.val.len);
typename function_ret_type<
typename boost::remove_const<
typename boost::remove_reference<
typename boost::function<
typename boost::remove_member_pointer<F>
::type>::result_type>::type>::type>::type result;
iarc >> result;
reply.val.free();
return result;
}
};
\endcode
*/
#define REMOTE_REQUEST_ISSUE_GENERATOR(Z,N,FNAME_AND_CALL) \
template<typename T,typename F BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM_PARAMS(N, typename T)> \
class BOOST_PP_CAT(FNAME_AND_CALL, N) { \
public: \
static request_future<__GLRPC_FRESULT> exec(dc_dist_object_base* rmi, dc_send* sender, unsigned char flags, procid_t target,size_t objid, F remote_function BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM(N,GENARGS ,_) ) { \
oarchive* ptr = oarchive_from_pool(); \
oarchive& arc = *ptr; \
arc.advance(sizeof(size_t) + sizeof(packet_hdr)); \
request_future<__GLRPC_FRESULT> reply; \
dispatch_type d = BOOST_PP_CAT(dc_impl::OBJECT_NONINTRUSIVE_REQUESTDISPATCH,N)<distributed_control,T,F BOOST_PP_COMMA_IF(N) BOOST_PP_ENUM(N, GENT ,_) >; \
arc << reinterpret_cast<size_t>(d); \
serialize(arc, (char*)(&remote_function), sizeof(remote_function)); \
arc << objid; \
arc << reinterpret_cast<size_t>(reply.reply.get()); \
BOOST_PP_REPEAT(N, GENARC, _) \
if (arc.off >= BUFFER_RELINQUISH_LIMIT) { \
sender->send_data(target,flags , arc.buf, arc.off); \
arc.buf = NULL; arc.len = 0; \
} else { \
char* newbuf = (char*)malloc(arc.off); memcpy(newbuf, arc.buf, arc.off); \
sender->send_data(target,flags , newbuf, arc.off); \
} \
release_oarchive_to_pool(ptr); \
if ((flags & CONTROL_PACKET) == 0) \
rmi->inc_bytes_sent(target, arc.off - sizeof(size_t)); \
return reply; \
}\
};
BOOST_PP_REPEAT(6, REMOTE_REQUEST_ISSUE_GENERATOR, object_request_issue )
#undef GENARC
#undef GENT
#undef GENARGS
#undef REMOTE_REQUEST_ISSUE_GENERATOR
} // namespace dc_impl
} // namespace graphlab
#include <graphlab/rpc/mem_function_arg_types_undef.hpp>
#endif
| 5,366 | 1,873 |
#include <jni.h>
#include <string>
#include <android/log.h>
#include "facedetectcnn.h"
#include <opencv2/opencv.hpp>
//define the buffer size. Do not change the size!
#define DETECT_BUFFER_SIZE 0x20000
using namespace cv;
extern "C" {
char *JNITag = const_cast<char *>("face-jni");
JNIEXPORT jobjectArray JNICALL
Java_com_zl_face_YSQFaceUtil_detectCNN(JNIEnv *env, jobject /* this */, jlong matAddr) {
jobjectArray faceArgs = nullptr;
Mat &img = *(Mat *) matAddr;
Mat bgr = img.clone();
cvtColor(img, bgr, COLOR_RGBA2BGR);
__android_log_print(ANDROID_LOG_INFO, JNITag, "convert RGBA to RGB");
if (bgr.empty()) {
fprintf(stderr, "Can not convert image");
return faceArgs;
}
int *pResults = NULL;
//pBuffer is used in the detection functions.
//If you call functions in multiple threads, please create one buffer for each thread!
unsigned char *pBuffer = (unsigned char *) malloc(DETECT_BUFFER_SIZE);
if (!pBuffer) {
fprintf(stderr, "Can not alloc buffer.\n");
return faceArgs;
}
///////////////////////////////////////////
// CNN face detection
// Best detection rate
//////////////////////////////////////////
//!!! The input image must be a RGB one (three-channel)
//!!! DO NOT RELEASE pResults !!!
pResults = facedetect_cnn(pBuffer, (unsigned char *) (bgr.ptr(0)), bgr.cols, bgr.rows,(int) bgr.step);
int numOfFaces = pResults ? *pResults : 0;
__android_log_print(ANDROID_LOG_INFO, JNITag, "%d faces detected.\n", numOfFaces);
/**
* 获取Face类以及其对于参数的签名
*/
jclass faceClass = env->FindClass("com/zl/face/YSQFaceInfo");//获取Face类
jmethodID faceClassInitID = (env)->GetMethodID(faceClass, "<init>", "()V");
jfieldID faceConfidence = env->GetFieldID(faceClass, "faceConfidence","I");//获取int类型参数confidence
jfieldID faceAngle = env->GetFieldID(faceClass, "faceAngle", "I");//获取int数组类型参数angle
jfieldID faceRect = env->GetFieldID(faceClass, "faceRect","Landroid/graphics/Rect;");//获取faceRect的签名
/**
* 获取RECT类以及对应参数的签名
*/
jclass rectClass = env->FindClass("android/graphics/Rect");//获取到RECT类
jmethodID rectClassInitID = (env)->GetMethodID(rectClass, "<init>", "()V");
jfieldID rect_left = env->GetFieldID(rectClass, "left", "I");//获取x的签名
jfieldID rect_top = env->GetFieldID(rectClass, "top", "I");//获取y的签名
jfieldID rect_right = env->GetFieldID(rectClass, "right", "I");//获取width的签名
jfieldID rect_bottom = env->GetFieldID(rectClass, "bottom", "I");//获取height的签名
faceArgs = (env)->NewObjectArray(numOfFaces, faceClass, 0);
//print the detection results
for (int i = 0; i < (pResults ? *pResults : 0); i++) {
short *p = ((short *) (pResults + 1)) + 142 * i;
int x = p[0];
int y = p[1];
int w = p[2];
int h = p[3];
int confidence = p[4];
int angle = p[5];
__android_log_print(ANDROID_LOG_INFO, JNITag,"face_rect=[%d, %d, %d, %d], confidence=%d, angle=%d\n", x, y, w, h,confidence, angle);
jobject newFace = (env)->NewObject(faceClass, faceClassInitID);
jobject newRect = (env)->NewObject(rectClass, rectClassInitID);
(env)->SetIntField(newRect, rect_left, x);
(env)->SetIntField(newRect, rect_top, y);
(env)->SetIntField(newRect, rect_right, x + w);
(env)->SetIntField(newRect, rect_bottom, y + h);
(env)->SetObjectField(newFace, faceRect, newRect);
(env)->SetIntField(newFace, faceConfidence, confidence);
(env)->SetIntField(newFace, faceAngle, angle);
(env)->SetObjectArrayElement(faceArgs, i, newFace);
}
//release the buffer
free(pBuffer);
return faceArgs;
}
}; | 3,723 | 1,348 |
// Copyright (c) 2019, QuantStack and Mamba Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#ifndef UMAMBA_VERSION_HPP
#define UMAMBA_VERSION_HPP
#include <array>
#include <string>
#define UMAMBA_VERSION_MAJOR 0
#define UMAMBA_VERSION_MINOR 21
#define UMAMBA_VERSION_PATCH 2
// Binary version
#define UMAMBA_BINARY_CURRENT 1
#define UMAMBA_BINARY_REVISION 0
#define UMAMBA_BINARY_AGE 0
#define __UMAMBA_STRINGIZE_IMPL(s) #s
#define __UMAMBA_STRINGIZE(s) __UMAMBA_STRINGIZE_IMPL(s)
#define UMAMBA_VERSION \
(UMAMBA_VERSION_MAJOR * 10000 + UMAMBA_VERSION_MINOR * 100 + UMAMBA_VERSION_PATCH)
#define UMAMBA_VERSION_STRING \
__UMAMBA_STRINGIZE(UMAMBA_VERSION_MAJOR) \
"." __UMAMBA_STRINGIZE(UMAMBA_VERSION_MINOR) "." __UMAMBA_STRINGIZE(UMAMBA_VERSION_PATCH)
namespace umamba
{
std::string version();
std::array<int, 3> version_arr();
}
#endif
| 1,174 | 443 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include "../Application/jucer_Headers.h"
#include "../ProjectSaving/jucer_ProjectSaver.h"
#include "../ProjectSaving/jucer_ProjectExport_Xcode.h"
#include "../Application/jucer_Application.h"
//==============================================================================
ModuleDescription::ModuleDescription (const File& folder)
: moduleFolder (folder),
moduleInfo (parseJUCEHeaderMetadata (getHeader()))
{
}
File ModuleDescription::getHeader() const
{
if (moduleFolder != File())
{
const char* extensions[] = { ".h", ".hpp", ".hxx" };
for (auto e : extensions)
{
auto header = moduleFolder.getChildFile (moduleFolder.getFileName() + e);
if (header.existsAsFile())
return header;
}
}
return {};
}
StringArray ModuleDescription::getDependencies() const
{
auto deps = StringArray::fromTokens (moduleInfo ["dependencies"].toString(), " \t;,", "\"'");
deps.trim();
deps.removeEmptyStrings();
return deps;
}
//==============================================================================
static bool tryToAddModuleFromFolder (const File& path, ModuleIDAndFolderList& list)
{
ModuleDescription m (path);
if (m.isValid())
{
list.push_back ({ m.getID(), path });
return true;
}
return false;
}
static void addAllModulesInSubfoldersRecursively (const File& path, int depth, ModuleIDAndFolderList& list)
{
if (depth > 0)
{
for (DirectoryIterator iter (path, false, "*", File::findDirectories); iter.next();)
{
if (auto* job = ThreadPoolJob::getCurrentThreadPoolJob())
if (job->shouldExit())
return;
auto childPath = iter.getFile();
if (! tryToAddModuleFromFolder (childPath, list))
addAllModulesInSubfoldersRecursively (childPath, depth - 1, list);
}
}
}
static void addAllModulesInFolder (const File& path, ModuleIDAndFolderList& list)
{
if (! tryToAddModuleFromFolder (path, list))
{
int subfolders = 3;
addAllModulesInSubfoldersRecursively (path, subfolders, list);
}
}
static void sort (ModuleIDAndFolderList& listToSort)
{
std::sort (listToSort.begin(), listToSort.end(), [] (const ModuleIDAndFolder& m1, const ModuleIDAndFolder& m2)
{
return m1.first.compareIgnoreCase (m2.first) < 0;
});
}
//==============================================================================
struct ModuleScannerJob : public ThreadPoolJob
{
ModuleScannerJob (const Array<File>& paths, std::function<void (const ModuleIDAndFolderList&)>&& callback)
: ThreadPoolJob ("ModuleScannerJob"),
pathsToScan (paths),
completionCallback (std::move (callback))
{
}
JobStatus runJob() override
{
ModuleIDAndFolderList list;
for (auto& p : pathsToScan)
addAllModulesInFolder (p, list);
if (! shouldExit())
{
sort (list);
completionCallback (list);
}
return jobHasFinished;
}
Array<File> pathsToScan;
std::function<void (const ModuleIDAndFolderList&)> completionCallback;
};
AvailableModuleList::AvailableModuleList()
{
}
ThreadPoolJob* AvailableModuleList::createScannerJob (const Array<File>& paths)
{
return new ModuleScannerJob (paths, [this] (ModuleIDAndFolderList scannedModuleList)
{
{
const ScopedLock swapLock (lock);
moduleList.swap (scannedModuleList);
}
listeners.call ([] (Listener& l) { MessageManager::callAsync ([&] { l.availableModulesChanged(); }); });
});
}
void AvailableModuleList::removePendingAndAddJob (ThreadPoolJob* jobToAdd)
{
scanPool.removeAllJobs (false, 100);
scanPool.addJob (jobToAdd, true);
}
void AvailableModuleList::scanPaths (const Array<File>& paths)
{
auto* job = createScannerJob (paths);
removePendingAndAddJob (job);
scanPool.waitForJobToFinish (job, -1);
}
void AvailableModuleList::scanPathsAsync (const Array<File>& paths)
{
removePendingAndAddJob (createScannerJob (paths));
}
ModuleIDAndFolderList AvailableModuleList::getAllModules() const
{
const ScopedLock readLock (lock);
return moduleList;
}
ModuleIDAndFolder AvailableModuleList::getModuleWithID (const String& id) const
{
const ScopedLock readLock (lock);
for (auto& mod : moduleList)
if (mod.first == id)
return mod;
return {};
}
void AvailableModuleList::removeDuplicates (const ModuleIDAndFolderList& other)
{
const ScopedLock readLock (lock);
for (auto& m : other)
{
auto pos = std::find (moduleList.begin(), moduleList.end(), m);
if (pos != moduleList.end())
moduleList.erase (pos);
}
}
//==============================================================================
LibraryModule::LibraryModule (const ModuleDescription& d)
: moduleInfo (d)
{
}
//==============================================================================
void LibraryModule::writeIncludes (ProjectSaver& projectSaver, OutputStream& out)
{
auto& project = projectSaver.project;
auto& modules = project.getEnabledModules();
auto id = getID();
if (modules.shouldCopyModuleFilesLocally (id).getValue())
{
auto juceModuleFolder = moduleInfo.getFolder();
auto localModuleFolder = project.getLocalModuleFolder (id);
localModuleFolder.createDirectory();
projectSaver.copyFolder (juceModuleFolder, localModuleFolder);
}
out << "#include <" << moduleInfo.moduleFolder.getFileName() << "/"
<< moduleInfo.getHeader().getFileName()
<< ">" << newLine;
}
//==============================================================================
static void parseAndAddLibs (StringArray& libList, const String& libs)
{
libList.addTokens (libs, ", ", {});
libList.trim();
libList.removeDuplicates (false);
}
void LibraryModule::addSettingsForModuleToExporter (ProjectExporter& exporter, ProjectSaver& projectSaver) const
{
auto& project = exporter.getProject();
auto moduleRelativePath = exporter.getModuleFolderRelativeToProject (getID());
exporter.addToExtraSearchPaths (moduleRelativePath.getParentDirectory());
String libDirPlatform;
if (exporter.isLinux())
libDirPlatform = "Linux";
else if (exporter.isCodeBlocks() && exporter.isWindows())
libDirPlatform = "MinGW";
else
libDirPlatform = exporter.getTargetFolder().getFileName();
auto libSubdirPath = moduleRelativePath.toUnixStyle() + "/libs/" + libDirPlatform;
auto moduleLibDir = File (project.getProjectFolder().getFullPathName() + "/" + libSubdirPath);
if (moduleLibDir.exists())
exporter.addToModuleLibPaths ({ libSubdirPath, moduleRelativePath.getRoot() });
auto extraInternalSearchPaths = moduleInfo.getExtraSearchPaths().trim();
if (extraInternalSearchPaths.isNotEmpty())
{
auto paths = StringArray::fromTokens (extraInternalSearchPaths, true);
for (auto& path : paths)
exporter.addToExtraSearchPaths (moduleRelativePath.getChildFile (path.unquoted()));
}
{
auto extraDefs = moduleInfo.getPreprocessorDefs().trim();
if (extraDefs.isNotEmpty())
exporter.getExporterPreprocessorDefsValue() = exporter.getExporterPreprocessorDefsString() + "\n" + extraDefs;
}
{
Array<File> compiled;
auto& modules = project.getEnabledModules();
auto id = getID();
auto localModuleFolder = modules.shouldCopyModuleFilesLocally (id).getValue() ? project.getLocalModuleFolder (id)
: moduleInfo.getFolder();
findAndAddCompiledUnits (exporter, &projectSaver, compiled);
if (modules.shouldShowAllModuleFilesInProject (id).getValue())
addBrowseableCode (exporter, compiled, localModuleFolder);
}
if (exporter.isXcode())
{
auto& xcodeExporter = dynamic_cast<XcodeProjectExporter&> (exporter);
if (project.isAUPluginHost())
xcodeExporter.xcodeFrameworks.addTokens (xcodeExporter.isOSX() ? "AudioUnit CoreAudioKit" : "CoreAudioKit", false);
auto frameworks = moduleInfo.moduleInfo [xcodeExporter.isOSX() ? "OSXFrameworks" : "iOSFrameworks"].toString();
xcodeExporter.xcodeFrameworks.addTokens (frameworks, ", ", {});
parseAndAddLibs (xcodeExporter.xcodeLibs, moduleInfo.moduleInfo [exporter.isOSX() ? "OSXLibs" : "iOSLibs"].toString());
}
else if (exporter.isLinux())
{
parseAndAddLibs (exporter.linuxLibs, moduleInfo.moduleInfo ["linuxLibs"].toString());
parseAndAddLibs (exporter.linuxPackages, moduleInfo.moduleInfo ["linuxPackages"].toString());
}
else if (exporter.isWindows())
{
if (exporter.isCodeBlocks())
parseAndAddLibs (exporter.mingwLibs, moduleInfo.moduleInfo ["mingwLibs"].toString());
else
parseAndAddLibs (exporter.windowsLibs, moduleInfo.moduleInfo ["windowsLibs"].toString());
}
else if (exporter.isAndroid())
{
parseAndAddLibs (exporter.androidLibs, moduleInfo.moduleInfo ["androidLibs"].toString());
}
}
void LibraryModule::getConfigFlags (Project& project, OwnedArray<Project::ConfigFlag>& flags) const
{
auto header = moduleInfo.getHeader();
jassert (header.exists());
StringArray lines;
header.readLines (lines);
for (int i = 0; i < lines.size(); ++i)
{
auto line = lines[i].trim();
if (line.startsWith ("/**") && line.containsIgnoreCase ("Config:"))
{
std::unique_ptr<Project::ConfigFlag> config (new Project::ConfigFlag());
config->sourceModuleID = getID();
config->symbol = line.fromFirstOccurrenceOf (":", false, false).trim();
if (config->symbol.length() > 2)
{
++i;
while (! (lines[i].contains ("*/") || lines[i].contains ("@see")))
{
if (lines[i].trim().isNotEmpty())
config->description = config->description.trim() + " " + lines[i].trim();
++i;
}
config->description = config->description.upToFirstOccurrenceOf ("*/", false, false);
config->value = project.getConfigFlag (config->symbol);
i += 2;
if (lines[i].contains ("#define " + config->symbol))
{
auto value = lines[i].fromFirstOccurrenceOf ("#define " + config->symbol, false, true).trim();
config->value.setDefault (value == "0" ? false : true);
}
auto currentValue = config->value.get().toString();
if (currentValue == "enabled") config->value = true;
else if (currentValue == "disabled") config->value = false;
flags.add (config.release());
}
}
}
}
//==============================================================================
struct FileSorter
{
static int compareElements (const File& f1, const File& f2)
{
return f1.getFileName().compareNatural (f2.getFileName());
}
};
bool LibraryModule::CompileUnit::hasSuffix (const File& f, const char* suffix)
{
auto fileWithoutSuffix = f.getFileNameWithoutExtension() + ".";
return fileWithoutSuffix.containsIgnoreCase (suffix + String ("."))
|| fileWithoutSuffix.containsIgnoreCase (suffix + String ("_"));
}
void LibraryModule::CompileUnit::writeInclude (MemoryOutputStream&) const
{
}
bool LibraryModule::CompileUnit::isNeededForExporter (ProjectExporter& exporter) const
{
if ((hasSuffix (file, "_OSX") && ! exporter.isOSX())
|| (hasSuffix (file, "_iOS") && ! exporter.isiOS())
|| (hasSuffix (file, "_Windows") && ! exporter.isWindows())
|| (hasSuffix (file, "_Linux") && ! exporter.isLinux())
|| (hasSuffix (file, "_Android") && ! exporter.isAndroid()))
return false;
auto targetType = Project::getTargetTypeFromFilePath (file, false);
if (targetType != ProjectType::Target::unspecified && ! exporter.shouldBuildTargetType (targetType))
return false;
return exporter.usesMMFiles() ? isCompiledForObjC
: isCompiledForNonObjC;
}
String LibraryModule::CompileUnit::getFilenameForProxyFile() const
{
return "include_" + file.getFileName();
}
Array<LibraryModule::CompileUnit> LibraryModule::getAllCompileUnits (ProjectType::Target::Type forTarget) const
{
auto files = getFolder().findChildFiles (File::findFiles, false);
FileSorter sorter;
files.sort (sorter);
Array<LibraryModule::CompileUnit> units;
for (auto& file : files)
{
if (file.getFileName().startsWithIgnoreCase (getID())
&& file.hasFileExtension (sourceFileExtensions))
{
if (forTarget == ProjectType::Target::unspecified
|| forTarget == Project::getTargetTypeFromFilePath (file, true))
{
CompileUnit cu;
cu.file = file;
units.add (cu);
}
}
}
for (auto& cu : units)
{
cu.isCompiledForObjC = true;
cu.isCompiledForNonObjC = ! cu.file.hasFileExtension ("mm;m");
if (cu.isCompiledForNonObjC)
if (files.contains (cu.file.withFileExtension ("mm")))
cu.isCompiledForObjC = false;
jassert (cu.isCompiledForObjC || cu.isCompiledForNonObjC);
}
return units;
}
void LibraryModule::findAndAddCompiledUnits (ProjectExporter& exporter,
ProjectSaver* projectSaver,
Array<File>& result,
ProjectType::Target::Type forTarget) const
{
for (auto& cu : getAllCompileUnits (forTarget))
{
if (cu.isNeededForExporter (exporter))
{
auto localFile = exporter.getProject().getGeneratedCodeFolder()
.getChildFile (cu.getFilenameForProxyFile());
result.add (localFile);
if (projectSaver != nullptr)
projectSaver->addFileToGeneratedGroup (localFile);
}
}
}
static void addFileWithGroups (Project::Item& group, const RelativePath& file, const String& path)
{
auto slash = path.indexOfChar (File::getSeparatorChar());
if (slash >= 0)
{
auto topLevelGroup = path.substring (0, slash);
auto remainingPath = path.substring (slash + 1);
auto newGroup = group.getOrCreateSubGroup (topLevelGroup);
addFileWithGroups (newGroup, file, remainingPath);
}
else
{
if (! group.containsChildForFile (file))
group.addRelativeFile (file, -1, false);
}
}
void LibraryModule::findBrowseableFiles (const File& folder, Array<File>& filesFound) const
{
Array<File> tempList;
FileSorter sorter;
DirectoryIterator iter (folder, true, "*", File::findFiles);
bool isHiddenFile;
while (iter.next (nullptr, &isHiddenFile, nullptr, nullptr, nullptr, nullptr))
if (! isHiddenFile && iter.getFile().hasFileExtension (browseableFileExtensions))
tempList.addSorted (sorter, iter.getFile());
filesFound.addArray (tempList);
}
void LibraryModule::addBrowseableCode (ProjectExporter& exporter, const Array<File>& compiled, const File& localModuleFolder) const
{
if (sourceFiles.isEmpty())
findBrowseableFiles (localModuleFolder, sourceFiles);
auto sourceGroup = Project::Item::createGroup (exporter.getProject(), getID(), "__mainsourcegroup" + getID(), false);
auto moduleFromProject = exporter.getModuleFolderRelativeToProject (getID());
auto moduleHeader = moduleInfo.getHeader();
for (auto& sourceFile : sourceFiles)
{
auto pathWithinModule = FileHelpers::getRelativePathFrom (sourceFile, localModuleFolder);
// (Note: in exporters like MSVC we have to avoid adding the same file twice, even if one of those instances
// is flagged as being excluded from the build, because this overrides the other and it fails to compile)
if ((exporter.canCopeWithDuplicateFiles() || ! compiled.contains (sourceFile)) && sourceFile != moduleHeader)
addFileWithGroups (sourceGroup,
moduleFromProject.getChildFile (pathWithinModule),
pathWithinModule);
}
sourceGroup.sortAlphabetically (true, true);
sourceGroup.addFileAtIndex (moduleHeader, -1, false);
exporter.getModulesGroup().state.appendChild (sourceGroup.state.createCopy(), nullptr);
}
//==============================================================================
EnabledModuleList::EnabledModuleList (Project& p, const ValueTree& s)
: project (p), state (s)
{
}
ModuleDescription EnabledModuleList::getModuleInfo (const String& moduleID)
{
return ModuleDescription (project.getModuleWithID (moduleID).second);
}
bool EnabledModuleList::isModuleEnabled (const String& moduleID) const
{
return state.getChildWithProperty (Ids::ID, moduleID).isValid();
}
bool EnabledModuleList::isAudioPluginModuleMissing() const
{
return project.getProjectType().isAudioPlugin()
&& ! isModuleEnabled ("juce_audio_plugin_client");
}
bool EnabledModuleList::shouldUseGlobalPath (const String& moduleID) const
{
return static_cast<bool> (state.getChildWithProperty (Ids::ID, moduleID)
.getProperty (Ids::useGlobalPath));
}
Value EnabledModuleList::getShouldUseGlobalPathValue (const String& moduleID) const
{
return state.getChildWithProperty (Ids::ID, moduleID)
.getPropertyAsValue (Ids::useGlobalPath, getUndoManager());
}
Value EnabledModuleList::shouldShowAllModuleFilesInProject (const String& moduleID)
{
return state.getChildWithProperty (Ids::ID, moduleID)
.getPropertyAsValue (Ids::showAllCode, getUndoManager());
}
struct ModuleTreeSorter
{
static int compareElements (const ValueTree& m1, const ValueTree& m2)
{
return m1[Ids::ID].toString().compareIgnoreCase (m2[Ids::ID]);
}
};
void EnabledModuleList::sortAlphabetically()
{
ModuleTreeSorter sorter;
state.sort (sorter, getUndoManager(), false);
}
Value EnabledModuleList::shouldCopyModuleFilesLocally (const String& moduleID) const
{
return state.getChildWithProperty (Ids::ID, moduleID)
.getPropertyAsValue (Ids::useLocalCopy, getUndoManager());
}
void EnabledModuleList::addModule (const File& moduleFolder, bool copyLocally, bool useGlobalPath, bool sendAnalyticsEvent)
{
ModuleDescription info (moduleFolder);
if (info.isValid())
{
auto moduleID = info.getID();
if (! isModuleEnabled (moduleID))
{
ValueTree module (Ids::MODULE);
module.setProperty (Ids::ID, moduleID, getUndoManager());
state.appendChild (module, getUndoManager());
sortAlphabetically();
shouldShowAllModuleFilesInProject (moduleID) = true;
shouldCopyModuleFilesLocally (moduleID) = copyLocally;
getShouldUseGlobalPathValue (moduleID) = useGlobalPath;
RelativePath path (moduleFolder.getParentDirectory(),
project.getProjectFolder(), RelativePath::projectFolder);
for (Project::ExporterIterator exporter (project); exporter.next();)
exporter->getPathForModuleValue (moduleID) = path.toUnixStyle();
if (! useGlobalPath)
project.rescanExporterPathModules (false);
if (sendAnalyticsEvent)
{
StringPairArray data;
data.set ("label", moduleID);
Analytics::getInstance()->logEvent ("Module Added", data, ProjucerAnalyticsEvent::projectEvent);
}
}
}
}
void EnabledModuleList::removeModule (String moduleID) // must be pass-by-value, and not a const ref!
{
for (auto i = state.getNumChildren(); --i >= 0;)
if (state.getChild(i) [Ids::ID] == moduleID)
state.removeChild (i, getUndoManager());
for (Project::ExporterIterator exporter (project); exporter.next();)
exporter->removePathForModule (moduleID);
}
void EnabledModuleList::createRequiredModules (OwnedArray<LibraryModule>& modules)
{
for (int i = 0; i < getNumModules(); ++i)
modules.add (new LibraryModule (getModuleInfo (getModuleID (i))));
}
StringArray EnabledModuleList::getAllModules() const
{
StringArray moduleIDs;
for (int i = 0; i < getNumModules(); ++i)
moduleIDs.add (getModuleID (i));
return moduleIDs;
}
static void getDependencies (Project& project, const String& moduleID, StringArray& dependencies)
{
auto info = project.getEnabledModules().getModuleInfo (moduleID);
for (auto uid : info.getDependencies())
{
if (! dependencies.contains (uid, true))
{
dependencies.add (uid);
getDependencies (project, uid, dependencies);
}
}
}
StringArray EnabledModuleList::getExtraDependenciesNeeded (const String& moduleID) const
{
StringArray dependencies, extraDepsNeeded;
getDependencies (project, moduleID, dependencies);
for (auto dep : dependencies)
if (dep != moduleID && ! isModuleEnabled (dep))
extraDepsNeeded.add (dep);
return extraDepsNeeded;
}
bool EnabledModuleList::doesModuleHaveHigherCppStandardThanProject (const String& moduleID)
{
auto projectCppStandard = project.getCppStandardString();
if (projectCppStandard == "latest")
return false;
auto moduleCppStandard = getModuleInfo (moduleID).getMinimumCppStandard();
return (moduleCppStandard.getIntValue() > projectCppStandard.getIntValue());
}
bool EnabledModuleList::areMostModulesUsingGlobalPath() const
{
int numYes = 0, numNo = 0;
for (auto i = getNumModules(); --i >= 0;)
{
if (shouldUseGlobalPath (getModuleID (i)))
++numYes;
else
++numNo;
}
return numYes > numNo;
}
bool EnabledModuleList::areMostModulesCopiedLocally() const
{
int numYes = 0, numNo = 0;
for (auto i = getNumModules(); --i >= 0;)
{
if (shouldCopyModuleFilesLocally (getModuleID (i)).getValue())
++numYes;
else
++numNo;
}
return numYes > numNo;
}
void EnabledModuleList::setLocalCopyModeForAllModules (bool copyLocally)
{
for (auto i = getNumModules(); --i >= 0;)
shouldCopyModuleFilesLocally (project.getEnabledModules().getModuleID (i)) = copyLocally;
}
File EnabledModuleList::findDefaultModulesFolder (Project& project)
{
File globalPath (getAppSettings().getStoredPath (Ids::defaultJuceModulePath, TargetOS::getThisOS()).get().toString());
if (globalPath.exists())
return globalPath;
for (auto& exporterPathModule : project.getExporterPathsModuleList().getAllModules())
{
auto f = exporterPathModule.second;
if (f.isDirectory())
return f.getParentDirectory();
}
return File::getCurrentWorkingDirectory();
}
void EnabledModuleList::addModuleFromUserSelectedFile()
{
static auto lastLocation = findDefaultModulesFolder (project);
FileChooser fc ("Select a module to add...", lastLocation, {});
if (fc.browseForDirectory())
{
lastLocation = fc.getResult();
addModuleOfferingToCopy (lastLocation, true);
}
}
void EnabledModuleList::addModuleInteractive (const String& moduleID)
{
auto f = project.getModuleWithID (moduleID).second;
if (f != File())
{
addModule (f, areMostModulesCopiedLocally(), areMostModulesUsingGlobalPath(), true);
return;
}
addModuleFromUserSelectedFile();
}
void EnabledModuleList::addModuleOfferingToCopy (const File& f, bool isFromUserSpecifiedFolder)
{
ModuleDescription m (f);
if (! m.isValid())
{
AlertWindow::showMessageBoxAsync (AlertWindow::InfoIcon,
"Add Module", "This wasn't a valid module folder!");
return;
}
if (isModuleEnabled (m.getID()))
{
AlertWindow::showMessageBoxAsync (AlertWindow::InfoIcon,
"Add Module", "The project already contains this module!");
return;
}
addModule (m.moduleFolder, areMostModulesCopiedLocally(),
isFromUserSpecifiedFolder ? false : areMostModulesUsingGlobalPath(),
true);
}
bool isJUCEFolder (const File& f)
{
return isJUCEModulesFolder (f.getChildFile ("modules"));
}
bool isJUCEModulesFolder (const File& f)
{
return f.isDirectory() && f.getChildFile ("juce_core").isDirectory();
}
| 27,213 | 7,845 |
/*=========================================================================
Program: ParaView
Module: $RCSfile: pqTestUtility.cxx,v $
Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.1.
See License_v1.1.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqTestUtility.h"
#include <QFileInfo>
#include <QApplication>
#include "pqEventSource.h"
#include "pqEventObserver.h"
#include "pqRecordEventsDialog.h"
#include "QtTestingConfigure.h"
#ifdef QT_TESTING_WITH_XML
#include "pqXMLEventSource.h"
#include "pqXMLEventObserver.h"
#endif
#ifdef QT_TESTING_WITH_PYTHON
#include "pqPythonEventSource.h"
#include "pqPythonEventObserver.h"
#endif
pqTestUtility::pqTestUtility(QObject* p) :
QObject(p)
{
QObject::connect(
&this->Dispatcher,
SIGNAL(succeeded()),
this,
SLOT(testSucceeded()));
QObject::connect(
&this->Dispatcher,
SIGNAL(failed()),
this,
SLOT(testFailed()));
this->Translator.addDefaultWidgetEventTranslators();
this->Player.addDefaultWidgetEventPlayers();
#ifdef QT_TESTING_WITH_XML
// add an XML source
this->addEventSource("xml", new pqXMLEventSource(this));
this->addEventObserver("xml", new pqXMLEventObserver(this));
#endif
#ifdef QT_TESTING_WITH_PYTHON
// add a python event source
this->addEventSource("py", new pqPythonEventSource(this));
this->addEventObserver("py", new pqPythonEventObserver(this));
#endif
}
pqTestUtility::~pqTestUtility()
{
}
pqEventDispatcher* pqTestUtility::dispatcher()
{
return &this->Dispatcher;
}
pqEventPlayer* pqTestUtility::eventPlayer()
{
return &this->Player;
}
pqEventTranslator* pqTestUtility::eventTranslator()
{
return &this->Translator;
}
void pqTestUtility::addEventSource(const QString& fileExtension, pqEventSource* source)
{
QMap<QString, pqEventSource*>::iterator iter;
iter = this->EventSources.find(fileExtension);
if(iter != this->EventSources.end())
{
pqEventSource* src = iter.value();
this->EventSources.erase(iter);
delete src;
}
this->EventSources.insert(fileExtension, source);
source->setParent(this);
}
void pqTestUtility::addEventObserver(const QString& fileExtension,
pqEventObserver* observer)
{
QMap<QString, pqEventObserver*>::iterator iter;
iter = this->EventObservers.find(fileExtension);
if(iter != this->EventObservers.end() && iter.value() != observer)
{
pqEventObserver* src = iter.value();
this->EventObservers.erase(iter);
delete src;
}
if(iter != this->EventObservers.end() && iter.value() == observer)
{
return;
}
this->EventObservers.insert(fileExtension, observer);
observer->setParent(this);
}
void pqTestUtility::playTests(const QString& filename)
{
QFileInfo info(filename);
QString suffix = info.completeSuffix();
QMap<QString, pqEventSource*>::iterator iter;
iter = this->EventSources.find(suffix);
if(info.isReadable() && iter != this->EventSources.end())
{
iter.value()->setContent(filename);
this->Dispatcher.playEvents(*iter.value(), this->Player);
}
}
void pqTestUtility::playTests(const QStringList& filenames)
{
foreach(QString filename, filenames)
{
this->playTests(filename);
}
}
void pqTestUtility::recordTests(const QString& filename)
{
#if defined(Q_WS_MAC)
// check for native or non-native menu bar.
// testing framework doesn't work with native menu bar, so let's warn if we
// get that.
if(!getenv("QT_MAC_NO_NATIVE_MENUBAR"))
{
qWarning("Recording menu events for native Mac menus doesn't work.\n"
"Set the QT_MAC_NO_NATIVE_MENUBAR environment variable to"
" correctly record menus");
}
#endif
QMap<QString, pqEventObserver*>::iterator iter;
QFileInfo info(filename);
QString suffix = info.completeSuffix();
pqEventObserver* observer = NULL;
iter = this->EventObservers.find(suffix);
if(iter != this->EventObservers.end())
{
observer = iter.value();
}
if(!observer)
{
// cannot find observer for type of file
return;
}
pqRecordEventsDialog* dialog = new pqRecordEventsDialog(this->Translator,
*observer,
filename,
QApplication::activeWindow());
dialog->setAttribute(Qt::WA_QuitOnClose, false);
dialog->show();
}
void pqTestUtility::testSucceeded()
{
}
void pqTestUtility::testFailed()
{
}
| 5,592 | 1,961 |
//
// yield.hpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "coroutine.hpp"
#ifndef reenter
# define reenter(c) ASIO_CORO_REENTER(c)
#endif
#ifndef yield
# define yield ASIO_CORO_YIELD
#endif
#ifndef fork
# define fork ASIO_CORO_FORK
#endif
| 487 | 213 |
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/video.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videostab.hpp"
#include "opencv2/opencv_modules.hpp"
#define arg(name) cmd.get<string>(name)
#define argb(name) cmd.get<bool>(name)
#define argi(name) cmd.get<int>(name)
#define argf(name) cmd.get<float>(name)
#define argd(name) cmd.get<double>(name)
using namespace std;
using namespace cv;
using namespace cv::videostab;
Ptr<IFrameSource> stabilizedFrames;
string saveMotionsPath;
double outputFps;
string outputPath;
bool quietMode;
void run();
void saveMotionsIfNecessary();
void printHelp();
MotionModel motionModel(const string &str);
void run()
{
VideoWriter writer;
Mat stabilizedFrame;
int nframes = 0;
// for each stabilized frame
while (!(stabilizedFrame = stabilizedFrames->nextFrame()).empty())
{
nframes++;
// init writer (once) and save stabilized frame
if (!outputPath.empty())
{
if (!writer.isOpened())
writer.open(outputPath, VideoWriter::fourcc('X','V','I','D'),
outputFps, stabilizedFrame.size());
writer << stabilizedFrame;
}
// show stabilized frame
if (!quietMode)
{
imshow("stabilizedFrame", stabilizedFrame);
char key = static_cast<char>(waitKey(3));
if (key == 27) { cout << endl; break; }
}
}
cout << "processed frames: " << nframes << endl
<< "finished\n";
}
void printHelp()
{
cout << "OpenCV video stabilizer.\n"
"Usage: videostab <file_path> [arguments]\n\n"
"Arguments:\n"
" -m=, --model=(transl|transl_and_scale|rigid|similarity|affine|homography)\n"
" Set motion model. The default is affine.\n"
" -lp=, --lin-prog-motion-est=(yes|no)\n"
" Turn on/off LP based motion estimation. The default is no.\n"
" --subset=(<int_number>|auto)\n"
" Number of random samples per one motion hypothesis. The default is auto.\n"
" --thresh=(<float_number>|auto)\n"
" Maximum error to classify match as inlier. The default is auto.\n"
" --outlier-ratio=<float_number>\n"
" Motion estimation outlier ratio hypothesis. The default is 0.5.\n"
" --min-inlier-ratio=<float_number>\n"
" Minimum inlier ratio to decide if estimated motion is OK. The default is 0.1.\n"
" --nkps=<int_number>\n"
" Number of keypoints to find in each frame. The default is 1000.\n"
" --local-outlier-rejection=(yes|no)\n"
" Perform local outlier rejection. The default is no.\n\n"
" --feature-masks=(file_path|no)\n"
" Load masks from file. The default is no.\n\n"
" -sm=, --save-motions=(<file_path>|no)\n"
" Save estimated motions into file. The default is no.\n"
" -lm=, --load-motions=(<file_path>|no)\n"
" Load motions from file. The default is no.\n\n"
" -r=, --radius=<int_number>\n"
" Set sliding window radius. The default is 15.\n"
" --stdev=(<float_number>|auto)\n"
" Set smoothing weights standard deviation. The default is auto\n"
" (i.e. sqrt(radius)).\n"
" -lps=, --lin-prog-stab=(yes|no)\n"
" Turn on/off linear programming based stabilization method.\n"
" --lps-trim-ratio=(<float_number>|auto)\n"
" Trimming ratio used in linear programming based method.\n"
" --lps-w1=(<float_number>|1)\n"
" 1st derivative weight. The default is 1.\n"
" --lps-w2=(<float_number>|10)\n"
" 2nd derivative weight. The default is 10.\n"
" --lps-w3=(<float_number>|100)\n"
" 3rd derivative weight. The default is 100.\n"
" --lps-w4=(<float_number>|100)\n"
" Non-translation motion components weight. The default is 100.\n\n"
" --deblur=(yes|no)\n"
" Do deblurring.\n"
" --deblur-sens=<float_number>\n"
" Set deblurring sensitivity (from 0 to +inf). The default is 0.1.\n\n"
" -t=, --trim-ratio=<float_number>\n"
" Set trimming ratio (from 0 to 0.5). The default is 0.1.\n"
" -et=, --est-trim=(yes|no)\n"
" Estimate trim ratio automatically. The default is yes.\n"
" -ic=, --incl-constr=(yes|no)\n"
" Ensure the inclusion constraint is always satisfied. The default is no.\n\n"
" -bm=, --border-mode=(replicate|reflect|const)\n"
" Set border extrapolation mode. The default is replicate.\n\n"
" --mosaic=(yes|no)\n"
" Do consistent mosaicing. The default is no.\n"
" --mosaic-stdev=<float_number>\n"
" Consistent mosaicing stdev threshold. The default is 10.0.\n\n"
" -mi=, --motion-inpaint=(yes|no)\n"
" Do motion inpainting (requires CUDA support). The default is no.\n"
" --mi-dist-thresh=<float_number>\n"
" Estimated flow distance threshold for motion inpainting. The default is 5.0.\n\n"
" -ci=, --color-inpaint=(no|average|ns|telea)\n"
" Do color inpainting. The default is no.\n"
" --ci-radius=<float_number>\n"
" Set color inpainting radius (for ns and telea options only).\n"
" The default is 2.0\n\n"
" -ws=, --wobble-suppress=(yes|no)\n"
" Perform wobble suppression. The default is no.\n"
" --ws-lp=(yes|no)\n"
" Turn on/off LP based motion estimation. The default is no.\n"
" --ws-period=<int_number>\n"
" Set wobble suppression period. The default is 30.\n"
" --ws-model=(transl|transl_and_scale|rigid|similarity|affine|homography)\n"
" Set wobble suppression motion model (must have more DOF than motion \n"
" estimation model). The default is homography.\n"
" --ws-subset=(<int_number>|auto)\n"
" Number of random samples per one motion hypothesis. The default is auto.\n"
" --ws-thresh=(<float_number>|auto)\n"
" Maximum error to classify match as inlier. The default is auto.\n"
" --ws-outlier-ratio=<float_number>\n"
" Motion estimation outlier ratio hypothesis. The default is 0.5.\n"
" --ws-min-inlier-ratio=<float_number>\n"
" Minimum inlier ratio to decide if estimated motion is OK. The default is 0.1.\n"
" --ws-nkps=<int_number>\n"
" Number of keypoints to find in each frame. The default is 1000.\n"
" --ws-local-outlier-rejection=(yes|no)\n"
" Perform local outlier rejection. The default is no.\n\n"
" -sm2=, --save-motions2=(<file_path>|no)\n"
" Save motions estimated for wobble suppression. The default is no.\n"
" -lm2=, --load-motions2=(<file_path>|no)\n"
" Load motions for wobble suppression from file. The default is no.\n\n"
" -gpu=(yes|no)\n"
" Use CUDA optimization whenever possible. The default is no.\n\n"
" -o=, --output=(no|<file_path>)\n"
" Set output file path explicitly. The default is stabilized.avi.\n"
" --fps=(<float_number>|auto)\n"
" Set output video FPS explicitly. By default the source FPS is used (auto).\n"
" -q, --quiet\n"
" Don't show output video frames.\n\n"
" -h, --help\n"
" Print help.\n\n"
"Note: some argument configurations lead to two passes, some to single pass.\n\n";
}
// motion estimator builders are for concise creation of motion estimators
class IMotionEstimatorBuilder
{
public:
virtual ~IMotionEstimatorBuilder() {}
virtual Ptr<ImageMotionEstimatorBase> build() = 0;
protected:
IMotionEstimatorBuilder(CommandLineParser &command) : cmd(command) {}
CommandLineParser cmd;
};
class MotionEstimatorRansacL2Builder : public IMotionEstimatorBuilder
{
public:
MotionEstimatorRansacL2Builder(CommandLineParser &command, bool use_gpu, const string &_prefix = "")
: IMotionEstimatorBuilder(command), gpu(use_gpu), prefix(_prefix) {}
virtual Ptr<ImageMotionEstimatorBase> build() CV_OVERRIDE
{
Ptr<MotionEstimatorRansacL2> est = makePtr<MotionEstimatorRansacL2>(motionModel(arg(prefix + "model")));
RansacParams ransac = est->ransacParams();
if (arg(prefix + "subset") != "auto")
ransac.size = argi(prefix + "subset");
if (arg(prefix + "thresh") != "auto")
ransac.thresh = argf(prefix + "thresh");
ransac.eps = argf(prefix + "outlier-ratio");
est->setRansacParams(ransac);
est->setMinInlierRatio(argf(prefix + "min-inlier-ratio"));
Ptr<IOutlierRejector> outlierRejector = makePtr<NullOutlierRejector>();
if (arg(prefix + "local-outlier-rejection") == "yes")
{
Ptr<TranslationBasedLocalOutlierRejector> tblor = makePtr<TranslationBasedLocalOutlierRejector>();
RansacParams ransacParams = tblor->ransacParams();
if (arg(prefix + "thresh") != "auto")
ransacParams.thresh = argf(prefix + "thresh");
tblor->setRansacParams(ransacParams);
outlierRejector = tblor;
}
#if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDAOPTFLOW)
if (gpu)
{
Ptr<KeypointBasedMotionEstimatorGpu> kbest = makePtr<KeypointBasedMotionEstimatorGpu>(est);
kbest->setOutlierRejector(outlierRejector);
return kbest;
}
#else
CV_Assert(gpu == false && "CUDA modules are not available");
#endif
Ptr<KeypointBasedMotionEstimator> kbest = makePtr<KeypointBasedMotionEstimator>(est);
kbest->setDetector(GFTTDetector::create(argi(prefix + "nkps")));
kbest->setOutlierRejector(outlierRejector);
return kbest;
}
private:
bool gpu;
string prefix;
};
class MotionEstimatorL1Builder : public IMotionEstimatorBuilder
{
public:
MotionEstimatorL1Builder(CommandLineParser &command, bool use_gpu, const string &_prefix = "")
: IMotionEstimatorBuilder(command), gpu(use_gpu), prefix(_prefix) {}
virtual Ptr<ImageMotionEstimatorBase> build() CV_OVERRIDE
{
Ptr<MotionEstimatorL1> est = makePtr<MotionEstimatorL1>(motionModel(arg(prefix + "model")));
Ptr<IOutlierRejector> outlierRejector = makePtr<NullOutlierRejector>();
if (arg(prefix + "local-outlier-rejection") == "yes")
{
Ptr<TranslationBasedLocalOutlierRejector> tblor = makePtr<TranslationBasedLocalOutlierRejector>();
RansacParams ransacParams = tblor->ransacParams();
if (arg(prefix + "thresh") != "auto")
ransacParams.thresh = argf(prefix + "thresh");
tblor->setRansacParams(ransacParams);
outlierRejector = tblor;
}
#if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDAOPTFLOW)
if (gpu)
{
Ptr<KeypointBasedMotionEstimatorGpu> kbest = makePtr<KeypointBasedMotionEstimatorGpu>(est);
kbest->setOutlierRejector(outlierRejector);
return kbest;
}
#else
CV_Assert(gpu == false && "CUDA modules are not available");
#endif
Ptr<KeypointBasedMotionEstimator> kbest = makePtr<KeypointBasedMotionEstimator>(est);
kbest->setDetector(GFTTDetector::create(argi(prefix + "nkps")));
kbest->setOutlierRejector(outlierRejector);
return kbest;
}
private:
bool gpu;
string prefix;
};
int main(int argc, const char **argv)
{
try
{
const char *keys =
"{ @1 | | }"
"{ m model | affine | }"
"{ lp lin-prog-motion-est | no | }"
"{ subset | auto | }"
"{ thresh | auto | }"
"{ outlier-ratio | 0.5 | }"
"{ min-inlier-ratio | 0.1 | }"
"{ nkps | 1000 | }"
"{ extra-kps | 0 | }"
"{ local-outlier-rejection | no | }"
"{ feature-masks | no | }"
"{ sm save-motions | no | }"
"{ lm load-motions | no | }"
"{ r radius | 15 | }"
"{ stdev | auto | }"
"{ lps lin-prog-stab | no | }"
"{ lps-trim-ratio | auto | }"
"{ lps-w1 | 1 | }"
"{ lps-w2 | 10 | }"
"{ lps-w3 | 100 | }"
"{ lps-w4 | 100 | }"
"{ deblur | no | }"
"{ deblur-sens | 0.1 | }"
"{ et est-trim | yes | }"
"{ t trim-ratio | 0.1 | }"
"{ ic incl-constr | no | }"
"{ bm border-mode | replicate | }"
"{ mosaic | no | }"
"{ ms mosaic-stdev | 10.0 | }"
"{ mi motion-inpaint | no | }"
"{ mi-dist-thresh | 5.0 | }"
"{ ci color-inpaint | no | }"
"{ ci-radius | 2 | }"
"{ ws wobble-suppress | no | }"
"{ ws-period | 30 | }"
"{ ws-model | homography | }"
"{ ws-subset | auto | }"
"{ ws-thresh | auto | }"
"{ ws-outlier-ratio | 0.5 | }"
"{ ws-min-inlier-ratio | 0.1 | }"
"{ ws-nkps | 1000 | }"
"{ ws-extra-kps | 0 | }"
"{ ws-local-outlier-rejection | no | }"
"{ ws-lp | no | }"
"{ sm2 save-motions2 | no | }"
"{ lm2 load-motions2 | no | }"
"{ gpu | no | }"
"{ o output | stabilized.avi | }"
"{ fps | auto | }"
"{ q quiet | | }"
"{ h help | | }";
CommandLineParser cmd(argc, argv, keys);
// parse command arguments
if (argb("help"))
{
printHelp();
return 0;
}
if (arg("gpu") == "yes")
{
cout << "initializing GPU..."; cout.flush();
Mat hostTmp = Mat::zeros(1, 1, CV_32F);
cuda::GpuMat deviceTmp;
deviceTmp.upload(hostTmp);
cout << endl;
}
StabilizerBase *stabilizer = 0;
// check if source video is specified
string inputPath = arg(0);
if (inputPath.empty())
throw runtime_error("specify video file path");
// get source video parameters
Ptr<VideoFileSource> source = makePtr<VideoFileSource>(inputPath);
cout << "frame count (rough): " << source->count() << endl;
if (arg("fps") == "auto")
outputFps = source->fps();
else
outputFps = argd("fps");
// prepare motion estimation builders
Ptr<IMotionEstimatorBuilder> motionEstBuilder;
if (arg("lin-prog-motion-est") == "yes")
motionEstBuilder.reset(new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes"));
else
motionEstBuilder.reset(new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes"));
Ptr<IMotionEstimatorBuilder> wsMotionEstBuilder;
if (arg("ws-lp") == "yes")
wsMotionEstBuilder.reset(new MotionEstimatorL1Builder(cmd, arg("gpu") == "yes", "ws-"));
else
wsMotionEstBuilder.reset(new MotionEstimatorRansacL2Builder(cmd, arg("gpu") == "yes", "ws-"));
// determine whether we must use one pass or two pass stabilizer
bool isTwoPass =
arg("est-trim") == "yes" || arg("wobble-suppress") == "yes" || arg("lin-prog-stab") == "yes";
if (isTwoPass)
{
// we must use two pass stabilizer
TwoPassStabilizer *twoPassStabilizer = new TwoPassStabilizer();
stabilizer = twoPassStabilizer;
twoPassStabilizer->setEstimateTrimRatio(arg("est-trim") == "yes");
// determine stabilization technique
if (arg("lin-prog-stab") == "yes")
{
Ptr<LpMotionStabilizer> stab = makePtr<LpMotionStabilizer>();
stab->setFrameSize(Size(source->width(), source->height()));
stab->setTrimRatio(arg("lps-trim-ratio") == "auto" ? argf("trim-ratio") : argf("lps-trim-ratio"));
stab->setWeight1(argf("lps-w1"));
stab->setWeight2(argf("lps-w2"));
stab->setWeight3(argf("lps-w3"));
stab->setWeight4(argf("lps-w4"));
twoPassStabilizer->setMotionStabilizer(stab);
}
else if (arg("stdev") == "auto")
twoPassStabilizer->setMotionStabilizer(makePtr<GaussianMotionFilter>(argi("radius")));
else
twoPassStabilizer->setMotionStabilizer(makePtr<GaussianMotionFilter>(argi("radius"), argf("stdev")));
// init wobble suppressor if necessary
if (arg("wobble-suppress") == "yes")
{
Ptr<MoreAccurateMotionWobbleSuppressorBase> ws = makePtr<MoreAccurateMotionWobbleSuppressor>();
if (arg("gpu") == "yes")
#ifdef HAVE_OPENCV_CUDAWARPING
ws = makePtr<MoreAccurateMotionWobbleSuppressorGpu>();
#else
throw runtime_error("OpenCV is built without CUDA support");
#endif
ws->setMotionEstimator(wsMotionEstBuilder->build());
ws->setPeriod(argi("ws-period"));
twoPassStabilizer->setWobbleSuppressor(ws);
MotionModel model = ws->motionEstimator()->motionModel();
if (arg("load-motions2") != "no")
{
ws->setMotionEstimator(makePtr<FromFileMotionReader>(arg("load-motions2")));
ws->motionEstimator()->setMotionModel(model);
}
if (arg("save-motions2") != "no")
{
ws->setMotionEstimator(makePtr<ToFileMotionWriter>(arg("save-motions2"), ws->motionEstimator()));
ws->motionEstimator()->setMotionModel(model);
}
}
}
else
{
// we must use one pass stabilizer
OnePassStabilizer *onePassStabilizer = new OnePassStabilizer();
stabilizer = onePassStabilizer;
if (arg("stdev") == "auto")
onePassStabilizer->setMotionFilter(makePtr<GaussianMotionFilter>(argi("radius")));
else
onePassStabilizer->setMotionFilter(makePtr<GaussianMotionFilter>(argi("radius"), argf("stdev")));
}
stabilizer->setFrameSource(source);
stabilizer->setMotionEstimator(motionEstBuilder->build());
if (arg("feature-masks") != "no")
{
Ptr<MaskFrameSource> maskSource = makePtr<MaskFrameSource>(
makePtr<VideoFileSource>(arg("feature-masks")));
std::function<void(Mat&)> maskCallback = [](Mat & inputFrame)
{
cv::cvtColor(inputFrame, inputFrame, cv::COLOR_BGR2GRAY);
threshold(inputFrame, inputFrame, 127, 255, THRESH_BINARY);
};
maskSource->setMaskCallback(maskCallback);
stabilizer->setMaskSource(maskSource);
}
// cast stabilizer to simple frame source interface to read stabilized frames
stabilizedFrames.reset(dynamic_cast<IFrameSource*>(stabilizer));
MotionModel model = stabilizer->motionEstimator()->motionModel();
if (arg("load-motions") != "no")
{
stabilizer->setMotionEstimator(makePtr<FromFileMotionReader>(arg("load-motions")));
stabilizer->motionEstimator()->setMotionModel(model);
}
if (arg("save-motions") != "no")
{
stabilizer->setMotionEstimator(makePtr<ToFileMotionWriter>(arg("save-motions"), stabilizer->motionEstimator()));
stabilizer->motionEstimator()->setMotionModel(model);
}
stabilizer->setRadius(argi("radius"));
// init deblurer
if (arg("deblur") == "yes")
{
Ptr<WeightingDeblurer> deblurer = makePtr<WeightingDeblurer>();
deblurer->setRadius(argi("radius"));
deblurer->setSensitivity(argf("deblur-sens"));
stabilizer->setDeblurer(deblurer);
}
// set up trimming parameters
stabilizer->setTrimRatio(argf("trim-ratio"));
stabilizer->setCorrectionForInclusion(arg("incl-constr") == "yes");
if (arg("border-mode") == "reflect")
stabilizer->setBorderMode(BORDER_REFLECT);
else if (arg("border-mode") == "replicate")
stabilizer->setBorderMode(BORDER_REPLICATE);
else if (arg("border-mode") == "const")
stabilizer->setBorderMode(BORDER_CONSTANT);
else
throw runtime_error("unknown border extrapolation mode: "
+ cmd.get<string>("border-mode"));
// init inpainter
InpaintingPipeline *inpainters = new InpaintingPipeline();
Ptr<InpainterBase> inpainters_(inpainters);
if (arg("mosaic") == "yes")
{
Ptr<ConsistentMosaicInpainter> inp = makePtr<ConsistentMosaicInpainter>();
inp->setStdevThresh(argf("mosaic-stdev"));
inpainters->pushBack(inp);
}
if (arg("motion-inpaint") == "yes")
{
Ptr<MotionInpainter> inp = makePtr<MotionInpainter>();
inp->setDistThreshold(argf("mi-dist-thresh"));
inpainters->pushBack(inp);
}
if (arg("color-inpaint") == "average")
inpainters->pushBack(makePtr<ColorAverageInpainter>());
else if (arg("color-inpaint") == "ns")
inpainters->pushBack(makePtr<ColorInpainter>(int(INPAINT_NS), argd("ci-radius")));
else if (arg("color-inpaint") == "telea")
inpainters->pushBack(makePtr<ColorInpainter>(int(INPAINT_TELEA), argd("ci-radius")));
else if (arg("color-inpaint") != "no")
throw runtime_error("unknown color inpainting method: " + arg("color-inpaint"));
if (!inpainters->empty())
{
inpainters->setRadius(argi("radius"));
stabilizer->setInpainter(inpainters_);
}
if (arg("output") != "no")
outputPath = arg("output");
quietMode = argb("quiet");
run();
}
catch (const exception &e)
{
cout << "error: " << e.what() << endl;
stabilizedFrames.release();
return -1;
}
stabilizedFrames.release();
return 0;
}
MotionModel motionModel(const string &str)
{
if (str == "transl")
return MM_TRANSLATION;
if (str == "transl_and_scale")
return MM_TRANSLATION_AND_SCALE;
if (str == "rigid")
return MM_RIGID;
if (str == "similarity")
return MM_SIMILARITY;
if (str == "affine")
return MM_AFFINE;
if (str == "homography")
return MM_HOMOGRAPHY;
throw runtime_error("unknown motion model: " + str);
}
| 24,507 | 7,722 |
/*
* SPDX-License-Identifier: Apache-2.0
*/
//===------ KrnlSeqStore.cpp - Lower KrnlSeqStoreOp ----------------------===//
//
// Copyright 2019-2022 The IBM Research Authors.
//
// =============================================================================
//
// This file lowers the KrnlSeqStoreOp operator.
//
//===----------------------------------------------------------------------===//
#include "mlir/Conversion/LLVMCommon/Pattern.h"
#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "src/Conversion/KrnlToLLVM/KrnlToLLVMHelper.hpp"
#include "src/Dialect/Krnl/KrnlHelper.hpp"
#include "src/Dialect/Krnl/KrnlOps.hpp"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "krnl_to_llvm"
using namespace mlir;
using namespace onnx_mlir;
namespace onnx_mlir {
namespace krnl {
class KrnlSeqStoreOpLowering : public ConversionPattern {
public:
explicit KrnlSeqStoreOpLowering(
TypeConverter &typeConverter, MLIRContext *context)
: ConversionPattern(
typeConverter, KrnlSeqStoreOp::getOperationName(), 1, context) {}
LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
KrnlSeqStoreOpAdaptor operandAdaptor(operands);
auto loc = op->getLoc();
MultiDialectBuilder<MathBuilder, MemRefBuilder> create(rewriter, loc);
// Allocate a new tensor and copy input tensor into it
auto inputType = operandAdaptor.input().getType().cast<MemRefType>();
SmallVector<mlir::Value, 4> allocParams;
for (size_t i = 0; i < inputType.getShape().size(); i++) {
if (inputType.getShape()[i] == -1) {
allocParams.emplace_back(create.mem.dim(operandAdaptor.input(), i));
}
}
Value alloc = create.mem.alignedAlloc(inputType, allocParams);
rewriter.create<memref::CopyOp>(loc, operandAdaptor.input(), alloc);
// Cast the input tensor to the element type of the sequence
auto seq = operandAdaptor.seq();
auto seqElementType =
seq.getType().cast<MemRefType>().getElementType().cast<MemRefType>();
auto casted = create.mem.cast(alloc, seqElementType);
// Store the tensor
rewriter.create<memref::StoreOp>(loc, casted, seq, operandAdaptor.index());
rewriter.eraseOp(op);
return success();
}
};
void populateLoweringKrnlSeqStoreOpPattern(TypeConverter &typeConverter,
RewritePatternSet &patterns, MLIRContext *ctx) {
patterns.insert<KrnlSeqStoreOpLowering>(typeConverter, ctx);
}
} // namespace krnl
} // namespace onnx_mlir
| 2,622 | 868 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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 "SineSource.h"
#include <binder/ProcessState.h>
#include <datasource/FileSource.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/ALooper.h>
#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/CameraSource.h>
#include <media/stagefright/MediaBufferGroup.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaCodecSource.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/MediaExtractor.h>
#include <media/stagefright/MediaExtractorFactory.h>
#include <media/stagefright/MPEG4Writer.h>
#include <media/stagefright/SimpleDecodingSource.h>
#include <media/MediaPlayerInterface.h>
#include "AudioPlayer.h"
using namespace android;
static const int32_t kAudioBitRate = 12200;
#if 0
static const int32_t kFramerate = 24; // fps
static const int32_t kIFramesIntervalSec = 1;
static const int32_t kVideoBitRate = 512 * 1024;
static const int64_t kDurationUs = 10000000LL; // 10 seconds
class DummySource : public MediaSource {
public:
DummySource(int width, int height, int colorFormat)
: mWidth(width),
mHeight(height),
mColorFormat(colorFormat),
mSize((width * height * 3) / 2) {
mGroup.add_buffer(new MediaBuffer(mSize));
// Check the color format to make sure
// that the buffer size mSize it set correctly above.
CHECK(colorFormat == OMX_COLOR_FormatYUV420SemiPlanar ||
colorFormat == OMX_COLOR_FormatYUV420Planar);
}
virtual sp<MetaData> getFormat() {
sp<MetaData> meta = new MetaData;
meta->setInt32(kKeyWidth, mWidth);
meta->setInt32(kKeyHeight, mHeight);
meta->setInt32(kKeyColorFormat, mColorFormat);
meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
return meta;
}
virtual status_t start(MetaData *params) {
mNumFramesOutput = 0;
return OK;
}
virtual status_t stop() {
return OK;
}
virtual status_t read(
MediaBuffer **buffer, const MediaSource::ReadOptions *options) {
if (mNumFramesOutput == kFramerate * 10) {
// Stop returning data after 10 secs.
return ERROR_END_OF_STREAM;
}
// printf("DummySource::read\n");
status_t err = mGroup.acquire_buffer(buffer);
if (err != OK) {
return err;
}
char x = (char)((double)rand() / RAND_MAX * 255);
memset((*buffer)->data(), x, mSize);
(*buffer)->set_range(0, mSize);
(*buffer)->meta_data()->clear();
(*buffer)->meta_data()->setInt64(
kKeyTime, (mNumFramesOutput * 1000000) / kFramerate);
++mNumFramesOutput;
// printf("DummySource::read - returning buffer\n");
// ALOGI("DummySource::read - returning buffer");
return OK;
}
protected:
virtual ~DummySource() {}
private:
MediaBufferGroup mGroup;
int mWidth, mHeight;
int mColorFormat;
size_t mSize;
int64_t mNumFramesOutput;;
DummySource(const DummySource &);
DummySource &operator=(const DummySource &);
};
sp<MediaSource> createSource(const char *filename) {
sp<MediaSource> source;
sp<MediaExtractor> extractor =
MediaExtractorFactory::Create(new FileSource(filename));
if (extractor == NULL) {
return NULL;
}
size_t num_tracks = extractor->countTracks();
sp<MetaData> meta;
for (size_t i = 0; i < num_tracks; ++i) {
meta = extractor->getTrackMetaData(i);
CHECK(meta.get() != NULL);
const char *mime;
if (!meta->findCString(kKeyMIMEType, &mime)) {
continue;
}
if (strncasecmp(mime, "video/", 6)) {
continue;
}
source = extractor->getTrack(i);
break;
}
return source;
}
enum {
kYUV420SP = 0,
kYUV420P = 1,
};
// returns -1 if mapping of the given color is unsuccessful
// returns an omx color enum value otherwise
static int translateColorToOmxEnumValue(int color) {
switch (color) {
case kYUV420SP:
return OMX_COLOR_FormatYUV420SemiPlanar;
case kYUV420P:
return OMX_COLOR_FormatYUV420Planar;
default:
fprintf(stderr, "Unsupported color: %d\n", color);
return -1;
}
}
int main(int argc, char **argv) {
android::ProcessState::self()->startThreadPool();
#if 1
if (argc != 3) {
fprintf(stderr, "usage: %s <filename> <input_color_format>\n", argv[0]);
fprintf(stderr, " <input_color_format>: 0 (YUV420SP) or 1 (YUV420P)\n");
return 1;
}
int colorFormat = translateColorToOmxEnumValue(atoi(argv[2]));
if (colorFormat == -1) {
fprintf(stderr, "input color format must be 0 (YUV420SP) or 1 (YUV420P)\n");
return 1;
}
status_t err = OK;
#if 0
sp<MediaSource> source = createSource(argv[1]);
if (source == NULL) {
fprintf(stderr, "Unable to find a suitable video track.\n");
return 1;
}
sp<MetaData> meta = source->getFormat();
sp<MediaSource> decoder = SimpleDecodingSource::Create(source);
int width, height;
bool success = meta->findInt32(kKeyWidth, &width);
success = success && meta->findInt32(kKeyHeight, &height);
CHECK(success);
#else
int width = 720;
int height = 480;
sp<MediaSource> decoder = new DummySource(width, height, colorFormat);
#endif
sp<AMessage> enc_meta = new AMessage;
// enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
// enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
enc_meta->setInt32("width", width);
enc_meta->setInt32("height", height);
enc_meta->setInt32("sample-rate", kFramerate);
enc_meta->setInt32("bitrate", kVideoBitRate);
// enc_meta->setInt32("stride", width);
// enc_meta->setInt32("slice-height", height);
enc_meta->setInt32("i-frame-interval", kIFramesIntervalSec);
enc_meta->setInt32("color-format", colorFormat);
sp<MediaSource> encoder =
MediaCodecSource::Create(looper, format, decoder);
#if 1
sp<MPEG4Writer> writer = new MPEG4Writer("/sdcard/output.mp4");
writer->addSource(encoder);
writer->setMaxFileDuration(kDurationUs);
CHECK_EQ((status_t)OK, writer->start());
while (!writer->reachedEOS()) {
fprintf(stderr, ".");
usleep(100000);
}
err = writer->stop();
#else
CHECK_EQ((status_t)OK, encoder->start());
MediaBuffer *buffer;
while (encoder->read(&buffer) == OK) {
printf(".");
fflush(stdout);
int32_t isSync;
if (!buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isSync)) {
isSync = false;
}
printf("got an output frame of size %d%s\n", buffer->range_length(),
isSync ? " (SYNC)" : "");
buffer->release();
buffer = NULL;
}
err = encoder->stop();
#endif
printf("$\n");
#endif
#if 0
CameraSource *source = CameraSource::Create(
String16(argv[0], strlen(argv[0])));
source->start();
printf("source = %p\n", source);
for (int i = 0; i < 100; ++i) {
MediaBuffer *buffer;
status_t err = source->read(&buffer);
CHECK_EQ(err, (status_t)OK);
printf("got a frame, data=%p, size=%d\n",
buffer->data(), buffer->range_length());
buffer->release();
buffer = NULL;
}
err = source->stop();
delete source;
source = NULL;
#endif
if (err != OK && err != ERROR_END_OF_STREAM) {
fprintf(stderr, "record failed: %d\n", err);
return 1;
}
return 0;
}
#else
int main(int /* argc */, char ** /* argv */) {
android::ProcessState::self()->startThreadPool();
const int32_t kSampleRate = 22050;
const int32_t kNumChannels = 2;
sp<MediaSource> audioSource = new SineSource(kSampleRate, kNumChannels);
#if 0
sp<MediaPlayerBase::AudioSink> audioSink;
AudioPlayer *player = new AudioPlayer(audioSink);
player->setSource(audioSource);
player->start();
sleep(10);
player->stop();
#endif
sp<AMessage> encMeta = new AMessage;
encMeta->setString("mime",
0 ? MEDIA_MIMETYPE_AUDIO_AMR_WB : MEDIA_MIMETYPE_AUDIO_AAC);
encMeta->setInt32("sample-rate", kSampleRate);
encMeta->setInt32("channel-count", kNumChannels);
encMeta->setInt32("max-input-size", 8192);
encMeta->setInt32("bitrate", kAudioBitRate);
sp<ALooper> looper = new ALooper;
looper->setName("record");
looper->start();
sp<MediaSource> encoder =
MediaCodecSource::Create(looper, encMeta, audioSource);
encoder->start();
int32_t n = 0;
status_t err;
MediaBufferBase *buffer;
while ((err = encoder->read(&buffer)) == OK) {
printf(".");
fflush(stdout);
buffer->release();
buffer = NULL;
if (++n == 100) {
break;
}
}
printf("$\n");
encoder->stop();
return 0;
}
#endif
| 9,754 | 3,412 |
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fxfa/app/xfa_ffdraw.h"
#include "xfa/fxfa/xfa_ffapp.h"
#include "xfa/fxfa/xfa_ffdoc.h"
#include "xfa/fxfa/xfa_ffpageview.h"
#include "xfa/fxfa/xfa_ffwidget.h"
CXFA_FFDraw::CXFA_FFDraw(CXFA_WidgetAcc* pDataAcc) : CXFA_FFWidget(pDataAcc) {}
CXFA_FFDraw::~CXFA_FFDraw() {}
| 529 | 229 |
#include "coolpropsolver.h"
#include "CoolPropTools.h"
#include "CoolProp.h"
#include "CPState.h"
#include <iostream>
#include <string>
#include <stdlib.h>
CoolPropSolver::CoolPropSolver(const std::string& mediumName, const std::string& libraryName, const std::string& substanceName)
: BaseSolver(mediumName, libraryName, substanceName) {
// Fluid name can be used to pass in other parameters.
// The string can be composed like "Propane|enable_TTSE=1|calc_transport=0"
std::vector<std::string> name_options = strsplit(substanceName, '|');
// Set the defaults
fluidType = -1;
enable_TTSE = false;
debug_level = 0;
calc_transport = false;
extend_twophase = false;
twophase_derivsmoothing_xend = 0;
rho_smoothing_xend = 0;
if (name_options.size() > 1) {
for (unsigned int i = 1; i < name_options.size(); i++) {
// Split around the equals sign
std::vector<std::string> param_val = strsplit(name_options[i], '=');
if (param_val.size() != 2) {
errorMessage((char*)format("Could not parse the option [%s], must be in the form param=value", name_options[i].c_str()).c_str());
}
// Check each of the options in turn
if (!param_val[0].compare("enable_TTSE")) {
if (!param_val[1].compare("1") || !param_val[1].compare("true")) {
std::cout << "TTSE is on\n";
enable_TTSE = true;
} else if (!param_val[1].compare("0") || !param_val[1].compare("false")) {
std::cout << "TTSE is off\n";
enable_TTSE = false;
} else
errorMessage((char*)format("I don't know how to handle this option [%s]", name_options[i].c_str()).c_str());
//throw NotImplementedError((char*)format("I don't know how to handle this option [%s]",name_options[i].c_str()).c_str());
} else if (!param_val[0].compare("calc_transport")) {
if (!param_val[1].compare("1") || !param_val[1].compare("true"))
calc_transport = true;
else if (!param_val[1].compare("0") || !param_val[1].compare("false"))
calc_transport = false;
else
errorMessage((char*)format("I don't know how to handle this option [%s]", name_options[i].c_str()).c_str());
} else if (!param_val[0].compare("enable_EXTTP")) {
if (!param_val[1].compare("1") || !param_val[1].compare("true"))
extend_twophase = true;
else if (!param_val[1].compare("0") || !param_val[1].compare("false"))
extend_twophase = false;
else
errorMessage((char*)format("I don't know how to handle this option [%s]", name_options[i].c_str()).c_str());
} else if (!param_val[0].compare("twophase_derivsmoothing_xend")) {
twophase_derivsmoothing_xend = strtod(param_val[1].c_str(), NULL);
if (twophase_derivsmoothing_xend < 0 || twophase_derivsmoothing_xend > 1)
errorMessage(
(char*)format("I don't know how to handle this twophase_derivsmoothing_xend value [%d]", param_val[0].c_str()).c_str());
} else if (!param_val[0].compare("rho_smoothing_xend")) {
rho_smoothing_xend = strtod(param_val[1].c_str(), NULL);
if (rho_smoothing_xend < 0 || rho_smoothing_xend > 1)
errorMessage((char*)format("I don't know how to handle this rho_smoothing_xend value [%d]", param_val[0].c_str()).c_str());
} else if (!param_val[0].compare("debug")) {
debug_level = (int)strtol(param_val[1].c_str(), NULL, 0);
if (debug_level < 0 || debug_level > 1000)
errorMessage((char*)format("I don't know how to handle this debug level [%s]", param_val[0].c_str()).c_str());
} else {
errorMessage((char*)format("This option [%s] was not understood", name_options[i].c_str()).c_str());
}
// Some options were passed in, lets see what we have
std::cout << param_val[0] << " has the value of " << param_val[1] << std::endl;
}
}
// Handle the name and fill the fluid type
if (debug_level > 5) std::cout << "Checking fluid " << name_options[0] << " against database." << std::endl;
fluidType = getFluidType(name_options[0]); // Throws an error if unknown fluid
if (debug_level > 5) std::cout << "Check passed, reducing " << substanceName << " to " << name_options[0] << std::endl;
this->substanceName = name_options[0];
state = new CoolPropStateClassSI(name_options[0]);
setFluidConstants();
}
void CoolPropSolver::setFluidConstants() {
if ((fluidType == FLUID_TYPE_PURE) || (fluidType == FLUID_TYPE_PSEUDOPURE) || (fluidType == FLUID_TYPE_REFPROP)) {
if (debug_level > 5) std::cout << format("Setting constants for fluid %s \n", substanceName.c_str());
_fluidConstants.pc = PropsSI((char*)"pcrit", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str());
_fluidConstants.Tc = PropsSI((char*)"Tcrit", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str());
_fluidConstants.MM = PropsSI((char*)"molemass", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str());
_fluidConstants.dc = PropsSI((char*)"rhocrit", (char*)"T", 0, (char*)"P", 0, (char*)substanceName.c_str());
return;
}
if ((fluidType == FLUID_TYPE_INCOMPRESSIBLE_LIQUID) || (fluidType == FLUID_TYPE_INCOMPRESSIBLE_SOLUTION)) {
if (debug_level > 5) std::cout << format("Setting constants for incompressible fluid %s \n", substanceName.c_str());
_fluidConstants.pc = -1;
_fluidConstants.Tc = -1;
_fluidConstants.MM = -1;
_fluidConstants.dc = -1;
return;
}
}
void CoolPropSolver::preStateChange(void) {
/// Some common code to avoid pitfalls from incompressibles
if ((fluidType == FLUID_TYPE_PURE) || (fluidType == FLUID_TYPE_PSEUDOPURE) || (fluidType == FLUID_TYPE_REFPROP)) {
try {
if (enable_TTSE)
state->enable_TTSE_LUT();
else
state->disable_TTSE_LUT();
if (extend_twophase)
state->enable_EXTTP();
else
state->disable_EXTTP();
} catch (std::exception& e) {
errorMessage((char*)e.what());
std::cout << format("Exception from state object: %s \n", (char*)e.what());
}
}
}
void CoolPropSolver::postStateChange(ExternalThermodynamicState* const properties) {
/// Some common code to avoid pitfalls from incompressibles
switch (fluidType) {
case FLUID_TYPE_PURE:
case FLUID_TYPE_PSEUDOPURE:
case FLUID_TYPE_REFPROP:
try {
// Set the values in the output structure
properties->p = state->p();
properties->T = state->T();
properties->d = state->rho();
properties->h = state->h();
properties->s = state->s();
if (state->TwoPhase) {
properties->phase = 2;
} else {
properties->phase = 1;
}
properties->cp = state->cp();
properties->cv = state->cv();
properties->a = state->speed_sound();
if (state->TwoPhase && state->Q() >= 0 && state->Q() <= twophase_derivsmoothing_xend) {
// Use the smoothed derivatives between a quality of 0 and twophase_derivsmoothing_xend
properties->ddhp = state->drhodh_constp_smoothed(twophase_derivsmoothing_xend); // [1/kPa -- > 1/Pa]
properties->ddph = state->drhodp_consth_smoothed(twophase_derivsmoothing_xend); // [1/(kJ/kg) -- > 1/(J/kg)]
} else if (state->TwoPhase && state->Q() >= 0 && state->Q() <= rho_smoothing_xend) {
// Use the smoothed density between a quality of 0 and rho_smoothing_xend
double rho_spline;
double dsplinedh;
double dsplinedp;
state->rho_smoothed(rho_smoothing_xend, rho_spline, dsplinedh, dsplinedp);
properties->ddhp = dsplinedh;
properties->ddph = dsplinedp;
properties->d = rho_spline;
} else {
properties->ddhp = state->drhodh_constp();
properties->ddph = state->drhodp_consth();
}
properties->kappa = state->isothermal_compressibility();
properties->beta = state->isobaric_expansion_coefficient();
if (calc_transport) {
properties->eta = state->viscosity();
properties->lambda = state->conductivity(); //[kW/m/K --> W/m/K]
} else {
properties->eta = -_HUGE;
properties->lambda = -_HUGE;
}
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
break;
case FLUID_TYPE_INCOMPRESSIBLE_LIQUID:
case FLUID_TYPE_INCOMPRESSIBLE_SOLUTION:
try {
// Set the values in the output structure
properties->p = state->p();
properties->T = state->T();
properties->d = state->rho();
properties->h = state->h();
properties->s = state->s();
properties->phase = 1;
properties->cp = state->cp();
properties->cv = state->cv();
properties->a = -_HUGE;
properties->ddhp = state->drhodh_constp();
properties->ddph = 0.0; // TODO: Fix this
properties->kappa = -_HUGE;
properties->beta = -_HUGE;
if (calc_transport) {
properties->eta = state->viscosity();
properties->lambda = state->conductivity(); //[kW/m/K --> W/m/K]
} else {
properties->eta = -_HUGE;
properties->lambda = -_HUGE;
}
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
break;
default:
errorMessage((char*)"Invalid fluid type!");
break;
}
}
void CoolPropSolver::setSat_p(double& p, ExternalSaturationProperties* const properties) {
if (debug_level > 5) std::cout << format("setSat_p(%0.16e)\n", p);
this->preStateChange();
try {
state->update(iP, p, iQ, 0); // quality only matters for pseudo-pure fluids
//! Saturation temperature
properties->Tsat = state->TL(); // Not correct for pseudo-pure fluids
//! Derivative of Ts wrt pressure
properties->dTp = state->dTdp_along_sat();
//! Derivative of dls wrt pressure
properties->ddldp = state->drhodp_along_sat_liquid();
//! Derivative of dvs wrt pressure
properties->ddvdp = state->drhodp_along_sat_vapor();
//! Derivative of hls wrt pressure
properties->dhldp = state->dhdp_along_sat_liquid();
//! Derivative of hvs wrt pressure
properties->dhvdp = state->dhdp_along_sat_vapor();
//! Density at bubble line (for pressure ps)
properties->dl = state->rhoL();
//! Density at dew line (for pressure ps)
properties->dv = state->rhoV();
//! Specific enthalpy at bubble line (for pressure ps)
properties->hl = state->hL();
//! Specific enthalpy at dew line (for pressure ps)
properties->hv = state->hV();
//! Saturation pressure
properties->psat = p;
//! Surface tension
properties->sigma = state->surface_tension();
//! Specific entropy at bubble line (for pressure ps)
properties->sl = state->sL();
//! Specific entropy at dew line (for pressure ps)
properties->sv = state->sV();
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
void CoolPropSolver::setSat_T(double& T, ExternalSaturationProperties* const properties) {
if (debug_level > 5) std::cout << format("setSat_T(%0.16e)\n", T);
this->preStateChange();
try {
state->update(iT, T, iQ, 0); // Quality only matters for pseudo-pure fluids
properties->Tsat = T;
properties->psat = state->p();
properties->dl = state->rhoL();
properties->dv = state->rhoV();
properties->hl = state->hL();
properties->hv = state->hV();
properties->dTp = state->dTdp_along_sat();
properties->ddldp = state->drhodp_along_sat_liquid();
properties->ddvdp = state->drhodp_along_sat_vapor();
properties->dhldp = state->dhdp_along_sat_liquid();
properties->dhvdp = state->dhdp_along_sat_vapor();
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
// Note: the phase input is currently not supported
void CoolPropSolver::setState_ph(double& p, double& h, int& phase, ExternalThermodynamicState* const properties) {
if (debug_level > 5) std::cout << format("setState_ph(p=%0.16e,h=%0.16e)\n", p, h);
this->preStateChange();
try {
// Update the internal variables in the state instance
state->update(iP, p, iH, h);
if (!ValidNumber(state->rho()) || !ValidNumber(state->T())) {
throw ValueError(format("p-h [%g, %g] failed for update", p, h));
}
// Set the values in the output structure
this->postStateChange(properties);
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
void CoolPropSolver::setState_pT(double& p, double& T, ExternalThermodynamicState* const properties) {
if (debug_level > 5) std::cout << format("setState_pT(p=%0.16e,T=%0.16e)\n", p, T);
this->preStateChange();
try {
// Update the internal variables in the state instance
state->update(iP, p, iT, T);
// Set the values in the output structure
this->postStateChange(properties);
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
// Note: the phase input is currently not supported
void CoolPropSolver::setState_dT(double& d, double& T, int& phase, ExternalThermodynamicState* const properties) {
if (debug_level > 5) std::cout << format("setState_dT(d=%0.16e,T=%0.16e)\n", d, T);
this->preStateChange();
try {
// Update the internal variables in the state instance
state->update(iD, d, iT, T);
// Set the values in the output structure
this->postStateChange(properties);
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
// Note: the phase input is currently not supported
void CoolPropSolver::setState_ps(double& p, double& s, int& phase, ExternalThermodynamicState* const properties) {
if (debug_level > 5) std::cout << format("setState_ps(p=%0.16e,s=%0.16e)\n", p, s);
this->preStateChange();
try {
// Update the internal variables in the state instance
state->update(iP, p, iS, s);
// Set the values in the output structure
this->postStateChange(properties);
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
// Note: the phase input is currently not supported
void CoolPropSolver::setState_hs(double& h, double& s, int& phase, ExternalThermodynamicState* const properties) {
if (debug_level > 5) std::cout << format("setState_hs(h=%0.16e,s=%0.16e)\n", h, s);
this->preStateChange();
try {
// Update the internal variables in the state instance
state->update(iH, h, iS, s);
// Set the values in the output structure
this->postStateChange(properties);
} catch (std::exception& e) {
errorMessage((char*)e.what());
}
}
double CoolPropSolver::Pr(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: Pr() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: Pr() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::T(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: T() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: T() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::a(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: a() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: a() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::beta(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: beta() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: beta() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::cp(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: cp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: cp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::cv(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: cv() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: cv() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::d(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: d() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: d() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::ddhp(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: ddhp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: ddhp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::ddph(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: ddph() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: ddph() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::eta(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: eta() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: eta() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::h(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: h() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: h() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::kappa(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: kappa() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: kappa() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::lambda(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: lambda() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: lambda() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::p(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: p() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: p() not implemented in the Solver object");
return -_HUGE;
}
int CoolPropSolver::phase(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: phase() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: phase() not implemented in the Solver object");
return -1;
}
double CoolPropSolver::s(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: s() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: s() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::d_der(ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: d_der() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: d_der() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::isentropicEnthalpy(double& p, ExternalThermodynamicState* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: isentropicEnthalpy() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: isentropicEnthalpy() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::dTp(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: dTp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: dTp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::ddldp(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: ddldp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: ddldp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::ddvdp(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: ddvdp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: ddvdp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::dhldp(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: dhldp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: dhldp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::dhvdp(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: dhvdp() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: dhvdp() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::dl(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: dl() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: dl() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::dv(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: dv() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: dv() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::hl(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: hl() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: hl() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::hv(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: hv() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: hv() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::sigma(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: sigma() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: sigma() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::sl(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: sl() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: sl() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::sv(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: sv() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: sv() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::psat(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: psat() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: psat() not implemented in the Solver object");
return -_HUGE;
}
double CoolPropSolver::Tsat(ExternalSaturationProperties* const properties) {
// Base function returns an error if called - should be redeclared by the solver object
errorMessage((char*)"Internal error: Tsat() not implemented in the Solver object");
//throw NotImplementedError((char*)"Internal error: Tsat() not implemented in the Solver object");
return -_HUGE;
}
| 28,376 | 8,415 |
#include <iostream>
using namespace std;
int main ()
{
int n, arr[10000];
// INPUT HOW MUCH NUMBER TO INPUT
cout << "Numbers?: "; cin >> n;
// INPUT THE NUMBERS
for (int i=0; i<n; i++)
{
cin >> arr[i];
}
// SELECTION SORT ALGORITHM (ASCENDING)
for (int i=0; i<n-1; i++)
{
int min_index = i;
for(int j=i+1; j<n; j++)
{
if (arr[j] < arr[min_index]) // CHECKING GREATER OR SMALLER
{
min_index = j;
}
int temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
}
cout << "ASCENDING: ";
// THE RESULT AFTER ASCENDING SORTING USING SELECTION SORT
for (int i=0; i<n; i++)
{
cout << arr[i] << " ";
}
cout << "\n";
// SELECTION SORT ALGORITHM (DESCENDING)
for (int i=0; i<n-1; i++)
{
int min_index = i;
for(int j=i+1; j<n; j++)
{
if (arr[j] > arr[min_index]) // CHECKING GREATER OR SMALLER
{
min_index = j;
}
int temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
}
cout << "DESCENDING: ";
// THE RESULT AFTER DESCENDING SORTING USING SELECTION SORT
for (int i=0; i<n; i++)
{
cout << arr[i] << " ";
}
cout << "\n";
return 0;
}
| 1,151 | 595 |
/*
* Copyright (C) 2020 CESNET, https://photonics.cesnet.cz/
*
* Written by Jan Kundrát <jan.kundrat@cesnet.cz>, Tomáš Pecka <tomas.pecka@fit.cvut.cz>
*
*/
extern "C" {
#include <sysrepo.h>
}
#include <cinttypes>
#include <cstdio>
#include <cxxabi.h>
#include <spdlog/sinks/systemd_sink.h>
#include <sys/stat.h>
#include <unistd.h>
#include "logging.h"
extern "C" {
/** @short Propagate sysrepo events to spdlog */
static void spdlog_sr_log_cb(sr_log_level_t level, const char* message)
{
// Thread safety note: this is, as far as I know, thread safe:
// - the static initialization itself is OK
// - all loggers which we instantiate are thread-safe
// - std::shared_ptr::operator-> is const, and all const members of that class are documented to be thread-safe
static auto log = spdlog::get("sysrepo");
assert(log);
switch (level) {
case SR_LL_NONE:
case SR_LL_ERR:
log->error(message);
break;
case SR_LL_WRN:
log->warn(message);
break;
case SR_LL_INF:
log->info(message);
break;
case SR_LL_DBG:
log->debug(message);
break;
}
}
}
namespace lldp::utils {
/** @short Initialize logging
Creates and registers all required loggers and connect them to the provided sink.
*/
void initLogs(std::shared_ptr<spdlog::sinks::sink> sink)
{
auto defaultLogger = std::make_shared<spdlog::logger>("lldp-systemd-sysrepo", sink);
spdlog::register_logger(defaultLogger);
spdlog::set_default_logger(defaultLogger);
spdlog::register_logger(std::make_shared<spdlog::logger>("sysrepo", sink));
sr_log_set_cb(spdlog_sr_log_cb);
}
/** @short Is stderr connected to journald? Not thread safe. */
bool isJournaldActive()
{
const auto stream = ::getenv("JOURNAL_STREAM");
if (!stream) {
return false;
}
uintmax_t dev;
uintmax_t inode;
if (::sscanf(stream, "%" SCNuMAX ":%" SCNuMAX, &dev, &inode) != 2) {
return false;
}
struct stat buf;
if (fstat(STDERR_FILENO, &buf)) {
return false;
}
return static_cast<uintmax_t>(buf.st_dev) == dev && static_cast<uintmax_t>(buf.st_ino) == inode;
}
namespace impl {
/** @short Provide better levels, see https://github.com/gabime/spdlog/pull/1292#discussion_r340777258 */
template <typename Mutex>
class journald_sink : public spdlog::sinks::systemd_sink<Mutex> {
public:
journald_sink()
{
this->syslog_levels_ = {/* spdlog::level::trace */ LOG_DEBUG,
/* spdlog::level::debug */ LOG_INFO,
/* spdlog::level::info */ LOG_NOTICE,
/* spdlog::level::warn */ LOG_WARNING,
/* spdlog::level::err */ LOG_ERR,
/* spdlog::level::critical */ LOG_CRIT,
/* spdlog::level::off */ LOG_ALERT};
}
};
}
std::shared_ptr<spdlog::sinks::sink> create_journald_sink()
{
return std::make_shared<impl::journald_sink<std::mutex>>();
}
/** @short Log that everything is screwed up and rethrow
The purpose is to make sure that a nicely formatted error message gets stored into the journald buffer with a high enough priority.
*/
void fatalException [[noreturn]] (std::shared_ptr<spdlog::logger> log, const std::exception& e, const std::string& when)
{
int demangled;
char* classname = __cxxabiv1::__cxa_demangle(typeid(e).name(), nullptr, 0, &demangled);
log->critical("Fatal error in {}: {}", when, demangled == 0 ? classname : typeid(e).name());
log->critical("{}", e.what());
free(classname);
throw;
}
} /* namespace lldp::utils */
| 3,717 | 1,289 |
/* Copyright 2021 NVIDIA 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 "cunumeric/pitches.h"
namespace cunumeric {
using namespace Legion;
using namespace legate;
template <int32_t OUT_DIM, int32_t IN_DIM>
__CUDA_HD__ inline Point<IN_DIM> get_tile_point(const Point<OUT_DIM>& point,
const Point<IN_DIM>& strides)
{
Point<IN_DIM> result;
for (int32_t out_idx = OUT_DIM - 1, in_idx = IN_DIM - 1; in_idx >= 0; --out_idx, --in_idx)
result[in_idx] = point[out_idx] % strides[in_idx];
return result;
}
template <VariantKind KIND, typename VAL, int32_t OUT_DIM, int32_t IN_DIM>
struct TileImplBody;
template <VariantKind KIND, typename VAL>
struct TileImpl {
template <int32_t OUT_DIM, int32_t IN_DIM, std::enable_if_t<IN_DIM <= OUT_DIM>* = nullptr>
void operator()(TileArgs& args) const
{
const auto out_rect = args.out.shape<OUT_DIM>();
Pitches<OUT_DIM - 1> out_pitches;
auto out_volume = out_pitches.flatten(out_rect);
if (out_volume == 0) return;
const auto in_rect = args.in.shape<IN_DIM>();
Point<IN_DIM> in_strides = in_rect.hi + Point<IN_DIM>::ONES();
auto out = args.out.write_accessor<VAL, OUT_DIM>();
auto in = args.in.read_accessor<VAL, IN_DIM>();
TileImplBody<KIND, VAL, OUT_DIM, IN_DIM>{}(
out_rect, out_pitches, out_volume, in_strides, out, in);
}
template <int32_t OUT_DIM, int32_t IN_DIM, std::enable_if_t<!(IN_DIM <= OUT_DIM)>* = nullptr>
void operator()(TileArgs& args) const
{
assert(false);
}
};
template <VariantKind KIND>
struct TileDispatch {
template <LegateTypeCode CODE>
void operator()(TileArgs& args) const
{
using VAL = legate_type_of<CODE>;
double_dispatch(args.out.dim(), args.in.dim(), TileImpl<KIND, VAL>{}, args);
}
};
template <VariantKind KIND>
static void tile_template(TaskContext& context)
{
TileArgs args{context.inputs()[0], context.outputs()[0]};
type_dispatch(args.in.code(), TileDispatch<KIND>{}, args);
}
} // namespace cunumeric
| 2,571 | 966 |
/*
* Copyright (C) 2009, Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/ros.h"
#include "ros/callback_queue.h"
#include "std_msgs/String.h"
#include <boost/thread.hpp>
/**
* This tutorial demonstrates the use of custom separate callback queues that can be processed
* independently, whether in different threads or just at different times.
*/
/**
* This callback gets called from the main queue processed in spin()
*/
void chatterCallbackMainQueue(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO_STREAM("I heard: [ " << msg->data << "] in thread [" << boost::this_thread::get_id() << "] (Main thread)");
}
/**
* This callback gets called from the custom queue
*/
void chatterCallbackCustomQueue(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO_STREAM("I heard: [ " << msg->data << "] in thread [" << boost::this_thread::get_id() << "]");
}
/**
* The custom queue used for one of the subscription callbacks
*/
ros::CallbackQueue g_queue;
void callbackThread()
{
ROS_INFO_STREAM("Callback thread id=" << boost::this_thread::get_id());
ros::NodeHandle n;
while (n.ok())
{
g_queue.callAvailable(ros::WallDuration(0.01));
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener_with_custom_callback_processing");
ros::NodeHandle n;
/**
* The SubscribeOptions structure lets you specify a custom queue to use for a specific subscription.
* You can also set a default queue on a NodeHandle using the NodeHandle::setCallbackQueue() function.
*
* AdvertiseOptions and AdvertiseServiceOptions offer similar functionality.
*/
ros::SubscribeOptions ops = ros::SubscribeOptions::create<std_msgs::String>("chatter", 1000,
chatterCallbackCustomQueue,
ros::VoidPtr(), &g_queue);
ros::Subscriber sub = n.subscribe(ops);
/**
* Now we subscribe using the normal method, to demonstrate the difference.
*/
ros::Subscriber sub2 = n.subscribe("chatter", 1000, chatterCallbackMainQueue);
/**
* Start a thread to service the custom queue
*/
boost::thread chatter_thread(callbackThread);
ROS_INFO_STREAM("Main thread id=" << boost::this_thread::get_id());
/**
* Now do a custom spin, to demonstrate the difference.
*/
ros::Rate r(1);
while (n.ok())
{
ros::spinOnce();
r.sleep();
}
chatter_thread.join();
return 0;
}
| 4,009 | 1,281 |
/*
* Copyright (C) 2015 midnightBITS
*
* 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 "pch.h"
#include <gui/animation.hpp>
namespace ani {
struct actor {
actor(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration, uint32_t counts);
~actor();
const std::shared_ptr<animation>& target() const;
void start();
bool step();
private:
using clock = std::chrono::high_resolution_clock;
std::shared_ptr<animation> m_target;
clock::duration m_duration;
uint32_t m_counts;
clock::time_point m_startTime;
};
actor::actor(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration, uint32_t counts)
: m_target(target)
, m_duration(duration)
, m_counts(counts)
{
}
actor::~actor()
{
m_target->shutdown();
}
const std::shared_ptr<animation>& actor::target() const
{
return m_target;
}
void actor::start()
{
m_target->init();
m_startTime = clock::now();
}
bool actor::step()
{
auto now = clock::now();
auto running = now - m_startTime;
if (m_counts && (running / m_duration > m_counts))
return false;
auto timeframe = running % m_duration;
auto frame = animation::step_max * timeframe / m_duration;
m_target->step((uint32_t)frame);
return true;
}
void scene::animate(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration, uint32_t counts)
{
if (!target)
return;
remove(target);
std::lock_guard<std::mutex> guard(m_mtx);
auto animator = std::make_shared<actor>(target, duration, counts);
animator->start();
m_actors.push_back(std::move(animator));
}
void scene::animate(const std::shared_ptr<animation>& target, std::chrono::milliseconds duration)
{
return animate(target, duration, 0);
}
void scene::remove(const std::shared_ptr<animation>& target)
{
if (!target)
return;
std::lock_guard<std::mutex> guard(m_mtx);
auto it = std::find_if(std::begin(m_actors), std::end(m_actors), [&](const std::shared_ptr<actor>& ptr) {
return ptr->target() == target;
});
if (it == std::end(m_actors))
return;
m_actors.erase(it);
return;
}
bool scene::step()
{
std::lock_guard<std::mutex> guard(m_mtx);
auto it = std::begin(m_actors), end = std::end(m_actors);
while (it != end) {
auto& actor = *it;
if (!actor->step()) {
it = m_actors.erase(it);
end = std::end(m_actors);
} else {
++it;
}
}
return !m_actors.empty();
}
}
| 3,479 | 1,334 |
/*
Name: QtRpt
Version: 1.5.5
Web-site: http://www.qtrpt.tk
Programmer: Aleksey Osipov
E-mail: aliks-os@ukr.net
Web-site: http://www.aliks-os.tk
Copyright 2012-2015 Aleksey Osipov
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 "TContainerLine.h"
#include "ReportBand.h"
TContainerLine::TContainerLine(QWidget *parent, QPoint p, QWidget *cWidget) : RptContainer(parent,p,cWidget) {
QString stl = "TContainerLine#lbl {;"
"border-width:1px;"
"border-style:solid;"
"border-color:rgba(0,0,0,255);"
"border-top-color:rgba(0,0,0,255);"
"border-left-color:rgba(0,0,0,255);"
"border-right-color:rgba(0,0,0,255);"
"border-bottom-color:rgba(0,0,0,255);"
"color:rgba(0,0,0,255);"
"background-color:rgba(255,255,255,0);"
"}";
cs = 0;
ce = 0;
m_arrowStart = false;
m_arrowEnd = true;
this->setStyleSheet(stl);
this->resize(10,10);
this->setBaseSize(width(),height());
this->allowResize(false);
this->allowDrawSelection(false);
this->setAutoFillBackground(true);
this->move(-50,-50);
line.setP1( QPoint() );
line.setP2( QPoint() );
QPalette Pal(palette());
Pal.setColor(QPalette::Background, Qt::blue);
cs = new XYZContainer(parent,QPoint(line.p1().x(), line.p2().y()));
cs->setObjectName("CS");
cs->resize(6,6);
cs->allowResize(false);
cs->allowDrawSelection(false);
cs->setVisible(false);
cs->setAutoFillBackground(true);
cs->setPalette(Pal);
ce = new XYZContainer(parent,QPoint(line.p2().x(), line.p2().y()));
ce->setObjectName("CE");
ce->resize(6,6);
ce->allowResize(false);
ce->allowDrawSelection(false);
ce->setVisible(false);
ce->setAutoFillBackground(true);
ce->setPalette(Pal);
QObject::connect(cs, SIGNAL(newGeometry(QRect, QRect)), this, SIGNAL(newGeometry(QRect, QRect)));
QObject::connect(ce, SIGNAL(newGeometry(QRect, QRect)), this, SIGNAL(newGeometry(QRect, QRect)));
QObject::connect(ce, SIGNAL(newGeometry(QRect, QRect)), this, SLOT(lineChanged(QRect, QRect)));
QObject::connect(cs, SIGNAL(newGeometry(QRect, QRect)), this, SLOT(lineChanged(QRect, QRect)));
//QObject::connect(cs, SIGNAL(geomChanged(QRect, QRect)), this, SIGNAL(geomChanged(QRect, QRect)));
//QObject::connect(ce, SIGNAL(geomChanged(QRect, QRect)), this, SIGNAL(geomChanged(QRect, QRect)));
QObject::connect(cs, SIGNAL(geomChanged(QRect, QRect)), this, SLOT(geomContChanged(QRect, QRect)));
QObject::connect(ce, SIGNAL(geomChanged(QRect, QRect)), this, SLOT(geomContChanged(QRect, QRect)));
QObject::connect(cs, SIGNAL(destroyed()), this, SLOT(delItemInTree()));
QObject::connect(ce, SIGNAL(destroyed()), this, SLOT(delItemInTree()));
QObject::connect(this, SIGNAL(delCont(QTreeWidgetItem *)), this, SLOT(delItemInTree()));
QObject::connect(cs, SIGNAL(inFocus(bool)), this, SLOT(m_inFocus(bool)));
QObject::connect(ce, SIGNAL(inFocus(bool)), this, SLOT(m_inFocus(bool)));
//QObject::connect(this, SIGNAL(inFocus(bool)), cs, SIGNAL(inFocus(bool)));
//QObject::connect(this, SIGNAL(inFocus(bool)), ce, SIGNAL(inFocus(bool)));
this->show();
}
void TContainerLine::geomContChanged(QRect oldRect, QRect newRect) {
if (sender() == cs) {
m_oldP1 = oldRect;
m_oldP2 = ce->geometry();
}
if (sender() == ce) {
m_oldP1 = cs->geometry();
m_oldP2 = oldRect;
}
emit geomChanged(oldRect,newRect);
}
void TContainerLine::delItemInTree() {
delete this;
}
void TContainerLine::setArrow(Command command, QVariant value) {
if (command == ArrowStart)
m_arrowStart = value.toBool();
if (command ==ArrowEnd)
m_arrowEnd = value.toBool();
this->parentWidget()->repaint();
}
bool TContainerLine::getArrow(Command command) {
bool result = false;
if (command == ArrowStart)
result = m_arrowStart;
if (command ==ArrowEnd)
result = m_arrowEnd;
return result;
}
void TContainerLine::focusInEvent(QFocusEvent *e) {
XYZContainer::focusInEvent(e);
setLine(true);
}
void TContainerLine::focusOutEvent(QFocusEvent *e) {
XYZContainer::focusInEvent(e);
if (cs != 0 && ce != 0)
setSelectedLine(QPoint(0,0));
}
void TContainerLine::m_inFocus(bool value) {
setLine(value);
emit inFocus(value);
}
void TContainerLine::setLine(bool value) {
QPalette pal(Qt::white);
bool selected = false;
if (value) {
pal.setColor(QPalette::Background, Qt::blue);
selected = true;
}
ce->setPalette(pal);
cs->setPalette(pal);
ce->setVisible(selected);
cs->setVisible(selected);
}
void TContainerLine::setSelectedLine(QPoint point) {
QList<TContainerLine *> contLineList = this->parentWidget()->findChildren<TContainerLine *>();
foreach (TContainerLine *contLine, contLineList) {
bool selected = false;
QPointF intersectPnt;
QLineF line(point.x()-5, point.y()-5, point.x()+5, point.y()+5);
if (contLine->line.intersect(line, &intersectPnt) == QLineF::BoundedIntersection) {
if (!contLine->hasFocus()) {
contLine->setFocus();
}
selected = true;
}
if (contLine->ce->hasFocus() && this->ce->rect().contains(point)) {
selected = true;
}
if (contLine->cs->hasFocus() && this->cs->rect().contains(point)) {
selected = true;
}
contLine->setLine(selected);
}
}
void TContainerLine::lineChanged(QRect, QRect) {
if (cs != 0 && !cs->pos().isNull())
line.setP1( cs->pos()+QPoint(3,3) );
if (ce != 0 && !ce->pos().isNull())
line.setP2( ce->pos()+QPoint(3,3) );
}
void TContainerLine::movePoint(XYZContainer *cont, QRect rect) {
cont->move(rect.x(),rect.y());
lineChanged(QRect(),QRect());
this->parentWidget()->repaint();
}
void TContainerLine::setParent(QWidget *parent) {
RptContainer::setParent(parent);
ce->setParent(parent);
cs->setParent(parent);
}
void TContainerLine::setObjectName(const QString &name) {
const QString old_name = this->objectName();
QObject::setObjectName(name);
QString str = this->styleSheet().replace("lbl",name).replace(old_name,name);
this->setStyleSheet(str);
}
void TContainerLine::loadParamFromXML(QDomElement e) {
RptContainer::loadParamFromXML(e);
//this->setSheetValue(BackgroundColor,e.attribute("backgroundColor","rgba(255,255,255,0)"));
this->setSheetValue(BorderColor,e.attribute("borderColor","rgba(0,0,0,255)"));
this->line.setP1(QPointF(e.attribute("lineStartX","0").toDouble(), e.attribute("lineStartY","0" ).toDouble()));
this->line.setP2(QPointF(e.attribute("lineEndX","0").toDouble(), e.attribute("lineEndY","0" ).toDouble()));
this->m_arrowStart = e.attribute("arrowStart","0").toInt();
this->m_arrowEnd = e.attribute("arrowEnd","0").toInt();
this->cs->move(this->line.toLine().p1()-QPoint(3,3));
this->ce->move(this->line.toLine().p2()-QPoint(3,3));
}
QDomElement TContainerLine::saveParamToXML(QDomDocument *xmlDoc) {
QDomElement elem = RptContainer::saveParamToXML(xmlDoc);
QString borderColor = colorToString(getColorValue(BorderColor));
elem.setAttribute("borderColor",borderColor);
elem.setAttribute("borderStyle",getBorderStyleStr());
elem.setAttribute("lineStartX",this->line.p1().x());
elem.setAttribute("lineStartY",this->line.p1().y());
elem.setAttribute("lineEndX",this->line.p2().x());
elem.setAttribute("lineEndY",this->line.p2().y());
elem.setAttribute("arrowStart",this->m_arrowStart);
elem.setAttribute("arrowEnd",this->m_arrowEnd);
return elem;
}
void TContainerLine::setMenu(QMenu *menu_) {
QIcon icon;
QAction *actContDel = new QAction(tr("Delete"),this);
icon.addPixmap(QPixmap(QString::fromUtf8(":/new/prefix1/images/delete.png")), QIcon::Normal, QIcon::On);
actContDel->setObjectName("actContDel");
actContDel->setIcon(icon);
QObject::connect(actContDel, SIGNAL(triggered()), this, SIGNAL(deleteByUser()));
QObject::connect(actContDel, SIGNAL(triggered()), this, SLOT(deleteLater()));
menu->clear();
menu->insertActions(0,menu_->actions());
menu->addAction(actContDel);
}
TContainerLine *TContainerLine::clone() {
TContainerLine *newContField = new TContainerLine(this->parentWidget(),QPoint(0,0),0);
newContField->setType(this->getType());
newContField->setStyleSheet(this->styleSheet());
newContField->setGeometry(this->geometry());
newContField->setBaseSize(this->baseSize());
newContField->setVisible(true);
newContField->move(-10,-10);
newContField->line.setP1( this->line.p1()+QPointF(5,5));
newContField->line.setP2( this->line.p2()+QPointF(5,5));
newContField->cs->move( this->cs->pos()+QPoint(5,5) );
newContField->ce->move( this->ce->pos()+QPoint(5,5) );
newContField->setArrow(ArrowStart, this->getArrow(ArrowStart));
newContField->setArrow(ArrowEnd, this->getArrow(ArrowEnd));
newContField->setColorValue(BorderColor,this->getColorValue(BorderColor));
newContField->setBorderWidth(this->getBorderWidth());
return newContField;
}
qreal TContainerLine::getLength() {
return line.length();
}
void TContainerLine::drawArrow(QPainter *painter) {
// Draw the arrows
static const double Pi = 3.14159265358979323846264338327950288419717;
static double TwoPi = 2.0 * Pi;
double angle = ::acos(line.dx() / line.length());
if (line.dy() >= 0)
angle = TwoPi - angle;
QPointF sourcePoint = line.p1();
QPointF destPoint = line.p2();
int arrowSize= 10;
painter->setBrush(getColorValue(BorderColor));
if (m_arrowStart) {
QPointF sourceArrowP1 = sourcePoint + QPointF(sin(angle + Pi / 3) * arrowSize,
cos(angle + Pi / 3) * arrowSize);
QPointF sourceArrowP2 = sourcePoint + QPointF(sin(angle + Pi - Pi / 3) * arrowSize,
cos(angle + Pi - Pi / 3) * arrowSize);
painter->drawPolygon(QPolygonF() << line.p1() << sourceArrowP1 << sourceArrowP2);
}
if (m_arrowEnd) {
QPointF destArrowP1 = destPoint + QPointF(sin(angle - Pi / 3) * arrowSize,
cos(angle - Pi / 3) * arrowSize);
QPointF destArrowP2 = destPoint + QPointF(sin(angle - Pi + Pi / 3) * arrowSize,
cos(angle - Pi + Pi / 3) * arrowSize);
painter->drawPolygon(QPolygonF() << line.p2() << destArrowP1 << destArrowP2);
}
}
TContainerLine::~TContainerLine() {
if (cs != 0) {
cs->deleteLater();
cs = 0;
}
if (ce != 0) {
ce->deleteLater();
ce = 0;
}
}
void TContainerLine::setProperties() {
this->setProperty("FieldType",m_type);
}
//Restore fields from properties
void TContainerLine::setParamFromProperties() {
m_type = (FieldType)this->property("FieldType").toInt();
}
QDataStream &operator<<(QDataStream &stream, const TContainerLine &obj) {
for(int i=0; i<obj.metaObject()->propertyCount(); ++i) {
if(obj.metaObject()->property(i).isStored(&obj)) {
stream << obj.metaObject()->property(i).read(&obj);
}
}
QList<QByteArray> list = obj.dynamicPropertyNames();
for (int i=0; i<list.size(); i++) {
stream << obj.property(list.at(i));
}
stream << *obj.cs;
stream << *obj.ce;
return stream;
}
QDataStream &operator>>(QDataStream &stream, TContainerLine &obj) {
QVariant var;
for(int i=0; i<obj.metaObject()->propertyCount(); ++i) {
if(obj.metaObject()->property(i).isStored(&obj)) {
stream >> var;
if (!var.isNull())
obj.metaObject()->property(i).write(&obj, var);
}
}
obj.setProperties();
QList<QByteArray> list = obj.dynamicPropertyNames();
for (int i=0; i<list.size(); i++) {
stream >> var;
obj.setProperty(list.at(i),QVariant(var));
}
obj.setParamFromProperties();
stream >> *obj.cs;
stream >> *obj.ce;
return stream;
}
| 12,830 | 4,474 |
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2019
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/net/SessionProxy.h"
#include "td/telegram/Global.h"
#include "td/telegram/net/ConnectionCreator.h"
#include "td/telegram/net/DcId.h"
#include "td/telegram/net/NetQueryDispatcher.h"
#include "td/telegram/net/Session.h"
#include "td/telegram/UniqueId.h"
#include "td/actor/PromiseFuture.h"
#include "td/utils/common.h"
#include "td/utils/logging.h"
#include "td/utils/Slice.h"
#include <functional>
namespace td {
namespace mtproto {
class RawConnection;
} // namespace mtproto
class SessionCallback : public Session::Callback {
public:
SessionCallback(ActorShared<SessionProxy> parent, DcId dc_id, bool allow_media_only, bool is_media, size_t hash)
: parent_(std::move(parent))
, dc_id_(dc_id)
, allow_media_only_(allow_media_only)
, is_media_(is_media)
, hash_(hash) {
}
void on_failed() override {
send_closure(parent_, &SessionProxy::on_failed);
}
void on_closed() override {
send_closure(parent_, &SessionProxy::on_closed);
}
void request_raw_connection(unique_ptr<mtproto::AuthData> auth_data,
Promise<unique_ptr<mtproto::RawConnection>> promise) override {
send_closure(G()->connection_creator(), &ConnectionCreator::request_raw_connection, dc_id_, allow_media_only_,
is_media_, std::move(promise), hash_, std::move(auth_data));
}
void on_tmp_auth_key_updated(mtproto::AuthKey auth_key) override {
send_closure(parent_, &SessionProxy::on_tmp_auth_key_updated, std::move(auth_key));
}
void on_server_salt_updated(std::vector<mtproto::ServerSalt> server_salts) override {
send_closure(parent_, &SessionProxy::on_server_salt_updated, std::move(server_salts));
}
void on_result(NetQueryPtr query) override {
if (UniqueId::extract_type(query->id()) != UniqueId::BindKey &&
query->id() != 0) { // not bind key query and not an update
send_closure(parent_, &SessionProxy::on_query_finished);
}
G()->net_query_dispatcher().dispatch(std::move(query));
}
private:
ActorShared<SessionProxy> parent_;
DcId dc_id_;
bool allow_media_only_ = false;
bool is_media_ = false;
size_t hash_ = 0;
};
SessionProxy::SessionProxy(unique_ptr<Callback> callback, std::shared_ptr<AuthDataShared> shared_auth_data,
bool is_main, bool allow_media_only, bool is_media, bool use_pfs, bool is_cdn,
bool need_destroy)
: callback_(std::move(callback))
, auth_data_(std::move(shared_auth_data))
, is_main_(is_main)
, allow_media_only_(allow_media_only)
, is_media_(is_media)
, use_pfs_(use_pfs)
, is_cdn_(is_cdn)
, need_destroy_(need_destroy) {
}
void SessionProxy::start_up() {
class Listener : public AuthDataShared::Listener {
public:
explicit Listener(ActorShared<SessionProxy> session_proxy) : session_proxy_(std::move(session_proxy)) {
}
bool notify() override {
if (!session_proxy_.is_alive()) {
return false;
}
send_closure(session_proxy_, &SessionProxy::update_auth_key_state);
return true;
}
private:
ActorShared<SessionProxy> session_proxy_;
};
auth_key_state_ = auth_data_->get_auth_key_state().first;
auth_data_->add_auth_key_listener(make_unique<Listener>(actor_shared(this)));
open_session();
}
void SessionProxy::tear_down() {
for (auto &query : pending_queries_) {
query->resend();
callback_->on_query_finished();
G()->net_query_dispatcher().dispatch(std::move(query));
}
pending_queries_.clear();
}
void SessionProxy::send(NetQueryPtr query) {
if (query->auth_flag() == NetQuery::AuthFlag::On && auth_key_state_ != AuthKeyState::OK) {
query->debug(PSTRING() << get_name() << ": wait for auth");
pending_queries_.emplace_back(std::move(query));
return;
}
open_session(true);
query->debug(PSTRING() << get_name() << ": sent to session");
send_closure(session_, &Session::send, std::move(query));
}
void SessionProxy::update_main_flag(bool is_main) {
if (is_main_ == is_main) {
return;
}
LOG(INFO) << "Update " << get_name() << " is_main to " << is_main;
is_main_ = is_main;
close_session();
open_session();
}
void SessionProxy::update_destroy(bool need_destroy) {
need_destroy_ = need_destroy;
close_session();
open_session();
}
void SessionProxy::on_failed() {
if (session_generation_ != get_link_token()) {
return;
}
close_session();
open_session();
}
void SessionProxy::update_mtproto_header() {
close_session();
open_session();
}
void SessionProxy::on_closed() {
}
void SessionProxy::close_session() {
send_closure(std::move(session_), &Session::close);
session_generation_++;
}
void SessionProxy::open_session(bool force) {
if (!session_.empty()) {
return;
}
// There are several assumption that make this code OK
// 1. All unauthorized query will be sent into the same SessionProxy
// 2. All authorized query are delayed before we have authorization
// So only one SessionProxy will be active before we have authorization key
auto should_open = [&]() {
if (force) {
return true;
}
if (need_destroy_) {
return auth_key_state_ != AuthKeyState::Empty;
}
if (auth_key_state_ != AuthKeyState::OK) {
return false;
}
return is_main_ || !pending_queries_.empty();
}();
if (!should_open) {
return;
}
CHECK(session_.empty());
auto dc_id = auth_data_->dc_id();
string name = PSTRING() << "Session" << get_name().substr(Slice("SessionProxy").size());
string hash_string = PSTRING() << name << " " << dc_id.get_raw_id() << " " << allow_media_only_;
auto hash = std::hash<std::string>()(hash_string);
int32 int_dc_id = dc_id.get_raw_id();
if (G()->is_test_dc()) {
int_dc_id += 10000;
}
if (allow_media_only_ && !is_cdn_) {
int_dc_id = -int_dc_id;
}
session_ = create_actor<Session>(
name,
make_unique<SessionCallback>(actor_shared(this, session_generation_), dc_id, allow_media_only_, is_media_, hash),
auth_data_, int_dc_id, is_main_, use_pfs_, is_cdn_, need_destroy_, tmp_auth_key_, server_salts_);
}
void SessionProxy::update_auth_key_state() {
auto old_auth_key_state = auth_key_state_;
auth_key_state_ = auth_data_->get_auth_key_state().first;
if (auth_key_state_ != old_auth_key_state && old_auth_key_state == AuthKeyState::OK) {
close_session();
}
open_session();
if (session_.empty() || auth_key_state_ != AuthKeyState::OK) {
return;
}
for (auto &query : pending_queries_) {
query->debug(PSTRING() << get_name() << ": sent to session");
send_closure(session_, &Session::send, std::move(query));
}
pending_queries_.clear();
}
void SessionProxy::on_tmp_auth_key_updated(mtproto::AuthKey auth_key) {
Slice state;
if (auth_key.empty()) {
state = Slice("Empty");
} else if (auth_key.auth_flag()) {
state = Slice("OK");
} else {
state = Slice("NoAuth");
}
LOG(WARNING) << "Have tmp_auth_key " << auth_key.id() << ": " << state;
tmp_auth_key_ = std::move(auth_key);
}
void SessionProxy::on_server_salt_updated(std::vector<mtproto::ServerSalt> server_salts) {
server_salts_ = std::move(server_salts);
}
void SessionProxy::on_query_finished() {
callback_->on_query_finished();
}
} // namespace td
| 7,573 | 2,651 |
// RUN: %clang_cc1 -verify -fopenmp %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd %s -Wuninitialized
typedef void **omp_allocator_handle_t;
extern const omp_allocator_handle_t omp_default_mem_alloc;
extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
extern const omp_allocator_handle_t omp_const_mem_alloc;
extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
extern const omp_allocator_handle_t omp_pteam_mem_alloc;
extern const omp_allocator_handle_t omp_thread_mem_alloc;
void xxx(int argc) {
int i, step; // expected-note {{initialize the variable 'step' to silence this warning}}
#pragma omp target teams distribute parallel for simd linear(i : step) // expected-warning {{variable 'step' is uninitialized when used here}}
for (i = 0; i < 10; ++i)
;
}
namespace X {
int x;
};
struct B {
static int ib; // expected-note {{'B::ib' declared here}}
static int bfoo() { return 8; }
};
int bfoo() { return 4; }
int z;
const int C1 = 1;
const int C2 = 2;
void test_linear_colons()
{
int B = 0;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(B:bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(B::ib:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'}}
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(B:ib) // expected-error {{use of undeclared identifier 'ib'; did you mean 'B::ib'}}
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(z:B:ib) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}}
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(B:B::bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(X::x : ::z)
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 3 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(B,::z, X::x)
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(::z)
for (int i = 0; i < 10; ++i) ;
#pragma omp target teams distribute parallel for simd linear(B::bfoo()) // expected-error {{expected variable name}}
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 2 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(B::ib,B:C1+C2)
for (int i = 0; i < 10; ++i) ;
}
template<int L, class T, class N> T test_template(T* arr, N num) {
N i;
T sum = (T)0;
T ind2 = - num * L; // expected-note {{'ind2' defined here}}
#pragma omp target teams distribute parallel for simd linear(ind2:L) // expected-error {{argument of a linear clause should be of integral or pointer type}}
for (i = 0; i < num; ++i) {
T cur = arr[(int)ind2];
ind2 += L;
sum += cur;
}
return T();
}
template<int LEN> int test_warn() {
int ind2 = 0;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(ind2:LEN) // expected-warning {{zero linear step (ind2 should probably be const)}}
for (int i = 0; i < 100; i++) {
ind2 += LEN;
}
return ind2;
}
struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}}
extern S1 a;
class S2 {
mutable int a;
public:
S2():a(0) { }
};
const S2 b; // expected-note 2 {{'b' defined here}}
const S2 ba[5];
class S3 {
int a;
public:
S3():a(0) { }
};
const S3 ca[5];
class S4 {
int a;
S4();
public:
S4(int v):a(v) { }
};
class S5 {
int a;
S5():a(0) {}
public:
S5(int v):a(v) { }
};
S3 h;
#pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}}
template<class I, class C> int foomain(I argc, C **argv) {
I e(4);
I g(5);
int i;
int &j = i;
#pragma omp target teams distribute parallel for simd linear // expected-error {{expected '(' after 'linear'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear () // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear (argc : 5) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (a, b:B::ib) // expected-error {{linear variable with incomplete type 'S1'}} expected-error {{argument of a linear clause should be of integral or pointer type, not 'S2'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 2 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(e, g)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear(h) // expected-error {{threadprivate or thread local variable cannot be linear}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear(i)
for (int k = 0; k < argc; ++k) ++k;
return 0;
}
namespace A {
double x;
#pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}}
}
namespace C {
using A::x;
}
int main(int argc, char **argv) {
double darr[100];
// expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}}
test_template<-4>(darr, 4);
// expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}}
test_warn<0>();
S4 e(4); // expected-note {{'e' defined here}}
S5 g(5); // expected-note {{'g' defined here}}
int i;
int &j = i;
#pragma omp target teams distribute parallel for simd linear // expected-error {{expected '(' after 'linear'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear () // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+1 {{only loop iteration variables are allowed in 'linear' clause in distribute directives}}
#pragma omp target teams distribute parallel for simd linear (argc)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (a, b) // expected-error {{linear variable with incomplete type 'S1'}} expected-error {{argument of a linear clause should be of integral or pointer type, not 'S2'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear (argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear(e, g) // expected-error {{argument of a linear clause should be of integral or pointer type, not 'S4'}} expected-error {{argument of a linear clause should be of integral or pointer type, not 'S5'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp target teams distribute parallel for simd linear(h, C::x) // expected-error 2 {{threadprivate or thread local variable cannot be linear}}
for (int k = 0; k < argc; ++k) ++k;
foomain<int,char>(argc,argv); // expected-note {{in instantiation of function template specialization 'foomain<int, char>' requested here}}
return 0;
}
| 11,455 | 3,784 |
// Copyright (c) YugaByte, 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 "yb/util/random_util.h"
#include "yb/util/scope_exit.h"
#include "yb/util/size_literals.h"
#include "yb/yql/pgwrapper/libpq_utils.h"
#include "yb/yql/pgwrapper/libpq_test_base.h"
#include "yb/common/common.pb.h"
using namespace std::literals;
DECLARE_int64(external_mini_cluster_max_log_bytes);
namespace yb {
namespace pgwrapper {
class PgOnConflictTest : public LibPqTestBase {
protected:
void TestOnConflict(bool kill_master, const MonoDelta& duration);
};
namespace {
struct OnConflictKey {
int key;
int operation_index = 0;
};
constexpr int kMaxBatchSize = 5;
struct BatchInfo {
int key;
char append_char; // Zero means read request
std::string read_value;
std::string ToString() const {
if (append_char) {
char x[2] = {append_char, 0};
return Format("[$0+$1]", key, x);
} else {
return Format("[$0 $1]", key, read_value);
}
}
bool ComesBefore(const BatchInfo& rhs) const {
if (key != rhs.key) {
return false;
}
if (append_char) {
if (rhs.append_char) {
return false;
}
// rhs see our append
return rhs.read_value.find(append_char) != std::string::npos;
} else if (!rhs.append_char) {
// rhs has larger list
return read_value.length() < rhs.read_value.length();
} else {
// we don't see the result of rhs
return read_value.find(rhs.append_char) == std::string::npos;
}
}
};
struct TransactionInfo {
typedef std::array<BatchInfo, kMaxBatchSize> Batches;
typedef Batches::const_iterator const_iterator;
int batch_size = 0;
Batches batches;
int last_visit = 0; // Used to check whether this vertex was visited by current DFS run.
const_iterator begin() const {
return batches.begin();
}
const_iterator end() const {
return batches.begin() + batch_size;
}
bool ComesBefore(const TransactionInfo& rhs) const {
for (const auto& lbatch : *this) {
for (const auto& rbatch : rhs) {
if (lbatch.ComesBefore(rbatch)) {
return true;
}
}
}
return false;
}
};
class OnConflictHelper {
public:
explicit OnConflictHelper(size_t concurrent_keys)
: concurrent_keys_(concurrent_keys), active_keys_(concurrent_keys) {
for(size_t i = 0; i != concurrent_keys; ++i) {
active_keys_[i].key = ++next_key_;
}
for (auto i = 'A'; i <= 'Z'; ++i) {
chars_.push_back(i);
}
}
std::pair<int, char> RandomPair() {
size_t i = RandomUniformInt<size_t>(0, concurrent_keys_ - 1);
std::lock_guard<std::mutex> lock(mutex_);
auto& key = active_keys_[i];
char append_char;
if (RandomUniformBool()) {
append_char = 0; // Read key
} else {
append_char = chars_[key.operation_index];
if (++key.operation_index == chars_.size()) {
key.key = ++next_key_;
key.operation_index = 0;
}
}
return std::make_pair(key.key, append_char);
}
void Committed(TransactionInfo&& info) {
std::lock_guard<std::mutex> lock(mutex_);
committed_.push_back(std::move(info));
}
void Report() {
LOG(INFO) << "Committed transactions:";
ordered_.reserve(committed_.size());
// Iteration order does not matter here, so we iterate from end to have lower keys at the start
// of the list.
for (auto it = committed_.rbegin(); it != committed_.rend(); ++it) {
if (it->last_visit == 0) {
DepthFirstSearch(&*it, nullptr /* dest */);
}
}
std::reverse(ordered_.begin(), ordered_.end());
for (const auto* info : ordered_) {
LOG(INFO) << " " << yb::ToString(*info);
}
int inversions = 0;
for (auto it = ordered_.begin(); it != ordered_.end(); ++it) {
for (auto j = ordered_.begin(); j != it; ++j) {
if ((**it).ComesBefore(**j)) {
LOG(INFO) << "Order inversion: " << yb::ToString(**it) << " and " << yb::ToString(**j);
++inversions;
++query_;
DepthFirstSearch(*j, *it);
}
}
}
ASSERT_EQ(inversions, 0);
}
private:
// Returns true if dest was reached.
bool DepthFirstSearch(TransactionInfo* v, TransactionInfo* dest) {
v->last_visit = query_;
if (v == dest) {
LOG(INFO) << " " << yb::ToString(*v);
return true;
}
for (auto& target : committed_) {
if (target.last_visit < query_ && v->ComesBefore(target)) {
if (DepthFirstSearch(&target, dest)) {
LOG(INFO) << " " << yb::ToString(*v);
return true;
}
}
}
if (!dest) {
ordered_.push_back(v);
}
return false;
}
const size_t concurrent_keys_;
std::string chars_;
std::mutex mutex_;
int next_key_ = 0;
std::vector<OnConflictKey> active_keys_;
std::vector<TransactionInfo> committed_;
std::vector<TransactionInfo*> ordered_;
// Number of depth-first search run, used to filter visited vertexes.
int query_ = 1;
};
} // anonymous namespace
// Check that INSERT .. ON CONFLICT .. does not generate duplicate key errors.
void PgOnConflictTest::TestOnConflict(bool kill_master, const MonoDelta& duration) {
#ifndef NDEBUG
constexpr int kWriters = RegularBuildVsSanitizers(15, 5);
#else
constexpr int kWriters = 25;
#endif
auto conn = ASSERT_RESULT(Connect());
ASSERT_OK(conn.Execute("CREATE TABLE test (k int PRIMARY KEY, v TEXT)"));
std::atomic<int> processed(0);
TestThreadHolder thread_holder;
OnConflictHelper helper(3);
for (int i = 0; i != kWriters; ++i) {
thread_holder.AddThreadFunctor(
[this, &stop = thread_holder.stop_flag(), &processed, &helper] {
SetFlagOnExit set_flag_on_exit(&stop);
auto conn = ASSERT_RESULT(Connect());
char value[2] = "0";
while (!stop.load(std::memory_order_acquire)) {
int batch_size = RandomUniformInt(2, kMaxBatchSize);
TransactionInfo transaction_info;
transaction_info.batch_size = batch_size;
bool ok = false;
if (batch_size != 1) {
ASSERT_OK(conn.Execute("START TRANSACTION ISOLATION LEVEL SERIALIZABLE"));
}
auto se = ScopeExit([&conn, batch_size, &ok, &processed, &helper, &transaction_info] {
if (batch_size != 1) {
if (ok) {
auto status = conn.Execute("COMMIT");
if (status.ok()) {
++processed;
helper.Committed(std::move(transaction_info));
return;
}
auto msg = status.message().ToBuffer();
if (msg.find("Transaction expired") == std::string::npos &&
msg.find("Transaction aborted") == std::string::npos) {
ASSERT_OK(status);
}
}
ASSERT_OK(conn.Execute("ROLLBACK"));
} else if (ok) {
// To re-enable this we need to decrease the lower bound of batch_size to 1.
++processed;
}
});
ok = true;
for (int j = 0; j != batch_size; ++j) {
auto key_and_appended_char = helper.RandomPair();
Status status;
auto& current_batch = transaction_info.batches[j];
current_batch.key = key_and_appended_char.first;
current_batch.append_char = key_and_appended_char.second;
if (key_and_appended_char.second) {
value[0] = key_and_appended_char.second;
status = conn.ExecuteFormat(
"INSERT INTO test (k, v) VALUES ($0, '$1') ON CONFLICT (K) DO "
"UPDATE SET v = CONCAT(test.v, '$1')",
key_and_appended_char.first, value);
} else {
auto result = conn.FetchFormat(
"SELECT v FROM test WHERE k = $0", key_and_appended_char.first);
if (!result.ok()) {
status = result.status();
} else {
auto tuples = PQntuples(result->get());
if (tuples == 1) {
ASSERT_EQ(PQnfields(result->get()), 1);
current_batch.read_value = ASSERT_RESULT(
GetString(result->get(), 0, 0));
} else {
ASSERT_EQ(tuples, 0);
}
}
}
if (status.ok()) {
continue;
}
ok = false;
if (TransactionalFailure(status)) {
break;
}
auto msg = status.message().ToBuffer();
if (msg.find("Snapshot too old: Snapshot too old.") != std::string::npos ||
msg.find("Commit of expired transaction") != std::string::npos ||
msg.find("Catalog Version Mismatch") != std::string::npos ||
msg.find("Soft memory limit exceeded") != std::string::npos ||
msg.find("Missing metadata for transaction") != std::string::npos ||
msg.find("timed out after deadline expired") != std::string::npos) {
break;
}
ASSERT_OK(status);
}
}
});
}
if (!kill_master) {
thread_holder.WaitAndStop(duration.ToSteadyDuration());
} else {
// Every 15 seconds, pick a random master, then kill it if it is running, otherwise resume it.
auto deadline = CoarseMonoClock::now() + duration;
int num_masters = cluster_->num_masters();
while (!thread_holder.stop_flag().load(std::memory_order_acquire)) {
MonoDelta left(deadline - CoarseMonoClock::now());
if (left < MonoDelta::kZero) {
break;
}
auto* master = cluster_->master(RandomUniformInt(0, num_masters - 1));
if (master->IsProcessAlive()) {
std::this_thread::sleep_for(
std::min(left, MonoDelta(20s) * kTimeMultiplier).ToSteadyDuration());
LOG(INFO) << "Killing: " << master->uuid();
master->Shutdown();
} else {
std::this_thread::sleep_for(
std::min(left, MonoDelta(15s)).ToSteadyDuration());
LOG(INFO) << "Resuming: " << master->uuid();
ASSERT_OK(master->Start());
}
int live_masters = 0;
for (int i = 0; i != num_masters; ++i) {
if (cluster_->master(i)->IsProcessAlive()) {
++live_masters;
}
}
LOG(INFO) << "Live masters: " << live_masters;
}
for (int i = 0; i != num_masters; ++i) {
if (!cluster_->master(i)->IsProcessAlive()) {
ASSERT_OK(cluster_->master(i)->Start());
}
}
thread_holder.Stop();
}
for (;;) {
auto res = conn.Fetch("SELECT * FROM test ORDER BY k");
if (!res.ok()) {
ASSERT_TRUE(TransactionalFailure(res.status())) << res.status();
continue;
}
int cols = PQnfields(res->get());
ASSERT_EQ(cols, 2);
int rows = PQntuples(res->get());
for (int i = 0; i != rows; ++i) {
auto key = GetInt32(res->get(), i, 0);
auto value = GetString(res->get(), i, 1);
LOG(INFO) << " " << key << ": " << value;
}
LOG(INFO) << "Total processed: " << processed.load(std::memory_order_acquire);
break;
}
helper.Report();
}
TEST_F(PgOnConflictTest, YB_DISABLE_TEST_IN_TSAN(OnConflict)) {
TestOnConflict(false /* kill_master */, 120s);
}
TEST_F(PgOnConflictTest, YB_DISABLE_TEST_IN_TSAN(OnConflictWithKillMaster)) {
TestOnConflict(true /* kill_master */, 180s);
}
// When auto-commit fails block state switched to TBLOCK_ABORT.
// But correct state in this case is TBLOCK_DEFAULT.
// https://github.com/YugaByte/yugabyte-db/commit/73e966e5735efc21bf2ad43f9d961a488afbe050
TEST_F(PgOnConflictTest, YB_DISABLE_TEST_IN_TSAN(NoTxnOnConflict)) {
constexpr int kWriters = 5;
constexpr int kKeys = 20;
auto conn = ASSERT_RESULT(Connect());
ASSERT_OK(conn.Execute("CREATE TABLE test (k int PRIMARY KEY, v TEXT)"));
TestThreadHolder thread_holder;
for (int i = 0; i != kWriters; ++i) {
thread_holder.AddThreadFunctor([this, &stop = thread_holder.stop_flag()] {
SetFlagOnExit set_flag_on_exit(&stop);
auto conn = ASSERT_RESULT(Connect());
char value[2] = "0";
while (!stop.load(std::memory_order_acquire)) {
int key = RandomUniformInt(1, kKeys);
value[0] = RandomUniformInt('A', 'Z');
auto status = conn.ExecuteFormat(
"INSERT INTO test (k, v) VALUES ($0, '$1') ON CONFLICT (K) DO "
"UPDATE SET v = CONCAT(test.v, '$1')",
key, value);
if (status.ok() || TransactionalFailure(status)) {
continue;
}
ASSERT_OK(status);
}
});
}
thread_holder.WaitAndStop(30s);
LogResult(ASSERT_RESULT(conn.Fetch("SELECT * FROM test ORDER BY k")).get());
}
TEST_F(PgOnConflictTest, YB_DISABLE_TEST_IN_TSAN(ValidSessionAfterTxnCommitConflict)) {
auto conn = ASSERT_RESULT(Connect());
ASSERT_OK(conn.Execute("CREATE TABLE test (k int PRIMARY KEY)"));
ASSERT_OK(conn.Execute("BEGIN"));
ASSERT_OK(conn.Execute("INSERT INTO test VALUES(1)"));
auto extra_conn = ASSERT_RESULT(Connect());
ASSERT_OK(extra_conn.Execute("INSERT INTO test VALUES(1)"));
ASSERT_NOK(conn.Execute("COMMIT"));
// Check connection is in valid state after failed COMMIT
auto value = ASSERT_RESULT(GetInt32(ASSERT_RESULT(conn.Fetch("SELECT * FROM test")).get(), 0, 0));
ASSERT_EQ(value, 1);
}
} // namespace pgwrapper
} // namespace yb
| 13,817 | 4,640 |
#include "gamecredits.hpp"
CGameCredits::CGameCredits ( SDL_Renderer * r )
{
SDL_Surface * aux;
#if _WIN32 || _WIN64
char path[FILENAME_MAX], bg_path[FILENAME_MAX];
char p2[FILENAME_MAX];
_getcwd(p2, sizeof(p2));
#else
char path[1024], bg_path[1024];
#endif
#if _WIN32 || _WIN64
#ifndef PREFIX
sprintf(path, "%s\\fonts\\inhouseedition.ttf", p2);
#else
sprintf(path, "%s\\dangeroustux\\fonts\\inhouseedition.ttf", PREFIX);
#endif
#else
#ifndef PREFIX
sprintf(path, "./fonts/inhouseedition.ttf");
#else
sprintf(path, "%s/share/games/dangeroustux/fonts/inhouseedition.ttf", PREFIX);
#endif
#endif
if (!Writer::instance()->load_font(path, path, 100))
throw "CGameCredits: não foi possível carregar font\n";
Writer::instance()->set_renderer(r);
char s[5][32] =
{
{71,82,65,80,72,73,67,83},
{71,85,83,84,65,86,79,32,77,69,68,69,73,82,79,83},
{80,82,79,71,82,65,77,77,73,78,71},
{83,65,77,85,69,76,32,76,69,79,78,65,82,68,79},
{84,72,73,65,71,79,32,72,85,80,78,69,82},
};
GuiLabel * g = new GuiLabel(s[0], (SDL_Color){255,255,255,0});
widget.add_child(g);
GuiLabel * gg = new GuiLabel(s[1], (SDL_Color){255,255,0,0});
widget.add_child(gg);
GuiLabel * p = new GuiLabel(s[2], (SDL_Color){255,255,255,0});
widget.add_child(p);
GuiLabel * ps = new GuiLabel(s[3], (SDL_Color){255,255,0,0});
widget.add_child(ps);
GuiLabel * t = new GuiLabel(s[4], (SDL_Color){255,255,0,0});
widget.add_child(t);
widget.set_pos(Vect(960/2,624/2));
int h = g->get_texture_height() + gg->get_texture_height() + p->get_texture_height() + ps->get_texture_height();
g->set_rel_pos(Vect(-(g->get_texture_width()/2), h));
gg->set_rel_pos(Vect(-(gg->get_texture_width()/2), g->get_texture_height() + g->get_rel_pos().y));
p->set_rel_pos(Vect(-(p->get_texture_width()/2), gg->get_texture_height() + gg->get_rel_pos().y));
ps->set_rel_pos(Vect(-(ps->get_texture_width()/2), p->get_texture_height() + p->get_rel_pos().y));
t->set_rel_pos(Vect(-(t->get_texture_width()/2), ps->get_texture_height() + ps->get_rel_pos().y));
#if _WIN32 || _WIN64
#ifndef PREFIX
sprintf(path, "%s\\images\\tux_walk.png", p2);
#else
sprintf(path, "%s\\dangeroustux\\images\\tux_walk.png", PREFIX);
#endif
#else
#ifndef PREFIX
sprintf(path, "./images/tux_walk.png");
#else
sprintf(path, "%s/share/games/dangeroustux/images/tux_walk.png", PREFIX);
#endif
#endif
#if _WIN32 || _WIN64
#ifndef PREFIX
sprintf(bg_path, "%s\\images\\credits_BG.png", p2);
#else
sprintf(bg_path, "%s\\dangeroustux\\images\\credits_BG.png", PREFIX);
#endif
#else
#ifndef PREFIX
sprintf(bg_path, "./images/credits_BG.png");
#else
sprintf(bg_path, "%s/share/games/dangeroustux/images/credits_BG.png", PREFIX);
#endif
#endif
anim.add_frame(NULL, (SDL_Rect){0,0,0,0}, 15000);
SDL_Texture * texture = IMG_LoadTexture(r, path);
if (!texture)
throw "CGameCredits: não foi possivel carregar tux_walk.png\n";
tux_anim.add_frame(texture, (SDL_Rect){0, 0,214,234}, 200);
tux_anim.add_frame(texture, (SDL_Rect){0, 234,214,234}, 200); // meio
tux_anim.add_frame(texture, (SDL_Rect){0,2*234,214,234}, 200);
tux_anim.add_frame(texture, (SDL_Rect){0, 234,214,234}, 200); // meio
//tux_pos.x = widget.get_pos().x - texture_width(texture)/2;
tux_pos.x = (960 - texture_width(texture))/2;
if (!bg.set_texture(IMG_LoadTexture(r, bg_path)))
throw "CGameCredits: não foi possível carregar credits_BG.png\n";
//widget.set_pos(Vect(960/2, 358/2));
tux_pos.y = 358;
cam = new Camera((SDL_Rect){0,0,texture_width(bg.get_texture()),texture_height(bg.get_texture())}, (SDL_Rect){0,0,2000*texture_width(bg.get_texture()),texture_height(bg.get_texture())});
set_state(ACTIVE_CREDITS);
}
CGameCredits::~CGameCredits ( )
{
Widget * w = widget.get_child(0);
for (int i = 0; w; i++, w = widget.get_child(i))
delete w;
delete cam;
tux_anim.destroy_textures();
}
void CGameCredits::draw ( SDL_Renderer * renderer )
{
SDL_SetRenderDrawColor(renderer, 0x00,0xc6,0xff,0xFF);
SDL_RenderFillRect(renderer, NULL);
bg.draw_hor(renderer, cam);
tux_anim.draw(renderer, tux_pos.x, tux_pos.y);
widget.draw(renderer);
}
void CGameCredits::reset ( )
{
bg_pos.zero();
cam->set_position(Vect());
anim.reset();
tux_anim.reset();
set_state(ACTIVE_CREDITS);
}
int CGameCredits::update ( )
{
bg_pos.x += 5.50f;
cam->set_position(bg_pos);
auto children = widget.get_children();
for (auto child : children){
auto pos = child->get_pos();
if (pos.y < -1000) break;
pos.y -= 2.5f;
child->set_pos(pos);
}
widget.child_update();
widget.update();
tux_anim.update();
if (anim.update() == 3)
set_state(INACTIVE_CREDITS);
return get_state();
}
| 4,753 | 2,433 |
//////////////////////////////////////////////////////////////////////////
#include <polysolve/FEMSolver.hpp>
#include <catch2/catch.hpp>
#include <iostream>
#include <unsupported/Eigen/SparseExtra>
#include <fstream>
#include <vector>
#include <ctime>
#include <polysolve/LinearSolverAMGCL.hpp>
//////////////////////////////////////////////////////////////////////////
using namespace polysolve;
void loadSymmetric(Eigen::SparseMatrix<double> &A, std::string PATH)
{
std::ifstream fin(PATH);
long int M, N, L;
while (fin.peek() == '%')
{
fin.ignore(2048, '\n');
}
fin >> M >> N >> L;
A.resize(M, N);
A.reserve(L * 2 - M);
std::vector<Eigen::Triplet<double>> triple;
for (size_t i = 0; i < L; i++)
{
int m, n;
double data;
fin >> m >> n >> data;
triple.push_back(Eigen::Triplet<double>(m - 1, n - 1, data));
if (m != n)
{
triple.push_back(Eigen::Triplet<double>(n - 1, m - 1, data));
}
}
fin.close();
A.setFromTriplets(triple.begin(), triple.end());
};
TEST_CASE("all", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
auto solvers = LinearSolver::availableSolvers();
for (const auto &s : solvers)
{
if (s == "Eigen::DGMRES")
continue;
#ifdef WIN32
if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES")
continue;
#endif
auto solver = LinearSolver::create(s, "");
solver->setParameters(R"({"conv_tol": 1e-10})"_json);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(b.size());
x.setZero();
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
// solver->getInfo(solver_info);
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
INFO("solver: " + s);
REQUIRE(err < 1e-8);
}
}
TEST_CASE("pre_factor", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
auto solvers = LinearSolver::availableSolvers();
for (const auto &s : solvers)
{
if (s == "Eigen::DGMRES")
continue;
#ifdef WIN32
if (s == "Eigen::ConjugateGradient" || s == "Eigen::BiCGSTAB" || s == "Eigen::GMRES" || s == "Eigen::MINRES")
continue;
#endif
auto solver = LinearSolver::create(s, "");
solver->analyzePattern(A, A.rows());
std::default_random_engine eng{42};
std::uniform_real_distribution<double> urd(0.1, 5);
for (int i = 0; i < 10; ++i)
{
std::vector<Eigen::Triplet<double>> tripletList;
for (int k = 0; k < A.outerSize(); ++k)
{
for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it)
{
if (it.row() == it.col())
{
tripletList.emplace_back(it.row(), it.col(), urd(eng) * 100);
}
else if (it.row() < it.col())
{
const double val = -urd(eng);
tripletList.emplace_back(it.row(), it.col(), val);
tripletList.emplace_back(it.col(), it.row(), val);
}
}
}
Eigen::SparseMatrix<double> Atmp(A.rows(), A.cols());
Atmp.setFromTriplets(tripletList.begin(), tripletList.end());
Eigen::VectorXd b(Atmp.rows());
b.setRandom();
Eigen::VectorXd x(b.size());
x.setZero();
solver->factorize(Atmp);
solver->solve(b, x);
// solver->getInfo(solver_info);
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (Atmp * x - b).norm();
INFO("solver: " + s);
REQUIRE(err < 1e-8);
}
}
}
#ifdef POLYSOLVE_WITH_HYPRE
TEST_CASE("hypre", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
auto solver = LinearSolver::create("Hypre", "");
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(b.size());
x.setZero();
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
// solver->getInfo(solver_info);
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
TEST_CASE("hypre_initial_guess", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(A.rows());
x.setZero();
{
json solver_info;
auto solver = LinearSolver::create("Hypre", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 1);
}
{
json solver_info;
auto solver = LinearSolver::create("Hypre", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] == 1);
}
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
#endif
#ifdef POLYSOLVE_WITH_AMGCL
TEST_CASE("amgcl_initial_guess", "[solver]")
{
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(A.rows());
x.setZero();
{
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
}
{
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] == 0);
}
// std::cout<<"Solver error: "<<x<<std::endl;
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
#endif
TEST_CASE("saddle_point_test", "[solver]")
{
#ifdef WIN32
#ifndef NDEBUG
return;
#endif
#endif
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
bool ok = loadMarket(A, path + "/A0.mat");
REQUIRE(ok);
Eigen::VectorXd b;
ok = loadMarketVector(b, path + "/b0.mat");
REQUIRE(ok);
auto solver = LinearSolver::create("SaddlePointSolver", "");
solver->analyzePattern(A, 9934);
solver->factorize(A);
Eigen::VectorXd x(A.rows());
solver->solve(b, x);
const double err = (A * x - b).norm();
REQUIRE(err < 1e-8);
}
#ifdef POLYSOLVE_WITH_AMGCL
TEST_CASE("amgcl_blocksolver_small_scale", "[solver]")
{
#ifndef NDEBUG
return;
#endif
const std::string path = POLYSOLVE_DATA_DIR;
Eigen::SparseMatrix<double> A;
const bool ok = loadMarket(A, path + "/A_2.mat");
REQUIRE(ok);
// solver->setParameters(params);
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(A.rows());
Eigen::VectorXd x_b(A.rows());
x.setZero();
x_b.setZero();
{
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
solver->setParameters(R"({"conv_tol": 1e-8})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
const double err = (A * x - b).norm();
REQUIRE(err < 1e-5);
}
{
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
solver->setParameters(R"({"conv_tol": 1e-8,"block_size": 3})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
solver->solve(b, x_b);
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
const double err = (A * x_b - b).norm();
REQUIRE(err < 1e-5);
}
}
#endif
#ifdef POLYSOLVE_WITH_AMGCL
TEST_CASE("amgcl_blocksolver_b2", "[solver]")
{
#ifndef NDEBUG
return;
#endif
const std::string path = POLYSOLVE_DATA_DIR;
std::string MatrixName = "gr_30_30.mtx";
Eigen::SparseMatrix<double> A;
loadSymmetric(A, path + "/" + MatrixName);
std::cout << "Matrix Load OK" << std::endl;
Eigen::VectorXd b(A.rows());
b.setRandom();
Eigen::VectorXd x(A.rows());
Eigen::VectorXd x_b(A.rows());
x.setOnes();
x_b.setOnes();
{
amgcl::profiler<> prof("gr_30_30_Scalar");
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
prof.tic("setup");
solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 1000})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
prof.toc("setup");
prof.tic("solve");
solver->solve(b, x);
prof.toc("solve");
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
std::cout << solver_info["num_iterations"] << std::endl;
std::cout << solver_info["final_res_norm"] << std::endl
<< prof << std::endl;
}
{
amgcl::profiler<> prof("gr_30_30_Block");
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
prof.tic("setup");
solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 1000,"block_size": 2})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
prof.toc("setup");
prof.tic("solve");
solver->solve(b, x_b);
prof.toc("solve");
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] >0);
std::cout<<solver_info["num_iterations"]<<std::endl;
std::cout << solver_info["final_res_norm"] << std::endl
<< prof << std::endl;
}
REQUIRE((A * x - b).norm() / b.norm() < 1e-7);
REQUIRE((A * x_b - b).norm() / b.norm() < 1e-7);
}
#endif
#ifdef POLYSOLVE_WITH_AMGCL
TEST_CASE("amgcl_blocksolver_crystm03_CG", "[solver]")
{
#ifndef NDEBUG
return;
#endif
std::cout << "Polysolve AMGCL Solver" <<std::endl;
const std::string path = POLYSOLVE_DATA_DIR;
std::string MatrixName = "crystm03.mtx";
Eigen::SparseMatrix<double> A;
loadSymmetric(A, path + "/" + MatrixName);
std::cout<<"Matrix Load OK"<<std::endl;
Eigen::VectorXd b(A.rows());
b.setOnes();
Eigen::VectorXd x_b(A.rows());
x_b.setZero();
Eigen::VectorXd x(A.rows());
x.setZero();
{
amgcl::profiler<> prof("crystm03_Block");
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
prof.tic("setup");
solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000,"block_size": 3})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
prof.toc("setup");
prof.tic("solve");
solver->solve(b, x_b);
prof.toc("solve");
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
std::cout << solver_info["num_iterations"] << std::endl;
std::cout << solver_info["final_res_norm"] << std::endl
<< prof << std::endl;
}
{
amgcl::profiler<> prof("crystm03_Scalar");
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
prof.tic("setup");
solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
prof.toc("setup");
prof.tic("solve");
solver->solve(b, x);
prof.toc("solve");
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
std::cout<<solver_info["num_iterations"]<<std::endl;
std::cout << solver_info["final_res_norm"] << std::endl
<< prof << std::endl;
}
REQUIRE((A * x - b).norm() / b.norm() < 1e-7);
REQUIRE((A * x_b - b).norm() / b.norm() < 1e-7);
}
#endif
#ifdef POLYSOLVE_WITH_AMGCL
TEST_CASE("amgcl_blocksolver_crystm03_Bicgstab", "[solver]")
{
#ifndef NDEBUG
return;
#endif
std::cout << "Polysolve AMGCL Solver" << std::endl;
const std::string path = POLYSOLVE_DATA_DIR;
std::string MatrixName = "crystm03.mtx";
Eigen::SparseMatrix<double> A;
loadSymmetric(A, path + "/" + MatrixName);
std::cout << "Matrix Load OK" << std::endl;
Eigen::VectorXd b(A.rows());
b.setOnes();
Eigen::VectorXd x_b(A.rows());
x_b.setZero();
Eigen::VectorXd x(A.rows());
x.setZero();
{
amgcl::profiler<> prof("crystm03_Block");
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
prof.tic("setup");
solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000,"solver_type": "bicgstab","block_size": 3})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
prof.toc("setup");
prof.tic("solve");
solver->solve(b, x_b);
prof.toc("solve");
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
std::cout << solver_info["num_iterations"] << std::endl;
std::cout << solver_info["final_res_norm"] << std::endl
<< prof << std::endl;
}
{
amgcl::profiler<> prof("crystm03_Scalar");
json solver_info;
auto solver = LinearSolver::create("AMGCL", "");
prof.tic("setup");
solver->setParameters(R"({"conv_tol": 1e-8,"max_iter": 10000,"solver_type":"bicgstab"})"_json);
solver->analyzePattern(A, A.rows());
solver->factorize(A);
prof.toc("setup");
prof.tic("solve");
solver->solve(b, x);
prof.toc("solve");
solver->getInfo(solver_info);
REQUIRE(solver_info["num_iterations"] > 0);
std::cout << solver_info["num_iterations"] << std::endl;
std::cout << solver_info["final_res_norm"] << std::endl
<< prof << std::endl;
}
REQUIRE((A * x - b).norm() / b.norm() < 1e-7);
REQUIRE((A * x_b - b).norm() / b.norm() < 1e-7);
}
#endif
| 15,321 | 5,778 |
#define _CRT_SECURE_NO_WARNINGS
#include "../WtPorter/WtPorter.h"
//#include "../WtExecMon/WtExecPorter.h"
#include "../Includes/WTSStruct.h"
#include "../Share/DLLHelper.hpp"
#include "../Share/CodeHelper.hpp"
void PORTER_FLAG on_init(CtxHandler ctxid)
{
printf("on_init\r\n");
hft_sub_ticks(ctxid, "CFFEX.IF.HOT");
}
void PORTER_FLAG on_tick(CtxHandler ctxid, const char* stdCode, WTSTickStruct* newTick)
{
printf("on_tick\r\n");
}
void PORTER_FLAG on_calc(CtxHandler ctxid, WtUInt32 uDate, WtUInt32 uTime)
{
printf("on_calc\r\n");
}
void PORTER_FLAG on_bar(CtxHandler ctxid, const char* code, const char* period, WTSBarStruct* newBar)
{
printf("on_bar\r\n");
}
void PORTER_FLAG on_getbar(CtxHandler ctxid, const char* code, const char* period, WTSBarStruct* bar, bool isLast)
{
if (bar)
printf("on_getbar%I64d\r\n", bar->time);
else
int x = 1;
}
void PORTER_FLAG on_getticks(CtxHandler cHandle, const char* code, WTSTickStruct* tick, bool isLast)
{
printf("on_getticks\r\n");
}
void PORTER_FLAG on_event(WtUInt32 evtId, WtUInt32 curDate, WtUInt32 curTime)
{
printf("on_event\r\n");
}
void PORTER_FLAG on_channel_evt(CtxHandler cHandle, const char* trader, WtUInt32 evtid)
{
printf("on_channel_evt\r\n");
double undone = hft_get_undone(cHandle, "CFFEX.IF.HOT");
}
void PORTER_FLAG on_order(CtxHandler cHandle, WtUInt32 localid, const char* stdCode, bool isBuy, double totalQty, double leftQty, double price, bool isCanceled, const char* userTag)
{
}
void PORTER_FLAG on_trade(CtxHandler cHandle, WtUInt32 localid, const char* stdCode, bool isBuy, double vol, double price, const char* userTag)
{
}
void PORTER_FLAG on_entrust(CtxHandler cHandle, WtUInt32 localid, const char* stdCode, bool bSuccess, const char* message, const char* userTag)
{
}
void PORTER_FLAG on_order_queue(CtxHandler cHandle, const char* stdCode, WTSOrdQueStruct* ordQue)
{
}
void PORTER_FLAG on_order_detail(CtxHandler cHandle, const char* stdCode, WTSOrdDtlStruct* ordDtl)
{
}
void PORTER_FLAG on_transaction(CtxHandler cHandle, const char* stdCode, WTSTransStruct* trans)
{
}
void test_porter()
{
#ifdef _WIN32
DLLHelper::load_library("WtPorter.dll");
#else
DLLHelper::load_library("libWtPorter.so");
#endif
init_porter("logcfg.json", true, "./generated");
reg_hft_factories("./hft");
config_porter("config.json", true);
run_porter(true);
printf("press enter key to exit\n");
getchar();
release_porter();
}
int main()
{
test_porter();
getchar();
return 0;
}
| 2,600 | 1,083 |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dan Larkin-York
////////////////////////////////////////////////////////////////////////////////
#include "RocksDBBackgroundErrorListener.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
namespace arangodb {
RocksDBBackgroundErrorListener::~RocksDBBackgroundErrorListener() = default;
void RocksDBBackgroundErrorListener::OnBackgroundError(rocksdb::BackgroundErrorReason reason,
rocksdb::Status* status) {
if (status != nullptr && status->IsShutdownInProgress()) {
// this is not a relevant error, so let's ignore it
return;
}
if (!_called) {
_called = true;
std::string operation = "unknown";
switch (reason) {
case rocksdb::BackgroundErrorReason::kFlush: {
operation = "flush";
break;
}
case rocksdb::BackgroundErrorReason::kCompaction: {
operation = "compaction";
break;
}
case rocksdb::BackgroundErrorReason::kWriteCallback: {
operation = "write callback";
break;
}
case rocksdb::BackgroundErrorReason::kMemTable: {
operation = "memtable";
break;
}
}
LOG_TOPIC("fae2c", ERR, Logger::ROCKSDB)
<< "RocksDB encountered a background error during a " << operation
<< " operation: " << (status != nullptr ? status->ToString() : "unknown error")
<< "; The database will be put in read-only mode, and subsequent write errors are likely";
}
}
} // namespace arangodb
| 2,402 | 673 |
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_COMBINATORIAL_FUNCTIONS_LCM_HPP_INCLUDED
#define NT2_COMBINATORIAL_FUNCTIONS_LCM_HPP_INCLUDED
#include <nt2/include/functor.hpp>
namespace nt2 { namespace tag
{
/*!
@brief lcm generic tag
Represents the lcm function in generic contexts.
@par Models:
Hierarchy
**/
struct lcm_ : ext::elementwise_<lcm_>
{
/// @brief Parent hierarchy
typedef ext::elementwise_<lcm_> parent;
template<class... Args>
static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
BOOST_AUTO_DECLTYPE_BODY( dispatching_lcm_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
};
}
namespace ext
{
template<class Site>
BOOST_FORCEINLINE generic_dispatcher<tag::lcm_, Site> dispatching_lcm_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)
{
return generic_dispatcher<tag::lcm_, Site>();
}
template<class... Args>
struct impl_lcm_;
}
/*!
Computes the least common multiple
If parameters are floating point and not flint,
nan is returned.
@par Semantic:
For every table expressions
@code
auto r = lcm(a0,a1);
@endcode
- If any input is zero 0 is returned
- If parameters are floating point and not flint,
nan is returned.
@see @funcref{gcd}, @funcref{is_flint}
@param a0
@param a1
@return an expression which eventually will evaluate to the result
**/
NT2_FUNCTION_IMPLEMENTATION(tag::lcm_, lcm, 2)
}
#endif
| 2,007 | 695 |
#include "vklive/vulkan/vulkan_render.h"
#include "config_app.h"
#include "vklive/file/file.h"
#include "vklive/vulkan/vulkan_framebuffer.h"
#include "vklive/vulkan/vulkan_model.h"
#include "vklive/vulkan/vulkan_pipeline.h"
#include "vklive/vulkan/vulkan_shader.h"
#include "vklive/vulkan/vulkan_uniform.h"
#include "vklive/vulkan/vulkan_utils.h"
#include "vklive/vulkan/vulkan_scene.h"
namespace vulkan
{
namespace
{
// Vertex layout for this example
VertexLayout g_vertexLayout{ {
Component::VERTEX_COMPONENT_POSITION,
Component::VERTEX_COMPONENT_UV,
Component::VERTEX_COMPONENT_COLOR,
Component::VERTEX_COMPONENT_NORMAL,
} };
} // namespace
std::shared_ptr<RenderContext> render_context(VulkanContext& ctx)
{
return std::static_pointer_cast<RenderContext>(ctx.spRenderData);
}
void render_init(VulkanContext& ctx)
{
auto spRender = std::make_shared<RenderContext>();
ctx.spRenderData = spRender;
}
void render_destroy_images(VulkanContext& ctx, RenderContext& renderContext)
{
for (auto& buffer : renderContext.colorBuffers)
{
image_destroy(ctx, buffer);
}
renderContext.colorBuffers.clear();
if (renderContext.depthBuffer.format != vk::Format::eUndefined)
{
image_destroy(ctx, renderContext.depthBuffer);
}
}
void render_destroy(VulkanContext& ctx)
{
auto spRender = render_context(ctx);
render_destroy_images(ctx, *spRender);
ctx.spRenderData = nullptr;
}
void render_create_images(VulkanContext& ctx, RenderContext& renderContext, const glm::uvec2& size, vk::Format colorFormat, vk::Format depthFormat)
{
render_destroy_images(ctx, renderContext);
renderContext.colorBuffers.resize(1);
image_create(ctx, renderContext.colorBuffers[0], size, colorFormat, true, "RenderDefault");
bool useDepth = depthFormat != vk::Format::eUndefined;
if (useDepth)
{
image_create_depth(ctx, renderContext.depthBuffer, size, depthFormat, false, "RenderDefault");
}
}
void render_check_framebuffer(VulkanContext& ctx, const glm::uvec2& size)
{
auto spRender = render_context(ctx);
if (spRender->frameBufferSize == size)
{
return;
}
// Might still be rendering to/with this FB, so wait for it.
ctx.device.waitIdle();
// Destroy old
spRender->frameBufferSize = size;
render_create_images(ctx, *spRender, glm::uvec2(size), vk::Format::eR8G8B8A8Unorm, vk::Format::eD32Sfloat);
image_set_sampling(ctx, spRender->colorBuffers[0]);
debug_set_descriptorsetlayout_name(ctx.device, spRender->colorBuffers[0].samplerDescriptorSetLayout, "RenderColorBuffer::DescriptorSetLayout");
debug_set_descriptorset_name(ctx.device, spRender->colorBuffers[0].samplerDescriptorSet, "RenderColorBuffer::DescriptorSet");
debug_set_sampler_name(ctx.device, spRender->colorBuffers[0].sampler, "RenderColorBuffer::Sampler");
}
void render(VulkanContext& ctx, const glm::vec4& rect, Scene& scene)
{
auto spRender = render_context(ctx);
// Check the framebuffer
render_check_framebuffer(ctx, glm::uvec2(rect.z, rect.w));
// Render the scene
vulkan::vulkan_scene_render(ctx, *spRender, scene);
}
} // namespace vulkan
| 3,190 | 1,128 |
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2018 ScyllaDB Ltd.
*/
#include <seastar/core/reactor.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <atomic>
#include <chrono>
using namespace seastar;
using namespace std::chrono_literals;
class temporary_stall_detector_settings {
std::chrono::milliseconds _old_threshold;
std::function<void ()> _old_report;
public:
temporary_stall_detector_settings(std::chrono::duration<double> threshold, std::function<void ()> report)
: _old_threshold(engine().get_blocked_reactor_notify_ms())
, _old_report(engine().get_stall_detector_report_function()) {
engine().update_blocked_reactor_notify_ms(std::chrono::duration_cast<std::chrono::milliseconds>(threshold));
engine().set_stall_detector_report_function(std::move(report));
}
~temporary_stall_detector_settings() {
engine().update_blocked_reactor_notify_ms(_old_threshold);
engine().set_stall_detector_report_function(std::move(_old_report));
}
};
void spin(std::chrono::duration<double> how_much) {
auto end = std::chrono::steady_clock::now() + how_much;
while (std::chrono::steady_clock::now() < end) {
// spin!
}
}
void spin_some_cooperatively(std::chrono::duration<double> how_much) {
auto end = std::chrono::steady_clock::now() + how_much;
while (std::chrono::steady_clock::now() < end) {
spin(200us);
if (need_preempt()) {
thread::yield();
}
}
}
SEASTAR_THREAD_TEST_CASE(normal_case) {
std::atomic<unsigned> reports{};
temporary_stall_detector_settings tsds(10ms, [&] { ++reports; });
spin_some_cooperatively(1s);
BOOST_REQUIRE_EQUAL(reports, 0);
}
SEASTAR_THREAD_TEST_CASE(simple_stalls) {
std::atomic<unsigned> reports{};
temporary_stall_detector_settings tsds(10ms, [&] { ++reports; });
unsigned nr = 10;
for (unsigned i = 0; i < nr; ++i) {
spin_some_cooperatively(100ms);
spin(20ms);
}
spin_some_cooperatively(100ms);
BOOST_REQUIRE_EQUAL(reports, 10);
}
| 2,835 | 975 |
#include <math.h>
#include <stdio.h>
#include "utils.h"
//Helper function to see if value is in tolerance
int is_equal(double a, double b, const double epsilon)
{
double c = a - b;
return fabs(c) <= epsilon;
}
//Central diff function, makes two function calls, O(h^2)
REAL diff(const REAL x, REAL (*func)(const REAL), const REAL h)
{
// diff = f(x + h) - f(x -h)/2h + O(h^2)
return ((*func)(x + h) - (*func)(x - h))/(2.0*h + REALSMALL);
}
//Forward diff function, receive funcx making only one function call, O(h)
REAL diff_forward(const REAL x, const REAL funcx, REAL (*func)(const REAL), const REAL h)
{
// diff = f(x + h) - f(x)/h + O(h)
return ((*func)(x + h) - funcx)/(h + REALSMALL);
}
//Backward diff function, receive funcx making only one function call, O(h)
REAL diff_backward(const REAL x, const REAL funcx, REAL (*func)(const REAL), const REAL h)
{
// diff = f(x) - f(x - h)/h + O(h)
return (funcx - (*func)(x - h))/(h + REALSMALL);
}
//Central second diff function, receive funcx making only two function calls, O(h**2)
REAL diff2(const REAL x, const REAL funcx, REAL (*func)(const REAL), const REAL h)
{
// diff2 = f(x +h) -2*f(x) +f(x - h)/h**2 + O(h**2)
return ((*func)(x + h) -2.0*funcx +(*func)(x - h))/(h*h +REALSMALL*REALSMALL);
}
// Possitive unidimensional Newton-Raphson-Bissection algorithm
// Use numerical forward differencing for speed (reduces number of function calls)
// Use a initial guess when calling PNRB, like ideal gas equation solution for variable
REAL PNRB(REAL guess, REAL (*func)(const REAL), const REAL h)
{
REAL fx = (*func)(guess);
//Early-abort, check if guess is already root for equation
if (fx < h && guess > 0.0) return guess;
//Lower limit for real space. Searching for a non-negative root
REAL a = REALSMALL;
//Upper limit for real space in REAL type
REAL b = REALBIG;
REAL fa = (*func)(a);
unsigned short int count = 0;
do {
//If root is in [a, guess] reduces search space around it.
if (fx*fa < 0.0){
b = guess;
}
//Else advance to guess position
else {
a = guess;
}
//Choose new guess using Newton approximation
guess = guess - fx/diff_forward(guess, fx, func, h);
//If the result is outside braket use bissection step (for stability)
if ((b-guess)*(guess-a) < 0.0){
guess = guess + 0.5*(b-a);
}
//Compute new value for function
fx = (*func)(guess);
//Check if guess is root for equation
if (fx < h && guess > 0.0){
return guess;
}
//Increase interation count
count +=1;
//Limit the iterations to 1001, should converge much faster (like 5~10 iters)
} while(count < 1001);
return guess;
} | 2,630 | 1,041 |
#pragma once
#include <array>
#include <bitset>
#include <cassert>
#if !defined( BITPACKER_USE_STD_BIT )
# define BITPACKER_USE_STD_BIT __has_include( <bit> ) && __cplusplus >= 202002L
#endif
#if BITPACKER_USE_STD_BIT
# include <bit>
#endif
#define BITPACKER_VERSION_MAJOR 0
#define BITPACKER_VERSION_MINOR 1
#define BITPACKER_VERSION_PATCH 0
#define BITPACKER_VERSION_STR "0.1.0"
#define BITPACKER_VERSION \
( BITPACKER_VERSION_MAJOR * 10000 + BITPACKER_VERSION_MINOR * 100 + BITPACKER_VERSION_PATCH )
namespace bitpacker
{
#if BITPACKER_USE_STD_BIT
using std::bit_width;
#else
template <class V, std::enable_if_t<std::is_unsigned_v<V>, int> = 0>
[[nodiscard]] constexpr V bit_width( const V value ) noexcept
{
V result = 0u;
V temp = value;
while( temp != 0u )
{
++result;
temp >>= static_cast<V>( 1u );
}
return result;
}
#endif
template <class ContainerT>
class bit_ostream
{
public:
constexpr explicit bit_ostream( ContainerT& data )
: m_data( data )
{}
constexpr bit_ostream& operator<<( const bool value )
{
assert( m_offset < m_data.size() );
m_data[m_offset++] = value;
return *this;
}
[[nodiscard]] constexpr size_t offset() const
{
return m_offset;
}
private:
ContainerT& m_data;
size_t m_offset = 0;
};
template <class ContainerT>
class bit_istream
{
public:
constexpr explicit bit_istream( ContainerT& data )
: m_data( data )
{}
constexpr bit_istream& operator>>( bool& value )
{
assert( m_offset < m_data.size() );
value = m_data[m_offset++];
return *this;
}
[[nodiscard]] constexpr size_t offset() const
{
return m_offset;
}
private:
ContainerT& m_data;
size_t m_offset = 0;
};
/// Return unsigned difference between two integers
/// Left hand side value should be greater or equal than right hand side value
template <typename V, class UnsignedV = typename std::make_unsigned<V>::type>
[[nodiscard]] constexpr UnsignedV integral_unsigned_difference( const V lhs, const V rhs )
{
return static_cast<UnsignedV>( lhs ) - static_cast<UnsignedV>( rhs );
}
/// Calculate delta for integral values with given range
template <typename V, class UnsignedV = typename std::make_unsigned<V>::type>
[[nodiscard]] constexpr UnsignedV integral_delta( const V min_value, const V max_value )
{
return integral_unsigned_difference( max_value, min_value );
}
/// Calculate delta for integral values without limits
template <typename V, class UnsignedV = typename std::make_unsigned<V>::type>
[[nodiscard]] constexpr UnsignedV integral_delta()
{
const auto min_value = std::numeric_limits<V>::min();
const auto max_value = std::numeric_limits<V>::max();
return integral_delta( min_value, max_value );
}
// Pack normalized value in range from 0 to delta
template <typename V, typename OutputBitStreamT>
constexpr void pack_normalized_value( OutputBitStreamT& obstream, const V value, const V delta )
{
static_assert( std::is_unsigned_v<V> );
auto temp = value;
constexpr auto ONE = static_cast<V>( 1 );
for( size_t i = 0, ie = bit_width( delta ); i < ie; ++i )
{
const bool bit = temp & ONE;
obstream << bit;
temp >>= ONE;
}
}
template <typename V, typename InputBitStreamT>
constexpr V unpack_normalized_value( InputBitStreamT& ibstream, const V delta )
{
V value{};
constexpr auto ONE = static_cast<V>( 1 );
for( size_t i = 0, ie = bit_width( delta ); i < ie; ++i )
{
bool bit{};
ibstream >> bit;
if( bit )
{
value |= ( ONE << i );
}
}
return value;
}
} // namespace bitpacker
| 3,979 | 1,403 |
/*
* Copyright (c) 2019, Infosys Ltd.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <utils/mmeCommonUtils.h>
#include <cmath>
#include <controlBlock.h>
#include <contextManager/dataBlocks.h>
#include <contextManager/subsDataGroupManager.h>
#include <log.h>
#include <mme_app.h>
#include <msgBuffer.h>
#include <s1ap_structs.h>
#include <utils/defaultMmeProcedureCtxt.h>
#include <random>
using namespace mme;
extern mme_config_t *mme_cfg;
bool MmeCommonUtils::isLocalGuti(const guti &guti_r)
{
bool rc = false;
if (guti_r.mme_grp_id == mme_cfg->mme_group_id &&
guti_r.mme_code == mme_cfg->mme_code)
{
rc = true;
}
return rc;
}
#ifdef S10_FEATURE
bool MmeCommonUtils::compare_plmn_id(const struct PLMN *plmn)
{
bool rc = false;
//need to check whether this comparison will work or not, else need to decode idx to mcc and mnc
int config_plmn;
for(config_plmn = 0; config_plmn < mme_cfg->num_plmns; config_plmn++)
{
if((mme_cfg->plmns[config_plmn].idx[0] == plmn->idx[0]) &&
(mme_cfg->plmns[config_plmn].idx[1] == plmn->idx[1]) &&
(mme_cfg->plmns[config_plmn].idx[2] == plmn->idx[2]) &&
(mme_cfg->plmns[config_plmn].mnc_digits == plmn->mnc_digits))
rc = true;
}
return rc;
}
bool MmeCommonUtils::compare_tac(const uint16_t tac)
{
bool rc = false;
int i = 0;
/*for(i = 0; i < mme_cfg->num_tai; i++)
{
if(mme_cfg->served_tai.tac[i] == tac)
rc = true;
}*/
return rc;
}
bool MmeCommonUtils::isLocalTAI(const struct PLMN *plmn, const short target_tac)
{
bool rc = false;
if(true == compare_plmn_id(plmn))
{
if(true == compare_tac(target_tac))
{
log_msg(LOG_DEBUG, "TAC and PLMN are matching");
rc = true;
}
}
log_msg(LOG_DEBUG, "TAC and PLMN are not matching");
return rc;
}
void MmeCommonUtils::select_neighboring_mme(const struct TAI *tai, int *service_ip_addr)
{
//*service_ip_addr = mme_cfg->target_mme_ip;
return;
}
#endif
uint8_t MmeCommonUtils::select_preferred_int_algo(uint8_t &val)
{
uint8_t result = 0;
for(int i = 0; i < MAX_ALGO_COUNT; i++)
{
if (val & (0x80 >> mme_cfg->integrity_alg_order[i]))
{
result = mme_cfg->integrity_alg_order[i];
break;
}
}
return result;
}
uint8_t MmeCommonUtils::select_preferred_sec_algo(uint8_t &val)
{
uint8_t result = 0;
for(int i = 0; i < MAX_ALGO_COUNT; i++)
{
if (val & (0x80 >> mme_cfg->ciphering_alg_order[i]))
{
result = mme_cfg->ciphering_alg_order[i];
break;
}
}
return result;
}
uint32_t MmeCommonUtils::allocateMtmsi()
{
uint32_t tmsi = 0;
std::default_random_engine generator(time(NULL));
std::uniform_int_distribution<int> temp_fun(0, 1000000);
while(1)
{
tmsi = temp_fun(generator);
if (SubsDataGroupManager::Instance()->findCBWithmTmsi(tmsi) == -1)
break;
}
log_msg(LOG_INFO, "MTMSI allocated is %u", tmsi);
return tmsi;
}
void MmeCommonUtils::formatS1apPlmnId(struct PLMN* plmn_p)
{
/* Lets update plmnId .... What we received from s1ap is : 214365 and what we need on
* s6a/s11/nas interfaces is - 216354*/
unsigned char plmn_byte2 = plmn_p->idx[1];
unsigned char plmn_byte3 = plmn_p->idx[2];
unsigned char mnc3 = plmn_byte3 >> 4; // mnc3
unsigned char mnc2 = plmn_byte3 & 0xf; // mnc2
unsigned char mnc1 = plmn_byte2 >> 4; // mnc1
unsigned char mcc3 = plmn_byte2 & 0xf; //mcc3
// First byte we are not changing mcc2 mcc1
if(mnc1 != 0x0F)
{
plmn_byte2 = (mnc3 << 4) | mcc3; // 2nd byte on NAS - mnc3 mcc3
plmn_byte3 = (mnc2 << 4) | mnc1; // 3rd byte on NAS - <mnc2 mnc1>
plmn_p->idx[1] = plmn_byte2;
plmn_p->idx[2] = plmn_byte3;
}
}
void MmeCommonUtils::getS1apPlmnIdFroms11(struct PLMN* plmn_p)
{
/* we have on s11/nas/s6a - 216354 */
/* s1ap need : 214365 */
unsigned char plmn_byte2 = plmn_p->idx[1];
unsigned char plmn_byte3 = plmn_p->idx[2];
unsigned char mnc3 = plmn_byte2 >> 4; // mnc3
unsigned char mnc2 = plmn_byte3 >> 4; // mnc2
unsigned char mnc1 = plmn_byte3 & 0xf; // mnc1
unsigned char mcc3 = plmn_byte2 & 0xf; //mcc3
// First byte we are not changing mcc2 mcc1
if(mnc1 != 0x0F)
{
plmn_byte2 = (mnc1 << 4) | mcc3;
plmn_byte3 = (mnc3 << 4) | mnc2;
plmn_p->idx[1] = plmn_byte2;
plmn_p->idx[2] = plmn_byte3;
}
}
AttachType MmeCommonUtils::getAttachType(UEContext* ueContext_p,
const struct ue_attach_info& ue_info)
{
log_msg(LOG_INFO, "deriveAttachType");
AttachType attachType = maxAttachType_c;
if(UE_ID_IMSI(ue_info.flags))
{
log_msg(LOG_INFO, "IMSI attach received.");
attachType = imsiAttach_c;
}
else if (UE_ID_GUTI(ue_info.flags))
{
log_msg(LOG_INFO, "GUTI attach received. mTMSI is %u ",
ue_info.mi_guti.m_TMSI);
attachType = unknownGutiAttach_c;
if (isLocalGuti(ue_info.mi_guti))
{
// The guti is allocated by this MME, check if a context exists.
// If the context does not exist, treat as unknown GUTI attach?
log_msg(LOG_INFO, "GUTI is local..");
if (ueContext_p != NULL)
{
if (ueContext_p->getMTmsi() == ue_info.mi_guti.m_TMSI)
{
log_msg(LOG_INFO, "and known");
attachType = knownGutiAttach_c;
}
else
{
log_msg(LOG_INFO, "mTMSI mismatches with UE context. "
"Treat as unknown GUTI attach");
}
}
else
{
log_msg(LOG_INFO, "UE context is null. Unknown GUTI attach triggered");
}
}
else
{
log_msg(LOG_INFO, "GUTI is not local..");
}
}
return attachType;
}
SM::ControlBlock* MmeCommonUtils::findControlBlock(cmn::utils::MsgBuffer* buf)
{
SM::ControlBlock *cb = NULL;
const s1_incoming_msg_header_t* msgData_p = (s1_incoming_msg_header_t*)(buf->getDataPointer());
if(msgData_p == NULL)
{
log_msg(LOG_INFO, "MsgData is NULL .");
return cb;
}
switch (msgData_p->msg_type)
{
case attach_request:
{
const ue_attach_info_t *ue_info = (ue_attach_info_t *)(msgData_p);
if(UE_ID_IMSI(ue_info->flags))
{
log_msg(LOG_INFO, "IMSI attach received.");
uint8_t imsi[BINARY_IMSI_LEN] = {0};
memcpy( imsi, ue_info->IMSI, BINARY_IMSI_LEN );
uint8_t first = imsi[0] >> 4;
imsi[0] = (uint8_t)(( first << 4 ) | 0x0f );
DigitRegister15 IMSIInfo;
IMSIInfo.convertFromBcdArray(imsi);
int cbIndex = SubsDataGroupManager::Instance()->findCBWithimsi(IMSIInfo);
if (cbIndex > 0)
{
log_msg(LOG_DEBUG, "existing cb for IMSI. %s ",IMSIInfo.getDigitsArray());
cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex);
}
if (cb == NULL)
{
log_msg(LOG_INFO, "create new cb for IMSI %s.", IMSIInfo.getDigitsArray());
cb = SubsDataGroupManager::Instance()->allocateCB();
if(cb == NULL)
{
log_msg(LOG_DEBUG, "create new cb for IMSI failed. %s ",IMSIInfo.getDigitsArray());
return nullptr;
}
cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
}
else if (UE_ID_GUTI(ue_info->flags))
{
log_msg(LOG_INFO, "GUTI attach received.");
if (isLocalGuti(ue_info->mi_guti))
{
log_msg(LOG_INFO, "GUTI is local.");
int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(ue_info->mi_guti.m_TMSI);
if (cbIndex > 0)
{
cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex);
}
else
{
log_msg(LOG_ERROR, "Failed to find control block with mTmsi.");
// allocate new cb and proceed?
cb = SubsDataGroupManager::Instance()->allocateCB();
cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
}
else
{
cb = SubsDataGroupManager::Instance()->allocateCB();
cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
}
break;
}
case service_request:
{
int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(msgData_p->ue_idx);
if (cbIndex > 0)
{
cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex);
}
else
{
log_msg(LOG_INFO, "Failed to find control block with mTmsi.");
}
if (cb == NULL)
{
log_msg(LOG_INFO, "Failed to find control block using mtmsi %d."
" Allocate a temporary control block", msgData_p->ue_idx);
// Respond with Service Reject from default Service Request event handler
cb = SubsDataGroupManager::Instance()->allocateCB();
cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
break;
}
case detach_request:
{
const detach_req_Q_msg_t *detach_Req = (const detach_req_Q_msg_t *)(msgData_p);
int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(detach_Req->ue_m_tmsi);
if (cbIndex > 0)
{
cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex);
}
else
{
log_msg(LOG_INFO, "Failed to find control block with mTmsi. %d", detach_Req->ue_m_tmsi);
}
break;
}
case tau_request:
{
const tauReq_Q_msg_t *tau_Req = (const tauReq_Q_msg_t *)(msgData_p);
int cbIndex = SubsDataGroupManager::Instance()->findCBWithmTmsi(tau_Req->ue_m_tmsi);
if (cbIndex > 0)
{
cb = SubsDataGroupManager::Instance()->findControlBlock(cbIndex);
}
else
{
log_msg(LOG_INFO, "Failed to find control block using mTmsi %d."
" Allocate a temporary control block", tau_Req->ue_m_tmsi);
// Respond with TAU Reject from default TAU event handler
cb = SubsDataGroupManager::Instance()->allocateCB();
cb->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
break;
}
default:
{
log_msg(LOG_INFO, "Unhandled message type %d ", msgData_p->msg_type);
}
}
return cb;
}
ControlBlock* MmeCommonUtils::findControlBlockForS11Msg(cmn::utils::MsgBuffer* msg_p)
{
ControlBlock* cb_p = NULL;
const gtp_incoming_msg_data_t* msgData_p = (gtp_incoming_msg_data_t*)(msg_p->getDataPointer());
if(msgData_p == NULL)
{
log_msg(LOG_INFO, "GTP message data is NULL .");
return cb_p;
}
switch (msgData_p->msg_type)
{
case downlink_data_notification:
{
const struct ddn_Q_msg* ddn = (const struct ddn_Q_msg*) (msg_p->getDataPointer());
if (ddn->s11_mme_cp_teid == 0)
{
log_msg(LOG_INFO, "UE Index in DDN message data is 0.");
return cb_p;
}
cb_p = SubsDataGroupManager::Instance()->findControlBlock(ddn->s11_mme_cp_teid);
if (cb_p == NULL)
{
log_msg(LOG_INFO, "Failed to find control block using index %d."
" Allocate a temporary control block", ddn->s11_mme_cp_teid);
// Respond with DDN failure from default DDN event handler
cb_p = SubsDataGroupManager::Instance()->allocateCB();
cb_p->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
}break;
case create_bearer_request:
{
const struct cb_req_Q_msg * cbr = (const struct cb_req_Q_msg *) (msg_p->getDataPointer());
if (cbr->s11_mme_cp_teid == 0)
{
log_msg(LOG_INFO, "UE Index in CB Req message data is 0.");
return cb_p;
}
cb_p = SubsDataGroupManager::Instance()->findControlBlock(cbr->s11_mme_cp_teid);
if (cb_p == NULL)
{
log_msg(LOG_INFO, "Failed to find control block using index %d."
" Allocate a temporary control block", cbr->s11_mme_cp_teid);
// Respond with CB Resp from default CB Req event handler
cb_p = SubsDataGroupManager::Instance()->allocateCB();
cb_p->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
}break;
case delete_bearer_request:
{
const struct db_req_Q_msg * dbr = (const struct db_req_Q_msg *) (msg_p->getDataPointer());
if (dbr->s11_mme_cp_teid == 0)
{
log_msg(LOG_INFO, "UE Index in DB Req message data is 0.");
return cb_p;
}
cb_p = SubsDataGroupManager::Instance()->findControlBlock(dbr->s11_mme_cp_teid);
if (cb_p == NULL)
{
log_msg(LOG_INFO, "Failed to find control block using index %d."
" Allocate a temporary control block", dbr->s11_mme_cp_teid);
// Respond with DB Resp from default DB Req event handler
cb_p = SubsDataGroupManager::Instance()->allocateCB();
cb_p->addTempDataBlock(DefaultMmeProcedureCtxt::Instance());
}
}break;
default:
{
log_msg(LOG_INFO, "Unhandled message type");
}
}
return cb_p;
}
bool MmeCommonUtils::isEmmInfoRequired(ControlBlock& cb, UEContext& ueCtxt, MmeProcedureCtxt& procCtxt)
{
bool rc = false;
if (procCtxt.getCtxtType() == attach_c)
{
MmeAttachProcedureCtxt& attachCtxt = dynamic_cast<MmeAttachProcedureCtxt &>(procCtxt);
if (attachCtxt.getAttachType() == imsiAttach_c)
{
rc = true;
}
}
return rc;
}
bool MmeCommonUtils::isUeNRCapable(UEContext &ueCtxt)
{
bool rc;
if (!ueCtxt.getUeNetCapab().ue_net_capab_m.u.bits.dcnr) {
log_msg(LOG_DEBUG, "UE does not support dual connectivity");
rc = false;
} else if (!mme_cfg->feature_list.dcnr_support) {
log_msg(LOG_DEBUG,"MME local config does not allow dual connectivity");
rc = false;
} else if (!(ueCtxt.getHssFeatList2().feature_list & nrAsSecRatBitMask_c)) {
log_msg(LOG_DEBUG,"HSS does not support dual connectivity feature");
rc = false;
} else if (ueCtxt.getAccessRestrictionData() & nrAsSecRatInEutranNotAllowedBitMask_c) {
log_msg(LOG_DEBUG,"hss informed about access restriction for this UE");
rc = false;
} else {
log_msg(LOG_DEBUG,"All well, this UE can use DCNR");
rc = true;
}
return rc;
}
| 14,125 | 5,833 |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL)
return false;
if(root->left==NULL and root->right==NULL)
return (targetSum-root->val)==0;
return hasPathSum(root->left, targetSum-root->val) || hasPathSum(root->right,targetSum-root->val);
}
}; | 695 | 230 |
#include "FW/SC/scene.h"
#include "FW/tools.h"
#include "FW/ST/state_writer.h"
#include "FW/RC/record.h"
#include "FW/SC/scene_line.h"
////////////////////////////////////////////////////////////////////////
/// Static
long TypeScene::m_IdCount = 0;
QString TypeScene::GenerateId()
{
return QString().setNum( m_IdCount++ );
}
QString TypeScene::IdCount()
{
return QString().setNum( m_IdCount );
}
////////////////////////////////////////////////////////////////////////
TypeScene::TypeScene( TypeController& controller, TypeVariant* parent ) :
TypeVariant( parent ),
m_Controller( &controller ),
m_TopZ( 0 )
{
m_Graphics = new QGraphicsScene();
}
TypeScene::~TypeScene()
{
delete m_Graphics;
}
TypeSceneItem* TypeScene::NewItem( TypeStateWriter& state )
{
return new TypeSceneItem( *this, state );
}
TypeSceneItem* TypeScene::NewItem( TypeRecord& record )
{
return new TypeSceneItem( *this, record, 100 + ( qrand() % 40 - 80 ), 100 + ( qrand() % 40 - 80 ) );
}
TypeSceneItem* TypeScene::NewItem( TypeRecord& record, qreal x, qreal y, qreal z )
{
return new TypeSceneItem( *this, record, x, y, z );
}
QList<TypeSceneItem*> TypeScene::FromRecord( TypeRecord& record ) const
{
QList<TypeSceneItem*> result;
for( TypeSceneItem* item : Items() )
{
if( & item->Record() == & record )
result.append( item );
}
return result;
}
void TypeScene::Clear()
{
Graphics().clear();
}
int TypeScene::Size()
{
return Items().size();
}
void TypeScene::BringFront( TypeSceneItem& item )
{
m_TopZ += 0.01;
item.setZValue( m_TopZ );
}
void TypeScene::UpdateView()
{
// Update lines
ClearLines();
for( TypeSceneItem* from : Items() )
{
if( from->Record().Struct() != 0 )
{
for( TypeVariantPtr<TypeRecord> record : *from->Record().Struct() )
{
for( TypeSceneItem* target : Items() )
{
TypeRecord* record_target = &target->Record();
if( record == record_target )
m_Lines.append( new TypeSceneLine( *from, *target, Qt::blue ) );
}
}
}
}
}
void TypeScene::ClearLines()
{
for( TypeSceneLine* line : Lines() )
delete line;
}
| 2,319 | 763 |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <functional>
#include <numeric>
#include <sstream>
#include "utils/provenance_tag.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace detail
{
std::string concat_strings(
const std::vector<std::reference_wrapper<const std::string>>& strings)
{
const auto concat_with_comma =
[](const std::string& accumulator,
std::reference_wrapper<const std::string> next_string) {
return accumulator + ", " + next_string.get();
};
return std::accumulate(
strings.begin() + 1, strings.end(), strings.begin()->get(), concat_with_comma);
}
std::string build_input_provenance_tag(const std::string& input_name,
const PartialShape& shape)
{
std::stringstream tag_builder;
tag_builder << "<ONNX Input (" << input_name << ") Shape:" << shape << ">";
return tag_builder.str();
}
std::string build_op_provenance_tag(const Node& onnx_node)
{
const auto output_names = concat_strings(onnx_node.get_output_names());
const auto node_name =
onnx_node.get_name().empty() ? "" : onnx_node.get_name() + " ";
return std::string{"<ONNX " + onnx_node.op_type() + " (" + node_name + "-> " +
output_names + ")>"};
}
} // namespace detail
} // namespace onnx_import
} // namespace ngraph
| 1,766 | 487 |
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int n1 = 3;
int n2 = 5;
std::vector<int> v{0, 1, 2, 3, 4};
auto result1 = std::find(std::begin(v), std::end(v), n1);
auto result2 = std::find(std::begin(v), std::end(v), n2);
if (result1 != std::end(v)) {
std::cout << "v contains: " << n1 << '\n';
} else {
std::cout << "v does not contain: " << n1 << '\n';
}
if (result2 != std::end(v)) {
std::cout << "v contains: " << n2 << '\n';
} else {
std::cout << "v does not contain: " << n2 << '\n';
}
} | 619 | 249 |
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/unwind.h"
#include <boost/implicit_cast.hpp>
#include <folly/ScopeGuard.h>
#include "hphp/util/trace.h"
#include "hphp/runtime/base/tv-refcount.h"
#include "hphp/runtime/ext/asio/ext_async-function-wait-handle.h"
#include "hphp/runtime/ext/asio/ext_async-generator-wait-handle.h"
#include "hphp/runtime/ext/asio/ext_async-generator.h"
#include "hphp/runtime/ext/asio/ext_static-wait-handle.h"
#include "hphp/runtime/ext/generator/ext_generator.h"
#include "hphp/runtime/vm/bytecode.h"
#include "hphp/runtime/vm/debugger-hook.h"
#include "hphp/runtime/vm/func.h"
#include "hphp/runtime/vm/hhbc.h"
#include "hphp/runtime/vm/hhbc-codec.h"
#include "hphp/runtime/vm/resumable.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/runtime/vm/unit.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/runtime/vm/jit/unwind-itanium.h"
namespace HPHP {
TRACE_SET_MOD(unwind);
using boost::implicit_cast;
namespace {
//////////////////////////////////////////////////////////////////////
#if (!defined(NDEBUG) || defined(USE_TRACE))
std::string describeEx(Either<ObjectData*, Exception*> exception) {
if (exception.left()) {
return folly::format("[user exception] {}",
implicit_cast<void*>(exception.left())).str();
}
return folly::format("[C++ exception] {}",
implicit_cast<void*>(exception.right())).str();
}
#endif
void discardStackTemps(const ActRec* const fp, Stack& stack) {
ITRACE(2, "discardStackTemps with fp {} sp {}\n",
implicit_cast<const void*>(fp),
implicit_cast<void*>(stack.top()));
visitStackElems(
fp, stack.top(),
[&] (TypedValue* tv) {
assertx(tv == stack.top());
ITRACE(2, " unwind pop TV : {}\n",
implicit_cast<void*>(stack.top()));
stack.popTV();
}
);
ITRACE(2, "discardStackTemps ends with sp = {}\n",
implicit_cast<void*>(stack.top()));
}
/**
* Discard the current frame, assuming that a PHP exception given in
* phpException argument, or C++ exception (phpException == nullptr)
* is being thrown. Returns an exception to propagate, or nulltpr
* if the VM execution should be resumed.
*/
ObjectData* tearDownFrame(ActRec*& fp, Stack& stack, PC& pc,
ObjectData* phpException, bool jit,
bool teardownStack) {
auto const func = fp->func();
auto const prevFp = fp->sfp();
auto const callOff = fp->callOffset();
ITRACE(1, "tearDownFrame: {} ({})\n",
func->fullName()->data(),
func->unit()->filepath()->data());
ITRACE(1, " fp {}, prevFp {}, jit {}\n",
implicit_cast<void*>(fp),
implicit_cast<void*>(prevFp),
jit);
auto const decRefLocals = [&] {
/*
* It is possible that locals have already been decref'd.
*
* Here's why:
*
* - If a destructor for any of these things throws a php
* exception, it's swallowed at the dtor boundary and we keep
* running php.
*
* - If the destructor for any of these things throws a fatal,
* it's swallowed, and we set surprise flags to throw a fatal
* from now on.
*
* - If the second case happened and we have to run another
* destructor, its enter hook will throw, but it will be
* swallowed again.
*
* - Finally, the exit hook for the returning function can
* throw, but this happens last so everything is destructed.
*
* - When that happens, exit hook sets localsDecRefd flag.
*/
if (fp->localsDecRefd()) return false;
fp->setLocalsDecRefd();
try {
if (teardownStack) {
frame_free_locals_helper_inl(fp, func->numLocals());
if (fp->func()->cls() && fp->hasThis()) decRefObj(fp->getThis());
fp->trashThis();
}
EventHook::FunctionUnwind(fp, phpException);
} catch (...) {}
return true;
};
if (LIKELY(!isResumed(fp))) {
auto const decRefd = decRefLocals();
if (UNLIKELY(func->isAsyncFunction()) &&
decRefd &&
phpException &&
(!fp->isAsyncEagerReturn() || func->isMemoizeImpl())) {
// If in an eagerly executed async function without request for async
// eager return, wrap the user exception into a failed StaticWaitHandle
// and return it to the caller.
auto const waitHandle = c_StaticWaitHandle::CreateFailed(phpException);
phpException = nullptr;
stack.ndiscard(func->numSlotsInFrame());
if (jit) {
jit::g_unwind_rds->fswh = waitHandle;
// Don't trash the ActRec since service-request-handlers might not need
// to read the call offset and func pointer
stack.retNoTrash();
} else {
stack.ret();
assertx(stack.topTV() == fp->retSlot());
tvCopy(make_tv<KindOfObject>(waitHandle), *fp->retSlot());
fp->retSlot()->m_aux.u_asyncEagerReturnFlag = 0;
}
} else {
// Free ActRec.
stack.ndiscard(func->numSlotsInFrame());
stack.discardAR();
// JIT may have optimized away NullUninit writes over the space reserved
// for inout outputs, so we need to discard them.
stack.ndiscard(func->numInOutParams());
}
} else if (func->isAsyncFunction()) {
auto const waitHandle = frame_afwh(fp);
if (phpException) {
// Handle exception thrown by async function.
decRefLocals();
waitHandle->fail(phpException);
decRefObj(waitHandle);
phpException = nullptr;
if (jit) jit::g_unwind_rds->fswh = nullptr;
} else if (waitHandle->isRunning()) {
// Let the C++ exception propagate. If the current frame represents async
// function that is running, mark it as abruptly interrupted. Some opcodes
// like Await may change state of the async function just before exit hook
// decides to throw C++ exception.
decRefLocals();
waitHandle->failCpp();
decRefObj(waitHandle);
}
} else if (func->isAsyncGenerator()) {
auto const gen = frame_async_generator(fp);
if (phpException) {
// Handle exception thrown by async generator.
decRefLocals();
auto eagerResult = gen->fail(phpException);
phpException = nullptr;
if (eagerResult) {
if (jit) {
jit::g_unwind_rds->fswh = eagerResult;
// Allocate space on the stack for the eagerResult to be written later
// SP needs to be consistent between interp and jit
stack.top()--;
} else {
stack.pushObjectNoRc(eagerResult);
}
} else {
if (jit) jit::g_unwind_rds->fswh = nullptr;
}
} else if (gen->isEagerlyExecuted() || gen->getWaitHandle()->isRunning()) {
// Fail the async generator and let the C++ exception propagate.
decRefLocals();
gen->failCpp();
}
} else if (func->isNonAsyncGenerator()) {
// Mark the generator as finished.
decRefLocals();
frame_generator(fp)->fail();
} else {
not_reached();
}
/*
* At the final ActRec in this nesting level.
*/
if (UNLIKELY(!prevFp)) {
pc = nullptr;
fp = nullptr;
return phpException;
}
assertx(stack.isValidAddress(reinterpret_cast<uintptr_t>(prevFp)) ||
isResumed(prevFp));
pc = prevFp->func()->at(callOff);
assertx(prevFp->func()->contains(pc));
fp = prevFp;
return phpException;
}
const StaticString s_previous("previous");
const Slot s_previousIdx{6};
DEBUG_ONLY bool is_throwable(ObjectData* throwable) {
auto const erCls = SystemLib::s_ErrorClass;
auto const exCls = SystemLib::s_ExceptionClass;
return throwable->instanceof(erCls) || throwable->instanceof(exCls);
}
DEBUG_ONLY bool throwable_has_expected_props() {
auto const erCls = SystemLib::s_ErrorClass;
auto const exCls = SystemLib::s_ExceptionClass;
if (erCls->lookupDeclProp(s_previous.get()) != s_previousIdx ||
exCls->lookupDeclProp(s_previous.get()) != s_previousIdx) {
return false;
}
// Check that we have the expected type-hints on these props so we don't need
// to verify anything when setting. If someone changes the type-hint we want
// to know.
auto const isException = [&](const TypeConstraint& tc) {
if (!tc.isUnresolved() && !tc.isObject()) return false;
auto const cls = Class::lookup(tc.anyNamedEntity());
return cls && cls == SystemLib::s_ExceptionClass;
};
return
isException(erCls->declPropTypeConstraint(s_previousIdx)) &&
isException(exCls->declPropTypeConstraint(s_previousIdx));
}
const StaticString s_hphpd_break("hphpd_break");
//////////////////////////////////////////////////////////////////////
}
Offset findCatchHandler(const Func* func, Offset raiseOffset) {
auto const eh = func->findEH(raiseOffset);
if (eh == nullptr) return kInvalidOffset;
return eh->m_handler;
}
void chainFaultObjects(ObjectData* top, ObjectData* prev) {
assertx(throwable_has_expected_props());
// We don't chain the fault objects if there is a cycle in top, prev, or the
// resulting chained fault object.
std::unordered_set<uintptr_t> seen;
// Walk head's previous pointers untill we find an unset one, or determine
// they form a cycle.
auto findAcyclicPrev = [&](ObjectData* head) {
tv_lval foundLval;
do {
assertx(is_throwable(head));
if (!seen.emplace((uintptr_t)head).second) return tv_lval();
foundLval = head->propLvalAtOffset(s_previousIdx);
assertx(foundLval.type() != KindOfUninit);
head = foundLval.val().pobj;
} while (foundLval.type() == KindOfObject &&
foundLval.val().pobj->instanceof(SystemLib::s_ThrowableClass));
return foundLval;
};
auto const prevLval = findAcyclicPrev(top);
if (!prevLval || !findAcyclicPrev(prev)) {
decRefObj(prev);
return;
}
// Found an unset previous pointer, and result will not have a cycle so chain
// the fault objects.
tvMove(make_tv<KindOfObject>(prev), prevLval);
}
void lockObjectWhileUnwinding(PC pc, Stack& stack) {
auto const op = decode_op(pc);
if (LIKELY(op != OpFCallCtor)) return;
auto fca = decodeFCallArgs(op, pc, nullptr /* StringDecoder */);
if (!fca.lockWhileUnwinding()) return;
// We just unwound from a constructor that was called from a new expression
// (as opposed to via e.g. parent::__construct()). The object being
// constructed is on the top of the stack, and needs to be locked.
auto const obj = stack.top();
assertx(tvIsObject(obj));
ITRACE(2, "Locking object {}\n", obj);
obj->m_data.pobj->lockObject();
}
/*
* Unwinding proceeds as follows:
*
* - Discard all evaluation stack temporaries.
*
* - Check if we are handling user exception in an eagerly executed
* async function. If so, pop its frame, wrap the exception into
* failed StaticWaitHandle object, leave it on the stack as
* a return value from the async function and resume VM.
*
* - Failing any of the above, pop the frame for the current
* function. If the current function was the last frame in the
* current VM nesting level, rethrow the exception, otherwise go
* to the first step and repeat this process in the caller's
* frame.
*
* If a non nullptr fpToUnwind is given, the unwinder will not unwind past
* fpToUnwind, instead return when vmfp() is equal to fpToUnwind.
*
* The return value UnwinderResult indicates whether we ended unwinding due to
* reaching fpToUnwind as well as whether we ended with putting a failed
* static wait handle on the stack.
*/
UnwinderResult unwindVM(Either<ObjectData*, Exception*> exception,
const ActRec* fpToUnwind /* = nullptr */,
bool teardown /* = true */) {
assertx(!exception.isNull());
auto phpException = exception.left();
if (phpException) phpException->incRefCount();
auto& fp = vmfp();
auto& stack = vmStack();
auto& pc = vmpc();
ITRACE(1, "entering unwinder for exception: {}\n", describeEx(exception));
SCOPE_EXIT {
ITRACE(1, "leaving unwinder for exception: {}\n", describeEx(exception));
};
while (true) {
auto const func = fp->func();
ITRACE(1, "unwind: func {}, raiseOffset {}, fp {}, sp {}, teardown {}\n",
func->name()->data(),
func->offsetOf(pc),
implicit_cast<void*>(fp),
implicit_cast<void*>(stack.top()),
teardown);
ITRACE(3, "Stack top: {}, stack base: {}\n",
stack.top(), Stack::anyFrameStackBase(fp));
if (teardown) discardStackTemps(fp, stack);
// Jitted teardown should have decreffed all the stack elements in the
// middle
assertx(stack.top() == Stack::anyFrameStackBase(fp));
// Note: we skip catch/finally clauses if we have a pending C++
// exception as part of our efforts to avoid running more PHP
// code in the face of such exceptions. Similarly, if the frame
// has already been torn down (eg an exception thrown by a user
// profiler on function exit), we can't execute any handlers in
// *this* frame.
if (RequestInfo::s_requestInfo->m_pendingException == nullptr &&
phpException && !UNLIKELY(fp->localsDecRefd())) {
const EHEnt* eh = func->findEH(func->offsetOf(pc));
if (eh != nullptr) {
// Found exception handler. Push the exception on top of the
// stack and resume VM.
ITRACE(1, "unwind: entering catch at {} func {} ({})\n",
eh->m_handler,
func->fullName()->data(),
func->unit()->filepath()->data());
vmStack().pushObjectNoRc(phpException);
pc = func->at(eh->m_handler);
DEBUGGER_ATTACHED_ONLY(phpDebuggerExceptionHandlerHook());
return UnwindNone;
}
}
// We found no more handlers in this frame.
auto const jit = fpToUnwind != nullptr && fpToUnwind == fp->m_sfp;
phpException = tearDownFrame(fp, stack, pc, phpException, jit, teardown);
// If we entered from the JIT and this is the last iteration, we can't
// trust the PC since catch traces for inlined frames may add more
// frames on vmfp()'s rbp chain which might have resulted in us incorrectly
// calculating the PC.
if (exception.left() != phpException) {
assertx(phpException == nullptr);
if (fp && !jit) pc = skipCall(pc);
ITRACE(1, "Returning with exception == null\n");
return UnwindFSWH;
}
if (!fp || (fpToUnwind && fp == fpToUnwind)) break;
lockObjectWhileUnwinding(pc, stack);
}
if (fp || fpToUnwind) {
assertx(fpToUnwind && (phpException || exception.right()));
ITRACE(1, "Reached {}\n", fpToUnwind);
if (phpException) phpException->decRefCount();
return UnwindReachedGoal;
}
ITRACE(1, "unwind: reached the end of this nesting's ActRec chain\n");
if (exception.right()) {
exception.right()->throwException();
not_reached();
}
assertx(phpException);
throw_object(Object::attach(phpException));
}
//////////////////////////////////////////////////////////////////////
}
| 16,057 | 5,033 |
// Copyright 2013 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 "cc/output/copy_output_result.h"
#include "base/logging.h"
#include "components/viz/common/quads/texture_mailbox.h"
namespace cc {
CopyOutputResult::CopyOutputResult() {}
CopyOutputResult::CopyOutputResult(std::unique_ptr<SkBitmap> bitmap)
: size_(bitmap->width(), bitmap->height()), bitmap_(std::move(bitmap)) {
DCHECK(bitmap_);
}
CopyOutputResult::CopyOutputResult(
const gfx::Size& size,
const viz::TextureMailbox& texture_mailbox,
std::unique_ptr<SingleReleaseCallback> release_callback)
: size_(size),
texture_mailbox_(texture_mailbox),
release_callback_(std::move(release_callback)) {
DCHECK(texture_mailbox_.IsTexture());
}
CopyOutputResult::~CopyOutputResult() {
if (release_callback_)
release_callback_->Run(gpu::SyncToken(), false);
}
std::unique_ptr<SkBitmap> CopyOutputResult::TakeBitmap() {
return std::move(bitmap_);
}
void CopyOutputResult::TakeTexture(
viz::TextureMailbox* texture_mailbox,
std::unique_ptr<SingleReleaseCallback>* release_callback) {
*texture_mailbox = texture_mailbox_;
*release_callback = std::move(release_callback_);
texture_mailbox_ = viz::TextureMailbox();
}
} // namespace cc
| 1,360 | 443 |
#pragma once
/*
* Name: RS485.hpp
*
* Copyright (c) Mateusz Semegen and contributors. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for details.
*/
#ifdef STM32L4
#include <soc/m4/stm32l4/peripherals/RS485.hpp>
#endif // STM32L4
namespace cml {
namespace hal {
#ifdef STM32L4
using RS485 = soc::m4::stm32l4::peripherals::RS485;
#endif // STM32L4
} // namespace hal
} // namespace cml
| 468 | 206 |
#include"EchoCommand.h"
bool EchoCommand::Execute(SOCKET sock, char* buf)
{
Sleep(2000);
if (!Send(sock, buf))
{
return false;
}
return true;
} | 173 | 71 |
#include<vector>
#include<algorithm>
#include<iostream>
#include<unordered_map>
using namespace std;
class Solution {
private:
struct Node {
int idx;
vector<Node*> children;
Node() : idx(-1), children(26, nullptr) {}
};
struct Trie {
Node* root;
Trie() : root(new Node()) {}
void insert(string& word, int idx)
{
Node* p = root;
for (char& c : word) {
c -= 'a';
if (p->children[c] == nullptr)
{
p->children[c] = new Node();
}
p = p->children[c];
}
p->idx = idx;
}
};
public:
vector<vector<int>> multiSearch(string big, vector<string>& smalls) {
unordered_map<string, vector<int>> cache;
const int n = big.size();
const int m = smalls.size();
vector<vector<int>> res(m);
Trie trie = Trie();
// 构造前缀树
for (int i = 0; i < m; i++)
{
trie.insert(smalls[i], i);
}
for (int i = 0; i < n; i++)
{
int j = i;
Node* node = trie.root;
while (j < n && node->children[big[j] - 'a'])
{
node = node->children[big[j] - 'a'];
if (node->idx != -1)
{
res[node->idx].push_back(i);
}
j++;
}
}
return res;
}
};
// Test
int main()
{
Solution sol;
string big = "mississippi";
vector<string> smalls = {"is", "ppi", "hi", "sis", "i", "ssippi"};
auto res = sol.multiSearch(big, smalls);
for (auto& row : res) // 遍历每一行
{
for (auto& elem : row) // 输出每一个元素
cout << elem << " ";
cout << "\n";
}
return 0;
} | 1,864 | 610 |
#include <ATen/ATen.h>
#include <ATen/ExpandUtils.h>
#include <ATen/Dispatch.h>
#include <ATen/NativeFunctions.h>
#include <ATen/LegacyTHFunctions.h>
#include <ATen/native/LinearAlgebraUtils.h>
#include <ATen/TensorUtils.h>
#include <ATen/Parallel.h>
#include <functional>
#include <numeric>
#include <vector>
#include <limits>
namespace at {
namespace native {
// Helper function for det methods.
// For pivoted LU factorization A = P * L * U. Since we always have det(L) = 1,
// det(P) = \pm 1, this method returns a 3-tuple:
// (det(P), diag(U), info),
// where info helps us identify singular matrices.
static inline std::tuple<double, Tensor, int> _lu_det_P_diag_U_info(const Tensor& self) {
Tensor p, lu, info;
std::tie(lu, p, info) = at::_lu_with_info(self, /*pivot=*/true, /*check_errors=*/false);
int int_info = info.item<int32_t>();
AT_CHECK(int_info >= 0, "LU factorization (getrf) failed with info = ", int_info);
auto n = self.size(0);
auto num_exchanges = (at::arange(1, n + 1, p.options()) != p).nonzero().size(0);
if (num_exchanges % 2 == 1) {
return std::make_tuple(-1., lu.diag(), int_info);
} else {
return std::make_tuple(1., lu.diag(), int_info);
}
}
Tensor det(const Tensor& self) {
AT_CHECK(at::isFloatingType(self.scalar_type()) &&
self.dim() == 2 && self.size(0) == self.size(1),
"det(", self.type(), "{", self.sizes(), "}): expected a 2D square tensor "
"of floating types");
double det_P;
Tensor diag_U;
int info;
std::tie(det_P, diag_U, info) = _lu_det_P_diag_U_info(self);
if (info > 0) {
return at::zeros({}, self.options());
} else {
return diag_U.prod().mul_(det_P);
}
}
Tensor logdet(const Tensor& self) {
AT_CHECK(at::isFloatingType(self.scalar_type()) &&
self.dim() == 2 && self.size(0) == self.size(1),
"logdet(", self.type(), "{", self.sizes(), "}): expected a 2D square tensor "
"of floating types");
double det_P;
Tensor diag_U;
int info;
std::tie(det_P, diag_U, info) = _lu_det_P_diag_U_info(self);
if (info > 0) {
return at::full({}, -std::numeric_limits<double>::infinity(), self.options());
}
// `det_sign` is the sign of the determinant. We work on `diag_U.sign()` for
// numerical stability when diag_U has a lot small values.
auto det_sign = diag_U.sign().prod().mul_(det_P);
// This synchronizes on GPU, but `_lu_det_P_diag_U_info` above already synchronizes
if (det_sign.item<double>() <= 0) {
return det_sign.log_(); // get proper nan (det<0) or -inf (det=0)
} else {
return diag_U.abs_().log_().sum();
}
}
std::tuple<Tensor, Tensor> slogdet(const Tensor& self) {
AT_CHECK(at::isFloatingType(self.scalar_type()) &&
self.dim() == 2 && self.size(0) == self.size(1),
"slogdet(", self.type(), "{", self.sizes(), "}): expected a 2D square tensor "
"of floating types");
double det_P;
Tensor diag_U;
int info;
std::tie(det_P, diag_U, info) = _lu_det_P_diag_U_info(self);
if (info > 0) {
return std::make_tuple(at::zeros({}, self.options()),
at::full({}, -std::numeric_limits<double>::infinity(), self.options()));
} else {
// `det_sign` is the sign of the determinant. We work on `diag_U.sign()` for
// numerical stability when diag_U has a lot small values.
auto det_sign = diag_U.sign().prod().mul_(det_P);
return std::make_tuple(det_sign, diag_U.abs_().log_().sum());
}
}
Tensor pinverse(const Tensor& self, double rcond) {
AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2,
"pinverse(", self.type(), "{", self.sizes(), "}): expected a 2D tensor "
"of floating types");
if (self.numel() == 0) {
// Match NumPy
return at::empty({self.size(1), self.size(0)}, self.options());
}
Tensor U, S, V;
std::tie(U, S, V) = self.svd();
Tensor max_val = S[0];
Tensor S_pseudoinv = at::where(S > rcond * max_val, S.reciprocal(), at::zeros({}, self.options()));
return V.mm(S_pseudoinv.diag().mm(U.t()));
}
static inline Tensor _matrix_rank_helper(const Tensor& self, bool symmetric) {
Tensor S;
if (!symmetric) {
Tensor U, V;
std::tie(U, S, V) = self.svd(/*some=*/true, /*compute_uv=*/false);
} else {
Tensor eigvecs;
std::tie(S, eigvecs) = self.symeig(/*eigenvectors=*/false);
S = S.abs();
}
return S;
}
Tensor matrix_rank(const Tensor& self, double tol, bool symmetric) {
AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2,
"matrix_rank(", self.type(), "{", self.sizes(), "}): expected a 2D tensor "
"of floating types");
Tensor S = _matrix_rank_helper(self, symmetric);
return (S > tol).sum();
}
Tensor matrix_rank(const Tensor& self, bool symmetric) {
AT_CHECK(at::isFloatingType(self.scalar_type()) && self.dim() == 2,
"matrix_rank(", self.type(), "{", self.sizes(), "}): expected a 2D tensor "
"of floating types");
Tensor S = _matrix_rank_helper(self, symmetric);
double tol = _get_epsilon(self.scalar_type()) * std::max(self.size(0), self.size(1));
return (S > S.max().mul_(tol)).sum();
}
static void check_1d(const Tensor& t, const char* arg, const char* fn) {
AT_CHECK(t.dim() == 1, fn, ": Expected 1-D argument ", arg, ", but got ", t.dim(), "-D");
}
Tensor ger(const Tensor& self, const Tensor& vec2) {
check_1d(self, "self", "ger");
check_1d(vec2, "vec2", "ger");
return at::legacy::th::_th_ger(self, vec2);
}
Tensor& ger_out(Tensor& result, const Tensor& self, const Tensor& vec2) {
check_1d(self, "self", "ger");
check_1d(vec2, "vec2", "ger");
return at::legacy::th::_th_ger_out(result, self, vec2);
}
Tensor mm(const Tensor& self, const Tensor& mat2) {
if (self.is_sparse()) {
return at::zeros({}, mat2.options()).addmm(self, mat2, 0, 1);
}
return at::legacy::th::_th_mm(self, mat2);
}
Tensor& mm_out(Tensor& result, const Tensor& self, const Tensor& mat2) {
if (self.is_sparse()) {
return at::addmm_out(result, at::zeros({}, mat2.options()), self, mat2, 0, 1);
}
return at::legacy::th::_th_mm_out(result, self, mat2);
}
Tensor mv(const Tensor& self, const Tensor& vec) {
check_1d(vec, "vec", "mv");
return at::legacy::th::_th_mv(self, vec);
}
Tensor& mv_out(Tensor& result, const Tensor& self, const Tensor& vec) {
check_1d(vec, "vec", "mv");
return at::legacy::th::_th_mv_out(result, self, vec);
}
Tensor addmv(const Tensor& self, const Tensor& mat, const Tensor& vec, Scalar beta, Scalar alpha) {
check_1d(vec, "vec", "addmv");
return at::legacy::th::_th_addmv(self, mat, vec, beta, alpha);
}
Tensor& addmv_(Tensor& self, const Tensor& mat, const Tensor& vec, Scalar beta, Scalar alpha) {
check_1d(vec, "vec", "addmv");
return at::legacy::th::_th_addmv_(self, mat, vec, beta, alpha);
}
Tensor& addmv_out(Tensor &result, const Tensor& self, const Tensor& mat, const Tensor& vec, Scalar beta, Scalar alpha) {
check_1d(vec, "vec", "addmv");
return at::legacy::th::_th_addmv_out(result, self, mat, vec, beta, alpha);
}
Tensor addr(const Tensor& self, const Tensor& vec1, const Tensor& vec2, Scalar beta, Scalar alpha) {
check_1d(vec1, "vec1", "addr");
check_1d(vec2, "vec2", "addr");
return at::legacy::th::_th_addr(self, vec1, vec2, beta, alpha);
}
Tensor& addr_(Tensor& self, const Tensor& vec1, const Tensor& vec2, Scalar beta, Scalar alpha) {
check_1d(vec1, "vec1", "addr");
check_1d(vec2, "vec2", "addr");
return at::legacy::th::_th_addr_(self, vec1, vec2, beta, alpha);
}
Tensor& addr_out(Tensor &result, const Tensor& self, const Tensor& vec1, const Tensor& vec2, Scalar beta, Scalar alpha) {
check_1d(vec1, "vec1", "addr");
check_1d(vec2, "vec2", "addr");
return at::legacy::th::_th_addr_out(result, self, vec1, vec2, beta, alpha);
}
template <typename scalar_t, bool is_bmm>
inline void baddbmm_cpu_kernel(const Tensor& result, const Tensor& self, const Tensor& mat2, Scalar beta_, Scalar alpha_) {
int64_t bs = result.size(0);
int64_t is = result.size(1);
int64_t js = result.size(2);
int64_t ks = self.size(2);
scalar_t alpha = alpha_.to<scalar_t>();
scalar_t beta = beta_.to<scalar_t>();
auto r0 = result.accessor<scalar_t, 3>();
auto s0 = self.accessor<scalar_t, 3>();
auto m0 = mat2.accessor<scalar_t, 3>();
int64_t grain_size = std::min(internal::GRAIN_SIZE / (is * js * ks), (int64_t)1);
parallel_for(0, bs, grain_size, [&](int64_t b_begin, int64_t b_end) {
for (int64_t b = b_begin; b < b_end; b++) {
auto r1 = r0[b];
auto s1 = s0[b];
auto m1 = m0[b];
for (int64_t i = 0; i < is; i++) {
auto r2 = r1[i];
auto s2 = s1[i];
for (int64_t j = 0; j < js; j++) {
scalar_t &r = r2[j];
if (is_bmm) {
r = 0;
for (int64_t k = 0; k < ks; k++) {
r += s2[k] * m1[k][j];
}
} else {
r *= beta;
for (int64_t k = 0; k < ks; k++) {
r += alpha * s2[k] * m1[k][j];
}
}
}
}
}
});
}
// This tries to apply some optimizations to bmm/baddbmm:
// - When the operand size is small, computation are parallelized over the batch
// dimension using OMP and naive matrix multiplication is applied.
// - When the operand size is larger than the threshold, if compiled with MKL, MKL's batch gemm is used.
// - Otherwise, we use a series of matrix multiplications.
// The threshold of 400 for the first has not been thoroughly benchmarked yet and may have room for further
// optimization, it likely depends on the characteristics of the CPU, MKL will be different from non-MKL etc.,
// but this seems to be a first starting point.
static inline Tensor& bmm_out_or_baddbmm_(Tensor& self_or_result, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha, bool is_bmm_out) {
// is_bmm_out: true for bmm_out, false for baddbmm_
// self_or_result is "self" for baddbmm_ and "result" for bmm_out
CheckedFrom c = (is_bmm_out ? "bmm" : "baddbmm");
TensorArg self_arg(self_or_result, is_bmm_out ? "self" : "result", 0);
TensorArg b1_arg(batch1, "batch1", 1);
TensorArg b2_arg(batch2, "batch2", 2);
checkBackend(c, {self_or_result, batch1, batch2}, Backend::CPU);
checkDim(c, b1_arg, 3);
checkDim(c, b2_arg, 3);
int64_t bs = batch1.size(0);
checkSize(c, b2_arg, 0, bs);
int64_t contraction_size = batch1.size(2);
int64_t res_rows = batch1.size(1);
int64_t res_cols = batch2.size(2);
checkSize(c, b2_arg, 1, contraction_size);
if (is_bmm_out) {
self_or_result.resize_({bs, res_rows, res_cols});
} else {
checkSize(c, self_arg, 0, bs);
checkSize(c, self_arg, 1, res_rows);
checkSize(c, self_arg, 2, res_cols);
}
// handle pathological cases that blas may not like
if (self_or_result.numel() == 0) {
return self_or_result;
} else if (contraction_size == 0) {
return self_or_result.zero_();
}
auto batch_items_contiguous_or_transposed = [&](const Tensor& t) {
return (t.stride(2) == 1 && t.stride(1) >= t.size(2))
|| (t.stride(1) == 1 && t.stride(2) >= t.size(1));
};
if (contraction_size * res_rows * res_cols < 400) {
if (is_bmm_out) {
AT_DISPATCH_ALL_TYPES(batch1.scalar_type(), "bmm", [&] {
baddbmm_cpu_kernel<scalar_t, true>(self_or_result, batch1, batch2, beta, alpha);
});
} else {
AT_DISPATCH_ALL_TYPES(batch1.scalar_type(), "baddbmm", [&] {
baddbmm_cpu_kernel<scalar_t, false>(self_or_result, batch1, batch2, beta, alpha);
});
}
} else if (at::hasMKL() && at::native::is_floating_point(self_or_result)
&& batch_items_contiguous_or_transposed(batch1)
&& batch_items_contiguous_or_transposed(batch2)
&& self_or_result.is_contiguous()) {
at::native::_baddbmm_mkl_(self_or_result, batch1, batch2, beta, alpha);
} else { // split along batch dimension
if (is_bmm_out) {
for (int64_t b = 0; b < bs; b++) {
auto r = self_or_result.select(0, b);
at::native::mm_out(r, batch1.select(0, b), batch2.select(0, b));
}
} else {
for (int64_t b = 0; b < bs; b++) {
self_or_result.select(0, b).addmm_(batch1.select(0, b), batch2.select(0, b), beta, alpha);
}
}
}
return self_or_result;
}
Tensor baddbmm_cpu(const Tensor& self, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha) {
Tensor result = at::empty({0}, self.options());
return at::native::baddbmm_out_cpu(result, self, batch1, batch2, beta, alpha);
}
Tensor& baddbmm_out_cpu(Tensor &result, const Tensor& self_, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha) {
Tensor self;
std::tie(self) = expand_size(self_, {batch1.size(0), batch1.size(1), batch2.size(2)}, "baddbmm");
result.resize_(self.sizes());
result.copy_(self);
return at::native::baddbmm__cpu(result, batch1, batch2, beta, alpha);
}
Tensor& baddbmm__cpu(Tensor& self, const Tensor& batch1, const Tensor& batch2, Scalar beta, Scalar alpha) {
return bmm_out_or_baddbmm_(self, batch1, batch2, beta, alpha, false);
}
Tensor bmm_cpu(const Tensor& self, const Tensor& mat2) {
Tensor result = at::empty({0}, self.options());
return at::native::bmm_out_cpu(result, self, mat2);
}
Tensor& bmm_out_cpu(Tensor &result, const Tensor& batch1, const Tensor& batch2) {
Scalar beta(0.0);
Scalar alpha(1.0);
return bmm_out_or_baddbmm_(result, batch1, batch2, beta, alpha, true);
}
Tensor dot(const Tensor& self, const Tensor& tensor) {
check_1d(self, "self", "dot");
check_1d(tensor, "tensor", "dot");
return at::legacy::th::_th_dot(self, tensor);
}
Tensor& dot_out(Tensor& result, const Tensor& self, const Tensor& tensor) {
result.resize_({});
AT_CHECK(result.scalar_type() == self.scalar_type(),
"result dtype ", result.scalar_type(), " does not match self dtype ", self.scalar_type());
return result.fill_(self.dot(tensor));
}
/*
Matrix product of two Tensors.
The behavior depends on the dimensionality of the Tensors as follows:
- If both Tensors are 1-dimensional, the dot product (scalar) is returned.
- If both arguments are 2-dimensional, the matrix-matrix product is returned.
- If the first argument is 1-dimensional and the second argument is 2-dimensional,
a 1 is prepended to its dimension for the purpose of the matrix multiply.
After the matrix multiply, the prepended dimension is removed.
- If the first argument is 2-dimensional and the second argument is 1-dimensional,
the matrix-vector product is returned.
- If both arguments are at least 1-dimensional and at least one argument is
N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first
argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the
batched matrix multiply and removed after. If the second argument is 1-dimensional, a
1 is appended to its dimension for the purpose of the batched matrix multiple and removed after.
The non-matrix (i.e. batch) dimensions are broadcasted (and thus
must be broadcastable). For example, if tensor1 is a (j x 1 x n x m) Tensor
and tensor2 is a (k x m x p) Tensor, the returned tensor will be an (j x k x n x p) Tensor.
*/
Tensor matmul(
c10::optional<Tensor> out_opt,
const Tensor& tensor1,
const Tensor& tensor2) {
auto dim_tensor1 = tensor1.dim();
auto dim_tensor2 = tensor2.dim();
auto has_out = out_opt.has_value();
Tensor out = out_opt.value_or(Tensor());
if (dim_tensor1 == 1 && dim_tensor2 == 1) {
return has_out ? at::native::dot_out(out, tensor1, tensor2) : tensor1.dot(tensor2);
} else if (dim_tensor1 == 2 && dim_tensor2 == 1) {
return has_out ? at::native::mv_out(out, tensor1, tensor2) : tensor1.mv(tensor2);
} else if (dim_tensor1 == 1 && dim_tensor2 == 2) {
return has_out ? at::native::mm_out(out, tensor1.unsqueeze(0), tensor2).squeeze_(0)
: tensor1.unsqueeze(0).mm(tensor2).squeeze_(0);
} else if (dim_tensor1 == 2 && dim_tensor2 == 2) {
return has_out ? at::native::mm_out(out, tensor1, tensor2) : tensor1.mm(tensor2);
} else if (dim_tensor1 >= 3 && (dim_tensor2 == 1 || dim_tensor2 == 2)) {
// optimization: use mm instead of bmm by folding tensor1's batch into
// its leading matrix dimension.
Tensor t2 = dim_tensor2 == 1 ? tensor2.unsqueeze(-1) : tensor2;
auto size1 = tensor1.sizes();
auto size2 = t2.sizes();
std::vector<int64_t> output_size;
output_size.insert(output_size.end(), size1.begin(), size1.end() - 1);
if (dim_tensor2 > 1) {
output_size.push_back(size2[dim_tensor2 - 1]);
}
// fold the batch into the first dimension
Tensor t1 = tensor1.contiguous().view({-1, size1[size1.size() - 1]});
Tensor output = has_out ? at::_unsafe_view(at::mm_out(out, t1, t2), output_size)
: at::_unsafe_view(t1.mm(t2), output_size);
return has_out ? out.set_(output) : output;
} else if ((dim_tensor1 >= 1 && dim_tensor2 >= 1) && (dim_tensor1 >= 3 || dim_tensor2 >= 3)) {
// We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list);
// we track m1 vs m2 separately even though they must match for nicer error messages
int64_t n = dim_tensor1 > 1 ? tensor1.size(-2) : 1;
int64_t m1 = tensor1.size(-1);
IntArrayRef batch_tensor1(tensor1.sizes().data(), std::max<int64_t>(dim_tensor1 - 2, 0));
int64_t m2 = dim_tensor2 > 1 ? tensor2.size(-2) : 1;
int64_t p = tensor2.size(-1);
IntArrayRef batch_tensor2(tensor2.sizes().data(), std::max<int64_t>(dim_tensor2 - 2, 0));
// expand the batch portion (i.e. cut off matrix dimensions and expand rest)
std::vector<int64_t> expand_batch_portion = infer_size(batch_tensor1, batch_tensor2);
std::vector<int64_t> tensor1_expand_size(expand_batch_portion);
tensor1_expand_size.insert(tensor1_expand_size.end(), {n, m1});
std::vector<int64_t> tensor2_expand_size(expand_batch_portion);
tensor2_expand_size.insert(tensor2_expand_size.end(), {m2, p});
int expand_batch_product = std::accumulate(expand_batch_portion.begin(), expand_batch_portion.end(),
1, std::multiplies<int64_t>());
std::vector<int64_t> tensor1_bmm_view({expand_batch_product});
tensor1_bmm_view.insert(tensor1_bmm_view.end(), {n, m1});
std::vector<int64_t> tensor2_bmm_view({expand_batch_product});
tensor2_bmm_view.insert(tensor2_bmm_view.end(), {m2, p});
// flatten expanded batches
Tensor tensor1_expanded = tensor1.expand(tensor1_expand_size).contiguous().view(tensor1_bmm_view);
Tensor tensor2_expanded = tensor2.expand(tensor2_expand_size).contiguous().view(tensor2_bmm_view);
// reshape batches back into result
std::vector<int64_t> output_shape(expand_batch_portion);
if (dim_tensor1 > 1) {
output_shape.push_back(n);
}
if (dim_tensor2 > 1) {
output_shape.push_back(p);
}
Tensor output = has_out ? at::_unsafe_view(at::bmm_out(out, tensor1_expanded, tensor2_expanded), output_shape)
: at::_unsafe_view(tensor1_expanded.bmm(tensor2_expanded), output_shape);
return has_out ? out.set_(output) : output;
}
AT_ERROR("both arguments to matmul need to be at least 1D, but they are ",
dim_tensor1, "D and ", dim_tensor2, "D");
}
Tensor matmul(const Tensor & tensor1, const Tensor & tensor2) {
return at::native::matmul(c10::nullopt, tensor1, tensor2);
}
Tensor& matmul_out(Tensor &result, const Tensor & tensor1, const Tensor & tensor2) {
at::native::matmul(c10::optional<Tensor>(result), tensor1, tensor2);
return result;
}
Tensor matrix_power(const Tensor& a, int64_t n) {
AT_CHECK(a.dim() >= 2 && at::isFloatingType(a.scalar_type()),
"matrix_power(", a.type(), "{", a.sizes(), "}): expected a tensor "
"of floating types with dim at least 2");
if (n == 0) {
return a.clone().copy_(at::eye(a.size(-2), a.options()).expand_as(a));
} else if (n < 0) {
Tensor a_ = at::inverse(a);
n *= -1;
return at::native::matrix_power(a_, n);
} else if (n == 1) {
return a.clone();
} else if (n == 2) {
return at::native::matmul(a, a);
} else if (n == 3) {
return at::native::matmul(at::native::matmul(a, a), a);
}
// This is a binary decomposition of n.
// Moving from the least significant bit to the most significant bit
// This is done to reduce the number of matrix multiplications
// by raising the input matrix in powers of 2
// The total number of matrix multiplications are
// number of bits + number of bits that equal 1 ~ O(log n)
// instead of O(n)
Tensor result, z;
int64_t r;
while (n > 0) {
z = (!z.defined()) ? a.clone() : at::native::matmul(z, z);
r = n % 2;
n = n / 2;
if (r == 1) {
result = (!result.defined()) ? z.clone() : at::native::matmul(result, z);
}
}
return result;
}
Tensor frobenius_norm(const Tensor& self) {
return at::norm(self);
}
Tensor frobenius_norm(const Tensor& self, IntArrayRef dim, bool keepdim) {
AT_CHECK(
dim.size() <= 2,
"Expected at most 2 dimensions, but got ",
dim.size(),
" dimensions instead.");
if (dim.size() == 1) {
return at::norm(self, 2, dim, keepdim, self.scalar_type());
}
return at::sqrt(at::sum(self * self, dim, keepdim));
}
Tensor &frobenius_norm_out(
Tensor& result,
const Tensor& self,
IntArrayRef dim,
bool keepdim) {
AT_CHECK(
dim.size() <= 2,
"Expected at most 2 dimensions, but got ",
dim.size(),
" dimensions instead.");
if (dim.size() == 1) {
return at::norm_out(result, self, 2, dim, keepdim, self.scalar_type());
}
return at::sqrt_out(result, at::sum(self * self, dim, keepdim));
}
Tensor nuclear_norm(const Tensor& self, bool keepdim) {
AT_CHECK(
self.dim() == 2,
"Expected a tensor with 2 dimensions, but got a ",
self.dim(),
" dimensions tensor instead.");
return at::sum(std::get<1>(at::svd(self)), 0, keepdim);
}
Tensor &nuclear_norm_out(Tensor& result, const Tensor& self, bool keepdim) {
AT_CHECK(
self.dim() == 2,
"Expected a tensor with 2 dimensions, but got a ",
self.dim(),
" dimensions tensor instead.");
return at::sum_out(result, std::get<1>(at::svd(self)), 0, keepdim);
}
static inline Tensor _chain_matmul_general(TensorList matrices, std::vector<std::vector<int64_t>>& order, int64_t i, int64_t j) {
if (i == j)
return matrices[i];
else
return at::mm(_chain_matmul_general(matrices, order, i, order[i][j]), _chain_matmul_general(matrices, order, order[i][j] + 1, j));
}
// Why the separate implementation for 3 matrices?
// The logic for three matrices is much faster when done directly
// Requires 1 comparison to 4 comparisons and lesser arithmetic operations
static inline Tensor _chain_matmul_three_matrices(TensorList matrices) {
int64_t a = matrices[0].size(0); // This is the first dimension
int64_t b = matrices[1].size(0); // This is the common dimension between the first two matrices
int64_t c = matrices[2].size(0); // This is the common dimension between the last two matrices
int64_t d = matrices[2].size(1); // This is the last dimension
// The matrices are of size (a x b), (b x c), (c x d)
// cost_1 is the cost of parenthesizing (a x b) and (b x c) and then combining (c x d)
// cost_2 is the cost of parenthesizing (b x c) and (c x d) and then combining (a x b)
int64_t cost_1 = (a * c) * (b + d);
int64_t cost_2 = (b * d) * (a + c);
if (cost_1 > cost_2) {
return at::mm(matrices[0], at::mm(matrices[1], matrices[2]));
} else {
return at::mm(at::mm(matrices[0], matrices[1]), matrices[2]);
}
}
Tensor chain_matmul(TensorList matrices) {
checkAllSameDim(matrices, 2);
if (matrices.size() == 1) {
return matrices[0];
} else if (matrices.size() == 2) {
return at::mm(matrices[0], matrices[1]);
} else if (matrices.size() == 3) {
return _chain_matmul_three_matrices(matrices);
} else {
// Following the algorithm in Chapter 15.2 : Introduction to Algorithms, Cormen et al.
// Minor modifications have been made to accommodate zero-indexing
auto n = matrices.size();
// Dim vector - the length of which is n + 1. Note that for matrix multiplication, there
// needs to a common dimension between the multiplicands, hence for n matrices, there are
// n + 1 values. The values p_{i} and p_{i + 1} correspond to the dimensions of matrix i in
// the chain (zero-indexed)
std::vector<int64_t> p;
p.push_back(matrices[0].size(0));
for (int64_t i = 0; i < n; i++) {
p.push_back(matrices[i].size(1));
}
// Cost matrix - an element m[i, j] of this matrix corresponds to the minimum cost of
// parenthesizing matrices A_{i} to A_{j}. By this definition m[i, i] = 0 for all i
// m[i, j] is filled using the substructure property of the algorithm, meaning:
// m[i, j] = min_{i <= k < j} m[i, k] + m[k, j] + p_{i-1}p_{k}p_{j}
std::vector<std::vector<int64_t>> m(n, std::vector<int64_t>(n, 0));
// Auxiliary table for constructing the order
// s[i, j] stores the index k at which the optimal split is obtained
std::vector<std::vector<int64_t>> s(n, std::vector<int64_t>(n));
// j and q are used repetitively in the algorithm below
int64_t j, q;
for (int64_t l = 1; l < n; l++) {
for (int64_t i = 0; i < n - l; i++) {
j = i + l;
m[i][j] = std::numeric_limits<int64_t>::max();
for (int64_t k = i; k < j; k++) {
q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1];
if (q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
// We use the result from the algorithm to compute the matrix chain product via recursion
return _chain_matmul_general(matrices, s, 0, n - 1);
}
}
} // namespace native
} // namespace at
| 26,057 | 9,851 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "olap/reader.h"
#include <parallel_hashmap/phmap.h>
#include <boost/algorithm/string/case_conv.hpp>
#include <charconv>
#include <unordered_set>
#include "olap/bloom_filter_predicate.h"
#include "olap/collect_iterator.h"
#include "vec/olap/vcollect_iterator.h"
#include "olap/comparison_predicate.h"
#include "olap/in_list_predicate.h"
#include "olap/null_predicate.h"
#include "olap/row.h"
#include "olap/row_block.h"
#include "olap/row_cursor.h"
#include "olap/rowset/beta_rowset_reader.h"
#include "olap/rowset/column_data.h"
#include "olap/schema.h"
#include "olap/storage_engine.h"
#include "olap/tablet.h"
#include "runtime/mem_pool.h"
#include "runtime/mem_tracker.h"
#include "runtime/string_value.hpp"
#include "util/date_func.h"
#include "util/mem_util.hpp"
using std::nothrow;
using std::set;
using std::vector;
namespace doris {
void ReaderParams::check_validation() const {
if (UNLIKELY(version.first == -1)) {
LOG(FATAL) << "version is not set. tablet=" << tablet->full_name();
}
}
std::string ReaderParams::to_string() const {
std::stringstream ss;
ss << "tablet=" << tablet->full_name() << " reader_type=" << reader_type
<< " aggregation=" << aggregation << " version=" << version << " start_key_include=" << start_key_include
<< " end_key_include=" << end_key_include;
for (const auto& key : start_key) {
ss << " keys=" << key;
}
for (const auto& key : end_key) {
ss << " end_keys=" << key;
}
for (auto& condition : conditions) {
ss << " conditions=" << apache::thrift::ThriftDebugString(condition);
}
return ss.str();
}
KeysParam::~KeysParam() {
for (auto start_key : start_keys) {
SAFE_DELETE(start_key);
}
for (auto end_key : end_keys) {
SAFE_DELETE(end_key);
}
}
std::string KeysParam::to_string() const {
std::stringstream ss;
ss << "start_key_include=" << start_key_include << " end_key_include=" << end_key_include;
for (auto start_key : start_keys) {
ss << " keys=" << start_key->to_string();
}
for (auto end_key : end_keys) {
ss << " end_keys=" << end_key->to_string();
}
return ss.str();
}
Reader::Reader() : _collect_iter(new CollectIterator()) {}
Reader::~Reader() {
VLOG_NOTICE << "merged rows:" << _merged_rows;
_conditions.finalize();
if (!_all_conditions.empty()) {
_all_conditions.finalize();
}
_delete_handler.finalize();
for (auto pred : _col_predicates) {
delete pred;
}
for (auto pred : _value_col_predicates) {
delete pred;
}
}
OLAPStatus Reader::init(const ReaderParams& read_params) {
// TODO(yingchun): monitor
_tracker.reset(new MemTracker(-1, read_params.tablet->full_name()));
_predicate_mem_pool.reset(new MemPool(_tracker.get()));
OLAPStatus res = _init_params(read_params);
if (res != OLAP_SUCCESS) {
LOG(WARNING) << "fail to init reader when init params. res:" << res
<< ", tablet_id:" << read_params.tablet->tablet_id()
<< ", schema_hash:" << read_params.tablet->schema_hash()
<< ", reader type:" << read_params.reader_type
<< ", version:" << read_params.version;
return res;
}
std::vector<RowsetReaderSharedPtr> rs_readers;
res = _capture_rs_readers(read_params, &rs_readers);
if (res != OLAP_SUCCESS) {
LOG(WARNING) << "fail to init reader when _capture_rs_readers. res:" << res
<< ", tablet_id:" << read_params.tablet->tablet_id()
<< ", schema_hash:" << read_params.tablet->schema_hash()
<< ", reader_type:" << read_params.reader_type
<< ", version:" << read_params.version;
return res;
}
return OLAP_SUCCESS;
}
// When only one rowset has data, and this rowset is nonoverlapping, we can read directly without aggregation
bool Reader::_optimize_for_single_rowset(const std::vector<RowsetReaderSharedPtr>& rs_readers) {
bool has_delete_rowset = false;
bool has_overlapping = false;
int nonoverlapping_count = 0;
for (const auto& rs_reader : rs_readers) {
if (rs_reader->rowset()->rowset_meta()->delete_flag()) {
has_delete_rowset = true;
break;
}
if (rs_reader->rowset()->rowset_meta()->num_rows() > 0) {
if (rs_reader->rowset()->rowset_meta()->is_segments_overlapping()) {
// when there are overlapping segments, can not do directly read
has_overlapping = true;
break;
} else if (++nonoverlapping_count > 1) {
break;
}
}
}
return !has_overlapping && nonoverlapping_count == 1 && !has_delete_rowset;
}
OLAPStatus Reader::_capture_rs_readers(const ReaderParams& read_params,
std::vector<RowsetReaderSharedPtr>* valid_rs_readers) {
const std::vector<RowsetReaderSharedPtr>* rs_readers = &read_params.rs_readers;
if (rs_readers->empty()) {
LOG(WARNING) << "fail to acquire data sources. tablet=" << _tablet->full_name();
return OLAP_ERR_VERSION_NOT_EXIST;
}
bool eof = false;
bool is_lower_key_included = _keys_param.start_key_include;
bool is_upper_key_included = _keys_param.end_key_include;
for (int i = 0; i < _keys_param.start_keys.size(); ++i) {
// lower bound
RowCursor* start_key = _keys_param.start_keys[i];
RowCursor* end_key = _keys_param.end_keys[i];
if (!is_lower_key_included) {
if (end_key != nullptr && compare_row_key(*start_key, *end_key) >= 0) {
VLOG_NOTICE << "return EOF when lower key not include"
<< ", start_key=" << start_key->to_string()
<< ", end_key=" << end_key->to_string();
eof = true;
break;
}
} else {
if (end_key != nullptr && compare_row_key(*start_key, *end_key) > 0) {
VLOG_NOTICE << "return EOF when lower key include="
<< ", start_key=" << start_key->to_string()
<< ", end_key=" << end_key->to_string();
eof = true;
break;
}
}
_is_lower_keys_included.push_back(is_lower_key_included);
_is_upper_keys_included.push_back(is_upper_key_included);
}
if (eof) {
return OLAP_SUCCESS;
}
bool need_ordered_result = true;
if (read_params.reader_type == READER_QUERY) {
if (_tablet->tablet_schema().keys_type() == DUP_KEYS) {
// duplicated keys are allowed, no need to merge sort keys in rowset
need_ordered_result = false;
}
if (_aggregation) {
// compute engine will aggregate rows with the same key,
// it's ok for rowset to return unordered result
need_ordered_result = false;
}
}
_reader_context.reader_type = read_params.reader_type;
_reader_context.tablet_schema = &_tablet->tablet_schema();
_reader_context.need_ordered_result = need_ordered_result;
_reader_context.return_columns = &_return_columns;
_reader_context.seek_columns = &_seek_columns;
_reader_context.load_bf_columns = &_load_bf_columns;
_reader_context.load_bf_all_columns = &_load_bf_all_columns;
_reader_context.conditions = &_conditions;
_reader_context.all_conditions = &_all_conditions;
_reader_context.predicates = &_col_predicates;
_reader_context.value_predicates = &_value_col_predicates;
_reader_context.lower_bound_keys = &_keys_param.start_keys;
_reader_context.is_lower_keys_included = &_is_lower_keys_included;
_reader_context.upper_bound_keys = &_keys_param.end_keys;
_reader_context.is_upper_keys_included = &_is_upper_keys_included;
_reader_context.delete_handler = &_delete_handler;
_reader_context.stats = &_stats;
_reader_context.runtime_state = read_params.runtime_state;
_reader_context.use_page_cache = read_params.use_page_cache;
_reader_context.sequence_id_idx = _sequence_col_idx;
*valid_rs_readers = *rs_readers;
return OLAP_SUCCESS;
}
OLAPStatus Reader::_init_params(const ReaderParams& read_params) {
read_params.check_validation();
_aggregation = read_params.aggregation;
_need_agg_finalize = read_params.need_agg_finalize;
_reader_type = read_params.reader_type;
_tablet = read_params.tablet;
_init_conditions_param(read_params);
_init_load_bf_columns(read_params);
OLAPStatus res = _init_delete_condition(read_params);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to init delete param. [res=%d]", res);
return res;
}
res = _init_return_columns(read_params);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to init return columns. [res=%d]", res);
return res;
}
res = _init_keys_param(read_params);
if (res != OLAP_SUCCESS) {
LOG(WARNING) << "fail to init keys param. res=" << res;
return res;
}
_init_seek_columns();
_collect_iter->init(this);
if (_tablet->tablet_schema().has_sequence_col()) {
auto sequence_col_idx = _tablet->tablet_schema().sequence_col_idx();
DCHECK_NE(sequence_col_idx, -1);
for (auto col : _return_columns) {
// query has sequence col
if (col == sequence_col_idx) {
_sequence_col_idx = sequence_col_idx;
break;
}
}
}
return res;
}
OLAPStatus Reader::_init_return_columns(const ReaderParams& read_params) {
if (read_params.reader_type == READER_QUERY) {
_return_columns = read_params.return_columns;
if (!_delete_handler.empty()) {
// We need to fetch columns which there are deletion conditions on them.
set<uint32_t> column_set(_return_columns.begin(), _return_columns.end());
for (const auto& conds : _delete_handler.get_delete_conditions()) {
for (const auto& cond_column : conds.del_cond->columns()) {
if (column_set.find(cond_column.first) == column_set.end()) {
column_set.insert(cond_column.first);
_return_columns.push_back(cond_column.first);
}
}
}
}
for (auto id : read_params.return_columns) {
if (_tablet->tablet_schema().column(id).is_key()) {
_key_cids.push_back(id);
} else {
_value_cids.push_back(id);
}
}
} else if (read_params.return_columns.empty()) {
for (size_t i = 0; i < _tablet->tablet_schema().num_columns(); ++i) {
_return_columns.push_back(i);
if (_tablet->tablet_schema().column(i).is_key()) {
_key_cids.push_back(i);
} else {
_value_cids.push_back(i);
}
}
VLOG_NOTICE << "return column is empty, using full column as default.";
} else if (read_params.reader_type == READER_CHECKSUM) {
_return_columns = read_params.return_columns;
for (auto id : read_params.return_columns) {
if (_tablet->tablet_schema().column(id).is_key()) {
_key_cids.push_back(id);
} else {
_value_cids.push_back(id);
}
}
} else {
OLAP_LOG_WARNING("fail to init return columns. [reader_type=%d return_columns_size=%u]",
read_params.reader_type, read_params.return_columns.size());
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
std::sort(_key_cids.begin(), _key_cids.end(), std::greater<uint32_t>());
return OLAP_SUCCESS;
}
void Reader::_init_seek_columns() {
std::unordered_set<uint32_t> column_set(_return_columns.begin(), _return_columns.end());
for (auto& it : _conditions.columns()) {
column_set.insert(it.first);
}
size_t max_key_column_count = 0;
for (const auto& key : _keys_param.start_keys) {
max_key_column_count = std::max(max_key_column_count, key->field_count());
}
for (const auto& key : _keys_param.end_keys) {
max_key_column_count = std::max(max_key_column_count, key->field_count());
}
for (size_t i = 0; i < _tablet->tablet_schema().num_columns(); i++) {
if (i < max_key_column_count || column_set.find(i) != column_set.end()) {
_seek_columns.push_back(i);
}
}
}
OLAPStatus Reader::_init_keys_param(const ReaderParams& read_params) {
if (read_params.start_key.empty()) {
return OLAP_SUCCESS;
}
_keys_param.start_key_include = read_params.start_key_include;
_keys_param.end_key_include = read_params.end_key_include;
size_t start_key_size = read_params.start_key.size();
_keys_param.start_keys.resize(start_key_size, nullptr);
size_t scan_key_size = read_params.start_key.front().size();
if (scan_key_size > _tablet->tablet_schema().num_columns()) {
LOG(WARNING)
<< "Input param are invalid. Column count is bigger than num_columns of schema. "
<< "column_count=" << scan_key_size
<< ", schema.num_columns=" << _tablet->tablet_schema().num_columns();
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
std::vector<uint32_t> columns(scan_key_size);
std::iota(columns.begin(), columns.end(), 0);
std::shared_ptr<Schema> schema =
std::make_shared<Schema>(_tablet->tablet_schema().columns(), columns);
for (size_t i = 0; i < start_key_size; ++i) {
if (read_params.start_key[i].size() != scan_key_size) {
OLAP_LOG_WARNING("The start_key.at(%ld).size == %ld, not equals the %ld", i,
read_params.start_key[i].size(), scan_key_size);
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
if ((_keys_param.start_keys[i] = new (nothrow) RowCursor()) == nullptr) {
OLAP_LOG_WARNING("fail to new RowCursor!");
return OLAP_ERR_MALLOC_ERROR;
}
OLAPStatus res = _keys_param.start_keys[i]->init_scan_key(
_tablet->tablet_schema(), read_params.start_key[i].values(), schema);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to init row cursor. [res=%d]", res);
return res;
}
res = _keys_param.start_keys[i]->from_tuple(read_params.start_key[i]);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to init row cursor from Keys. [res=%d key_index=%ld]", res, i);
return res;
}
}
size_t end_key_size = read_params.end_key.size();
_keys_param.end_keys.resize(end_key_size, nullptr);
for (size_t i = 0; i < end_key_size; ++i) {
if (read_params.end_key[i].size() != scan_key_size) {
OLAP_LOG_WARNING("The end_key.at(%ld).size == %ld, not equals the %ld", i,
read_params.end_key[i].size(), scan_key_size);
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
if ((_keys_param.end_keys[i] = new (nothrow) RowCursor()) == nullptr) {
OLAP_LOG_WARNING("fail to new RowCursor!");
return OLAP_ERR_MALLOC_ERROR;
}
OLAPStatus res = _keys_param.end_keys[i]->init_scan_key(
_tablet->tablet_schema(), read_params.end_key[i].values(), schema);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to init row cursor. [res=%d]", res);
return res;
}
res = _keys_param.end_keys[i]->from_tuple(read_params.end_key[i]);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to init row cursor from Keys. [res=%d key_index=%ld]", res, i);
return res;
}
}
//TODO:check the valid of start_key and end_key.(eg. start_key <= end_key)
return OLAP_SUCCESS;
}
void Reader::_init_conditions_param(const ReaderParams& read_params) {
_conditions.set_tablet_schema(&_tablet->tablet_schema());
_all_conditions.set_tablet_schema(&_tablet->tablet_schema());
for (const auto& condition : read_params.conditions) {
ColumnPredicate* predicate = _parse_to_predicate(condition);
if (predicate != nullptr) {
if (_tablet->tablet_schema()
.column(_tablet->field_index(condition.column_name))
.aggregation() != FieldAggregationMethod::OLAP_FIELD_AGGREGATION_NONE) {
_value_col_predicates.push_back(predicate);
} else {
_col_predicates.push_back(predicate);
OLAPStatus status = _conditions.append_condition(condition);
DCHECK_EQ(OLAP_SUCCESS, status);
}
OLAPStatus status = _all_conditions.append_condition(condition);
DCHECK_EQ(OLAP_SUCCESS, status);
}
}
// Only key column bloom filter will push down to storage engine
for (const auto& filter : read_params.bloom_filters) {
_col_predicates.emplace_back(_parse_to_predicate(filter));
}
}
#define COMPARISON_PREDICATE_CONDITION_VALUE(NAME, PREDICATE) \
ColumnPredicate* Reader::_new_##NAME##_pred(const TabletColumn& column, int index, \
const std::string& cond, bool opposite) const { \
ColumnPredicate* predicate = nullptr; \
switch (column.type()) { \
case OLAP_FIELD_TYPE_TINYINT: { \
int8_t value = 0; \
std::from_chars(cond.data(), cond.data() + cond.size(), value); \
predicate = new PREDICATE<int8_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_SMALLINT: { \
int16_t value = 0; \
std::from_chars(cond.data(), cond.data() + cond.size(), value); \
predicate = new PREDICATE<int16_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_INT: { \
int32_t value = 0; \
std::from_chars(cond.data(), cond.data() + cond.size(), value); \
predicate = new PREDICATE<int32_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_BIGINT: { \
int64_t value = 0; \
std::from_chars(cond.data(), cond.data() + cond.size(), value); \
predicate = new PREDICATE<int64_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_LARGEINT: { \
int128_t value = 0; \
StringParser::ParseResult result; \
value = StringParser::string_to_int<__int128>(cond.data(), cond.size(), &result); \
predicate = new PREDICATE<int128_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_DECIMAL: { \
decimal12_t value = {0, 0}; \
value.from_string(cond); \
predicate = new PREDICATE<decimal12_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_CHAR: { \
StringValue value; \
size_t length = std::max(static_cast<size_t>(column.length()), cond.length()); \
char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length)); \
memset(buffer, 0, length); \
memory_copy(buffer, cond.c_str(), cond.length()); \
value.len = length; \
value.ptr = buffer; \
predicate = new PREDICATE<StringValue>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_VARCHAR: \
case OLAP_FIELD_TYPE_STRING: { \
StringValue value; \
int32_t length = cond.length(); \
char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length)); \
memory_copy(buffer, cond.c_str(), length); \
value.len = length; \
value.ptr = buffer; \
predicate = new PREDICATE<StringValue>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_DATE: { \
uint24_t value = timestamp_from_date(cond); \
predicate = new PREDICATE<uint24_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_DATETIME: { \
uint64_t value = timestamp_from_datetime(cond); \
predicate = new PREDICATE<uint64_t>(index, value, opposite); \
break; \
} \
case OLAP_FIELD_TYPE_BOOL: { \
int32_t ivalue = 0; \
auto result = std::from_chars(cond.data(), cond.data() + cond.size(), ivalue); \
bool value = false; \
if (result.ec == std::errc()) { \
if (ivalue == 0) { \
value = false; \
} else { \
value = true; \
} \
} else { \
StringParser::ParseResult parse_result; \
value = StringParser::string_to_bool(cond.data(), cond.size(), &parse_result); \
} \
predicate = new PREDICATE<bool>(index, value, opposite); \
break; \
} \
default: \
break; \
} \
\
return predicate; \
}
COMPARISON_PREDICATE_CONDITION_VALUE(eq, EqualPredicate)
COMPARISON_PREDICATE_CONDITION_VALUE(ne, NotEqualPredicate)
COMPARISON_PREDICATE_CONDITION_VALUE(lt, LessPredicate)
COMPARISON_PREDICATE_CONDITION_VALUE(le, LessEqualPredicate)
COMPARISON_PREDICATE_CONDITION_VALUE(gt, GreaterPredicate)
COMPARISON_PREDICATE_CONDITION_VALUE(ge, GreaterEqualPredicate)
ColumnPredicate* Reader::_parse_to_predicate(
const std::pair<std::string, std::shared_ptr<IBloomFilterFuncBase>>& bloom_filter) {
int32_t index = _tablet->field_index(bloom_filter.first);
if (index < 0) {
return nullptr;
}
const TabletColumn& column = _tablet->tablet_schema().column(index);
return BloomFilterColumnPredicateFactory::create_column_predicate(index, bloom_filter.second,
column.type());
}
ColumnPredicate* Reader::_parse_to_predicate(const TCondition& condition, bool opposite) const {
// TODO: not equal and not in predicate is not pushed down
int32_t index = _tablet->field_index(condition.column_name);
if (index < 0) {
return nullptr;
}
const TabletColumn& column = _tablet->tablet_schema().column(index);
ColumnPredicate* predicate = nullptr;
if ((condition.condition_op == "*=" || condition.condition_op == "!*=" ||
condition.condition_op == "=" || condition.condition_op == "!=") &&
condition.condition_values.size() == 1) {
predicate = condition.condition_op == "*=" || condition.condition_op == "="
? _new_eq_pred(column, index, condition.condition_values[0], opposite)
: _new_ne_pred(column, index, condition.condition_values[0], opposite);
} else if (condition.condition_op == "<<") {
predicate = _new_lt_pred(column, index, condition.condition_values[0], opposite);
} else if (condition.condition_op == "<=") {
predicate = _new_le_pred(column, index, condition.condition_values[0], opposite);
} else if (condition.condition_op == ">>") {
predicate = _new_gt_pred(column, index, condition.condition_values[0], opposite);
} else if (condition.condition_op == ">=") {
predicate = _new_ge_pred(column, index, condition.condition_values[0], opposite);
} else if ((condition.condition_op == "*=" || condition.condition_op == "!*=") &&
condition.condition_values.size() > 1) {
switch (column.type()) {
case OLAP_FIELD_TYPE_TINYINT: {
phmap::flat_hash_set<int8_t> values;
int8_t value = 0;
for (auto& cond_val : condition.condition_values) {
std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<int8_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<int8_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_SMALLINT: {
phmap::flat_hash_set<int16_t> values;
int16_t value = 0;
for (auto& cond_val : condition.condition_values) {
std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<int16_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<int16_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_INT: {
phmap::flat_hash_set<int32_t> values;
int32_t value = 0;
for (auto& cond_val : condition.condition_values) {
std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<int32_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<int32_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_BIGINT: {
phmap::flat_hash_set<int64_t> values;
int64_t value = 0;
for (auto& cond_val : condition.condition_values) {
std::from_chars(cond_val.data(), cond_val.data() + cond_val.size(), value);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<int64_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<int64_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_LARGEINT: {
phmap::flat_hash_set<int128_t> values;
int128_t value = 0;
StringParser::ParseResult result;
for (auto& cond_val : condition.condition_values) {
value = StringParser::string_to_int<__int128>(cond_val.c_str(), cond_val.size(),
&result);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<int128_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<int128_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_DECIMAL: {
phmap::flat_hash_set<decimal12_t> values;
for (auto& cond_val : condition.condition_values) {
decimal12_t value = {0, 0};
value.from_string(cond_val);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<decimal12_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<decimal12_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_CHAR: {
phmap::flat_hash_set<StringValue> values;
for (auto& cond_val : condition.condition_values) {
StringValue value;
size_t length = std::max(static_cast<size_t>(column.length()), cond_val.length());
char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length));
memset(buffer, 0, length);
memory_copy(buffer, cond_val.c_str(), cond_val.length());
value.len = length;
value.ptr = buffer;
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<StringValue>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<StringValue>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_VARCHAR:
case OLAP_FIELD_TYPE_STRING:{
phmap::flat_hash_set<StringValue> values;
for (auto& cond_val : condition.condition_values) {
StringValue value;
int32_t length = cond_val.length();
char* buffer = reinterpret_cast<char*>(_predicate_mem_pool->allocate(length));
memory_copy(buffer, cond_val.c_str(), length);
value.len = length;
value.ptr = buffer;
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<StringValue>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<StringValue>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_DATE: {
phmap::flat_hash_set<uint24_t> values;
for (auto& cond_val : condition.condition_values) {
uint24_t value = timestamp_from_date(cond_val);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<uint24_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<uint24_t>(index, std::move(values), opposite);
}
break;
}
case OLAP_FIELD_TYPE_DATETIME: {
phmap::flat_hash_set<uint64_t> values;
for (auto& cond_val : condition.condition_values) {
uint64_t value = timestamp_from_datetime(cond_val);
values.insert(value);
}
if (condition.condition_op == "*=") {
predicate = new InListPredicate<uint64_t>(index, std::move(values), opposite);
} else {
predicate = new NotInListPredicate<uint64_t>(index, std::move(values), opposite);
}
break;
}
// OLAP_FIELD_TYPE_BOOL is not valid in this case.
default:
break;
}
} else if (boost::to_lower_copy(condition.condition_op) == "is") {
predicate = new NullPredicate(
index, boost::to_lower_copy(condition.condition_values[0]) == "null", opposite);
}
return predicate;
}
void Reader::_init_load_bf_columns(const ReaderParams& read_params) {
_init_load_bf_columns(read_params, &_conditions, &_load_bf_columns);
_init_load_bf_columns(read_params, &_all_conditions, &_load_bf_all_columns);
}
void Reader::_init_load_bf_columns(const ReaderParams& read_params, Conditions* conditions,
std::set<uint32_t>* load_bf_columns) {
// add all columns with condition to load_bf_columns
for (const auto& cond_column : conditions->columns()) {
if (!_tablet->tablet_schema().column(cond_column.first).is_bf_column()) {
continue;
}
for (const auto& cond : cond_column.second->conds()) {
if (cond->op == OP_EQ ||
(cond->op == OP_IN && cond->operand_set.size() < MAX_OP_IN_FIELD_NUM)) {
load_bf_columns->insert(cond_column.first);
}
}
}
// remove columns which have same value between start_key and end_key
int min_scan_key_len = _tablet->tablet_schema().num_columns();
for (const auto& start_key : read_params.start_key) {
min_scan_key_len = std::min(min_scan_key_len, static_cast<int>(start_key.size()));
}
for (const auto& end_key : read_params.end_key) {
min_scan_key_len = std::min(min_scan_key_len, static_cast<int>(end_key.size()));
}
int max_equal_index = -1;
for (int i = 0; i < read_params.start_key.size(); ++i) {
int j = 0;
for (; j < min_scan_key_len; ++j) {
if (read_params.start_key[i].get_value(j) != read_params.end_key[i].get_value(j)) {
break;
}
}
if (max_equal_index < j - 1) {
max_equal_index = j - 1;
}
}
for (int i = 0; i < max_equal_index; ++i) {
load_bf_columns->erase(i);
}
// remove the max_equal_index column when it's not varchar
// or longer than number of short key fields
if (max_equal_index == -1) {
return;
}
FieldType type = _tablet->tablet_schema().column(max_equal_index).type();
if ((type != OLAP_FIELD_TYPE_VARCHAR && type != OLAP_FIELD_TYPE_STRING)|| max_equal_index + 1 > _tablet->num_short_key_columns()) {
load_bf_columns->erase(max_equal_index);
}
}
OLAPStatus Reader::_init_delete_condition(const ReaderParams& read_params) {
if (read_params.reader_type == READER_CUMULATIVE_COMPACTION) {
return OLAP_SUCCESS;
}
_tablet->obtain_header_rdlock();
OLAPStatus ret = _delete_handler.init(_tablet->tablet_schema(), _tablet->delete_predicates(),
read_params.version.second, this);
_tablet->release_header_lock();
if (read_params.reader_type == READER_BASE_COMPACTION) {
_filter_delete = true;
}
return ret;
}
} // namespace doris
| 40,053 | 11,438 |
/*
; Project: Open Vehicle Monitor System
; Module: CAN logging framework
; Date: 18th January 2018
;
; (C) 2018 Michael Balzer
;
; 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 "ovms_log.h"
static const char *TAG = "canlog";
#include "can.h"
#include "canlog.h"
#include <sys/param.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <sstream>
#include <iomanip>
#include "ovms_utils.h"
#include "ovms_config.h"
#include "ovms_command.h"
#include "ovms_events.h"
#include "ovms_peripherals.h"
#include "metrics_standard.h"
////////////////////////////////////////////////////////////////////////
// Command Processing
////////////////////////////////////////////////////////////////////////
void can_log_stop(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv)
{
if (!MyCan.HasLogger())
{
writer->puts("Error: No loggers running");
return;
}
if (argc==0)
{
// Stop all loggers
writer->puts("Stopping all loggers");
MyCan.RemoveLoggers();
return;
}
if (MyCan.RemoveLogger(atoi(argv[0])))
{
writer->puts("Stopped logger");
}
else
{
writer->puts("Error: Cannot find specified logger");
}
}
void can_log_status(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv)
{
if (!MyCan.HasLogger())
{
writer->puts("CAN logging inactive");
return;
}
if (argc>0)
{
canlog* cl = MyCan.GetLogger(atoi(argv[0]));
if (cl)
{
writer->printf("CAN logging active: %s\n Statistics: %s\n", cl->GetInfo().c_str(), cl->GetStats().c_str());
}
else
{
writer->puts("Error: Cannot find specified can logger");
}
return;
}
else
{
// Show the status of all loggers
OvmsMutexLock lock(&MyCan.m_loggermap_mutex);
for (can::canlog_map_t::iterator it=MyCan.m_loggermap.begin(); it!=MyCan.m_loggermap.end(); ++it)
{
canlog* cl = it->second;
writer->printf("CAN logger #%d: %s\n Statistics: %s\n",
it->first, cl->GetInfo().c_str(), cl->GetStats().c_str());
}
}
}
void can_log_list(int verbosity, OvmsWriter* writer, OvmsCommand* cmd, int argc, const char* const* argv)
{
if (!MyCan.HasLogger())
{
writer->puts("CAN logging inactive");
return;
}
else
{
// Show the list of all loggers
OvmsMutexLock lock(&MyCan.m_loggermap_mutex);
for (can::canlog_map_t::iterator it=MyCan.m_loggermap.begin(); it!=MyCan.m_loggermap.end(); ++it)
{
canlog* cl = it->second;
writer->printf("#%d: %s\n", it->first, cl->GetInfo().c_str());
}
}
}
////////////////////////////////////////////////////////////////////////
// CAN Logging System initialisation
////////////////////////////////////////////////////////////////////////
class OvmsCanLogInit
{
public: OvmsCanLogInit();
} MyOvmsCanLogInit __attribute__ ((init_priority (4550)));
OvmsCanLogInit::OvmsCanLogInit()
{
ESP_LOGI(TAG, "Initialising CAN logging (4550)");
OvmsCommand* cmd_can = MyCommandApp.FindCommand("can");
if (cmd_can == NULL)
{
ESP_LOGE(TAG,"Cannot find CAN command - aborting log command registration");
return;
}
OvmsCommand* cmd_canlog = cmd_can->RegisterCommand("log", "CAN logging framework");
cmd_canlog->RegisterCommand("stop", "Stop logging", can_log_stop,"[<id>]",0,1);
cmd_canlog->RegisterCommand("status", "Logging status", can_log_status,"[<id>]",0,1);
cmd_canlog->RegisterCommand("list", "Logging list", can_log_list);
cmd_canlog->RegisterCommand("start", "CAN logging start framework");
}
////////////////////////////////////////////////////////////////////////
// CAN Logger class
////////////////////////////////////////////////////////////////////////
canlog::canlog(const char* type, std::string format, canformat::canformat_serve_mode_t mode)
{
m_type = type;
m_format = format;
m_formatter = MyCanFormatFactory.NewFormat(format.c_str());
m_formatter->SetServeMode(mode);
m_filter = NULL;
m_msgcount = 0;
m_dropcount = 0;
m_filtercount = 0;
using std::placeholders::_1;
using std::placeholders::_2;
MyEvents.RegisterEvent(IDTAG, "*", std::bind(&canlog::EventListener, this, _1, _2));
int queuesize = MyConfig.GetParamValueInt("can", "log.queuesize",100);
m_queue = xQueueCreate(queuesize, sizeof(CAN_log_message_t));
xTaskCreatePinnedToCore(RxTask, "OVMS CanLog", 4096, (void*)this, 10, &m_task, CORE(1));
}
canlog::~canlog()
{
MyEvents.DeregisterEvent(IDTAG);
if (m_task)
{
vTaskDelete(m_task);
m_task = NULL;
}
if (m_queue)
{
CAN_log_message_t msg;
while (xQueueReceive(m_queue, &msg, 0) == pdTRUE)
{
switch (msg.type)
{
case CAN_LogInfo_Comment:
case CAN_LogInfo_Config:
case CAN_LogInfo_Event:
free(msg.text);
break;
default:
break;
}
}
vQueueDelete(m_queue);
}
if (m_formatter)
{
delete m_formatter;
m_formatter = NULL;
}
if (m_filter)
{
delete m_filter;
m_filter = NULL;
}
}
void canlog::RxTask(void *context)
{
canlog* me = (canlog*) context;
CAN_log_message_t msg;
while (1)
{
if (xQueueReceive(me->m_queue, &msg, (portTickType)portMAX_DELAY) == pdTRUE)
{
switch (msg.type)
{
case CAN_LogInfo_Comment:
case CAN_LogInfo_Config:
case CAN_LogInfo_Event:
me->OutputMsg(msg);
free(msg.text);
break;
default:
me->OutputMsg(msg);
break;
}
}
}
}
void canlog::EventListener(std::string event, void* data)
{
if (startsWith(event, "vehicle"))
LogInfo(NULL, CAN_LogInfo_Event, event.c_str());
}
const char* canlog::GetType()
{
return m_type;
}
const char* canlog::GetFormat()
{
return m_format.c_str();
}
void canlog::OutputMsg(CAN_log_message_t& msg)
{
}
std::string canlog::GetInfo()
{
std::ostringstream buf;
buf << "Type:" << m_type << " Format:" << m_format;
if (m_formatter)
{
buf << "(" << m_formatter->GetServeModeName() << ")";
}
if (m_filter)
{
buf << " Filter:" << m_filter->Info();
}
else
{
buf << " Filter:off";
}
buf << " Vehicle:" << StdMetrics.ms_v_type->AsString();
return buf.str();
}
std::string canlog::GetStats()
{
std::ostringstream buf;
float droprate = (m_msgcount > 0) ? ((float) m_dropcount/m_msgcount*100) : 0;
uint32_t waiting = uxQueueMessagesWaiting(m_queue);
buf << "total messages: " << m_msgcount
<< ", dropped: " << m_dropcount
<< ", filtered: " << m_filtercount
<< " = " << std::fixed << std::setprecision(1) << droprate << "%";
if (waiting > 0)
buf << ", waiting: " << waiting;
return buf.str();
}
void canlog::SetFilter(canfilter* filter)
{
if (m_filter)
{
delete m_filter;
}
m_filter = filter;
}
void canlog::ClearFilter()
{
if (m_filter)
{
delete m_filter;
m_filter = NULL;
}
}
void canlog::LogFrame(canbus* bus, CAN_log_type_t type, const CAN_frame_t* frame)
{
if (!IsOpen() || !bus || !frame) return;
if ((m_filter == NULL)||(m_filter->IsFiltered(frame)))
{
CAN_log_message_t msg;
msg.type = type;
gettimeofday(&msg.timestamp,NULL);
memcpy(&msg.frame,frame,sizeof(CAN_frame_t));
msg.frame.origin = bus;
m_msgcount++;
if (xQueueSend(m_queue, &msg, 0) != pdTRUE) m_dropcount++;
}
else
{
m_filtercount++;
}
}
void canlog::LogStatus(canbus* bus, CAN_log_type_t type, const CAN_status_t* status)
{
if (!IsOpen() || !bus) return;
if ((m_filter == NULL)||(m_filter->IsFiltered(bus)))
{
CAN_log_message_t msg;
msg.type = type;
gettimeofday(&msg.timestamp,NULL);
msg.origin = bus;
memcpy(&msg.status,status,sizeof(CAN_status_t));
m_msgcount++;
if (xQueueSend(m_queue, &msg, 0) != pdTRUE) m_dropcount++;
}
else
{
m_filtercount++;
}
}
void canlog::LogInfo(canbus* bus, CAN_log_type_t type, const char* text)
{
if (!IsOpen() || !text) return;
if ((m_filter == NULL)||(m_filter->IsFiltered(bus)))
{
CAN_log_message_t msg;
msg.type = type;
gettimeofday(&msg.timestamp,NULL);
msg.origin = bus;
msg.text = strdup(text);
m_msgcount++;
if (xQueueSend(m_queue, &msg, 0) != pdTRUE) m_dropcount++;
}
else
{
m_filtercount++;
}
}
| 9,571 | 3,516 |
/**
* @author Alessandro Bianco
*/
/**
* @addtogroup DFNs
* @{
*/
#ifndef STEREORECONSTRUCTION_SCANLINEOPTIMIZATION_HPP
#define STEREORECONSTRUCTION_SCANLINEOPTIMIZATION_HPP
#include "StereoReconstructionInterface.hpp"
#include <Types/CPP/PointCloud.hpp>
#include <Types/CPP/Frame.hpp>
#include <Helpers/ParametersListHelper.hpp>
#include <opencv2/core/core.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
namespace CDFF
{
namespace DFN
{
namespace StereoReconstruction
{
/**
* Scene reconstruction (as a 3D pointcloud) from 2D stereo images, using
* the Adaptive-Cost 2-Pass Scanline Optimization disparity mapping
* algorithm (by Tombari).
*
* Processing steps: (i) conversion of the images to PCL representation,
* (ii) computation of a disparity map using Tombari's algorithm, (iii)
* scene reconstruction based on the disparity map using a reprojection
* algorithm, (iv) downsampling of the generated pointcloud.
*
* @param costAggregationRadius
* @param spatialBandwidth
* @param colorBandwidth
* @param weakSmoothnessPenalty
* @param strongSmoothnessPenalty
*
* @param matchingOptionsSet.numberOfDisparities
* number of detected disparity intervals
* @param matchingOptionsSet.horizontalOffset
* @param matchingOptionsSet.ratioFilter
* @param matchingOptionsSet.peakFilter
* @param matchingOptionsSet.usePreprocessing
* @param matchingOptionsSet.useLeftRightConsistencyCheck
* @param matchingOptionsSet.leftRightConsistencyThreshold
*
* @param pointCloudSamplingDensity
* downsampling ratio: a number between 0 and 1 that describes how
* much downsampling of the generated pointcloud is desired. The
* pointcloud is subsampled at positions that are multiples of n,
* where n = 1/pointCloudSamplingDensity.
*
* @param stereoCameraParameters
* camera parameters in the form of the focal length and principal
* point of the left camera and the distance between the two cameras:
* the parameters to use to provide this information are called
* LeftFocalLength, LeftPrinciplePointX, LeftPrinciplePointY, and
* Baseline, respectively
*
* @param reconstructionSpace
* a bounding box for the reconstructed scene, provided via
* parameters called LimitX, LimitY, LimitZ. A reconstructed point
* of coordinates (x,y,z) is accepted into the pointcloud if
* -LimitX <= x <= LimitX, -LimitY <= y <= LimitY, 0 < z <= LimitZ.
*
* @reference The algorithm is adapted from Liang Wang, Miao Liao, Minglun
* Gong, Ruigang Yang, and David Nister (2006), "High Quality
* Real-Time Stereo using Adaptive Cost Aggregation and Dynamic
* Programming", Third IEEE International Symposium on 3D Data
* Processing, Visualization, and Transmission, 798-805.
*/
class ScanlineOptimization : public StereoReconstructionInterface
{
public:
ScanlineOptimization();
virtual ~ScanlineOptimization();
virtual void configure() override;
virtual void process() override;
private:
static const float EPSILON;
//DFN Parameters
typedef pcl::PointCloud<pcl::RGB> PclImage;
typedef pcl::PointCloud<pcl::RGB>::Ptr PclImagePtr;
typedef pcl::PointCloud<pcl::RGB>::ConstPtr PclImageConstPtr;
typedef pcl::PointCloud<pcl::PointXYZ> PclPointCloud;
typedef pcl::PointCloud<pcl::PointXYZ>::Ptr PclPointCloudPtr;
typedef pcl::PointCloud<pcl::PointXYZ>::ConstPtr PclPointCloudConstPtr;
struct ReconstructionSpace
{
float limitX;
float limitY;
float limitZ;
};
struct CameraParameters
{
float leftPrinciplePointX;
float leftPrinciplePointY;
float leftFocalLength;
float baseline;
};
struct MatchingOptionsSet
{
int numberOfDisparities;
int horizontalOffset;
int ratioFilter;
int peakFilter;
bool usePreprocessing;
bool useLeftRightConsistencyCheck;
int leftRightConsistencyThreshold;
};
struct ScanlineOptimizationOptionsSet
{
int costAggregationRadius;
int spatialBandwidth;
int colorBandwidth;
int strongSmoothnessPenalty;
int weakSmoothnessPenalty;
float pointCloudSamplingDensity;
float voxelGridLeafSize;
MatchingOptionsSet matchingOptionsSet;
CameraParameters cameraParameters;
ReconstructionSpace reconstructionSpace;
};
Helpers::ParametersListHelper parametersHelper;
ScanlineOptimizationOptionsSet parameters;
static const ScanlineOptimizationOptionsSet DEFAULT_PARAMETERS;
//Type conversion methods
PclImagePtr Convert(FrameWrapper::FrameConstPtr frame);
PointCloudWrapper::PointCloudConstPtr SampleCloud(PclPointCloudConstPtr pointCloud);
PointCloudWrapper::PointCloudConstPtr SampleCloudWithPeriodicSampling(PclPointCloudConstPtr pointCloud);
PointCloudWrapper::PointCloudConstPtr SampleCloudWithVoxelGrid(PclPointCloudConstPtr pointCloud);
cv::Mat PclImageToCvMatrix(PclImagePtr pclImage);
//Core computation methods
PclPointCloudPtr ComputePointCloud(PclImagePtr leftImage, PclImagePtr rightImage);
//Input Validation methods
void ValidateParameters();
//Testing methods for visualizing intermediate disparity map output.
#ifdef TESTING
#define SAVE_DISPARITY_MATRIX(visualMap) disparityMatrix = PclImageToCvMatrix(visualMap);
#else
#define SAVE_DISPARITY_MATRIX(visualMap)
#endif
};
}
}
}
#endif // STEREORECONSTRUCTION_SCANLINEOPTIMIZATION_HPP
/** @} */
| 5,542 | 1,901 |
//--------------------------------------------------------------------------------//
/*!
@file AvCommon.cpp
@brief libAvライブラリ共通クラス
@author 大橋
*/
//--------------------------------------------------------------------------------//
#include "../AvCommon.h"
#define __STDC_CONSTANT_MACROS
#ifdef _STDINT_H
#undef _STDINT_H
#endif
extern "C"{
#include <libavcodec/avcodec.h>
}
//--------------------------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//--------------------------------------------------------------------------------//
ClAvImage::ClAvImage()
{
m_dDuration = 0;
}
//--------------------------------------------------------------------------------//
//--------------------------------------------------------------------------------//
/*!
@brief コンストラクタ
@param[in] pFrame : フレームデータ
@param[in] dDuration : 画像表示時間(msec)
*/
//--------------------------------------------------------------------------------//
ClAvImage::ClAvImage(AVFrame *pFrame, qreal dDuration)
{
m_img = QImage(pFrame->data[0], pFrame->width, pFrame->height, QImage::Format_RGB888).copy();
m_dDuration = dDuration;
}
//--------------------------------------------------------------------------------//
| 1,229 | 354 |
/** A one line description of the class.
*
* #include "ButtonTest.hpp"
* Created 3-12-18 By: Smitty
*
* A longer description.
*/
#ifndef BUTTONTEST_HPP
#define BUTTONTEST_HPP
#include "../BaseModelTest/BaseModelTest.hpp"
class ButtonTest : public BaseModelTest
{
public:
ButtonTest(void);
~ButtonTest(void);
void update(void);
String getName(void);
int getState(void);
void setState(void);
};
#endif //BUTTONTEST_HPP
| 460 | 176 |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdn/v20180606/model/QnPrivateAccess.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdn::V20180606::Model;
using namespace std;
QnPrivateAccess::QnPrivateAccess() :
m_switchHasBeenSet(false),
m_accessKeyHasBeenSet(false),
m_secretKeyHasBeenSet(false)
{
}
CoreInternalOutcome QnPrivateAccess::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Switch") && !value["Switch"].IsNull())
{
if (!value["Switch"].IsString())
{
return CoreInternalOutcome(Core::Error("response `QnPrivateAccess.Switch` IsString=false incorrectly").SetRequestId(requestId));
}
m_switch = string(value["Switch"].GetString());
m_switchHasBeenSet = true;
}
if (value.HasMember("AccessKey") && !value["AccessKey"].IsNull())
{
if (!value["AccessKey"].IsString())
{
return CoreInternalOutcome(Core::Error("response `QnPrivateAccess.AccessKey` IsString=false incorrectly").SetRequestId(requestId));
}
m_accessKey = string(value["AccessKey"].GetString());
m_accessKeyHasBeenSet = true;
}
if (value.HasMember("SecretKey") && !value["SecretKey"].IsNull())
{
if (!value["SecretKey"].IsString())
{
return CoreInternalOutcome(Core::Error("response `QnPrivateAccess.SecretKey` IsString=false incorrectly").SetRequestId(requestId));
}
m_secretKey = string(value["SecretKey"].GetString());
m_secretKeyHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void QnPrivateAccess::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_switchHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Switch";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_switch.c_str(), allocator).Move(), allocator);
}
if (m_accessKeyHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AccessKey";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_accessKey.c_str(), allocator).Move(), allocator);
}
if (m_secretKeyHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SecretKey";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_secretKey.c_str(), allocator).Move(), allocator);
}
}
string QnPrivateAccess::GetSwitch() const
{
return m_switch;
}
void QnPrivateAccess::SetSwitch(const string& _switch)
{
m_switch = _switch;
m_switchHasBeenSet = true;
}
bool QnPrivateAccess::SwitchHasBeenSet() const
{
return m_switchHasBeenSet;
}
string QnPrivateAccess::GetAccessKey() const
{
return m_accessKey;
}
void QnPrivateAccess::SetAccessKey(const string& _accessKey)
{
m_accessKey = _accessKey;
m_accessKeyHasBeenSet = true;
}
bool QnPrivateAccess::AccessKeyHasBeenSet() const
{
return m_accessKeyHasBeenSet;
}
string QnPrivateAccess::GetSecretKey() const
{
return m_secretKey;
}
void QnPrivateAccess::SetSecretKey(const string& _secretKey)
{
m_secretKey = _secretKey;
m_secretKeyHasBeenSet = true;
}
bool QnPrivateAccess::SecretKeyHasBeenSet() const
{
return m_secretKeyHasBeenSet;
}
| 4,076 | 1,320 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016 The Auroracoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include "scrypt.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
//
// Main network
//
unsigned int pnSeed[] =
{
0xcb47d082
};
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
pchMessageStart[0] = 0xfb;
pchMessageStart[1] = 0xc0;
pchMessageStart[2] = 0xb6;
pchMessageStart[3] = 0xdb;
vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072");
nDefaultPort = 11337;
nRPCPort = 14242;
bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000
bnProofOfWorkLimit[ALGO_SCRYPT] = CBigNum(~uint256(0) >> 20);
bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311
bnProofOfWorkLimit[ALGO_SKEIN] = CBigNum(~uint256(0) >> 20); // 0.00195311
bnProofOfWorkLimit[ALGO_QUBIT] = CBigNum(~uint256(0) >> 20); // 0.00097655
// Build the genesis block.
const char* pszTimestamp = "NY Times 18/Aug/2014 Bitcoin's Price Falls 12%, to Lowest Value Since May";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 10000 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1408974288;
genesis.nBits = 0x1e0ffff0;
//genesis.nBits = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact();
//genesis.nBits = 0x1e0fffff;
genesis.nNonce = 386703170;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x660f734cf6c6d16111bde201bbd2122873f2f2c078b969779b9d4c99732354fd"));
assert(genesis.hashMerkleRoot == uint256("0xe9441ec39c399c76ea734ea31827e1895a82c5a1f9b2c6252b5dacada768ec8b"));
vSeeds.push_back(CDNSSeedData("smileyco.in", "dnsseed.smileyco.in"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,25); // Smileycoin addresses start with S
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); // 25 + 128
base58Prefixes[SECRET_KEY_OLD] = std::vector<unsigned char>(1,151);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x1E)(0x56)(0x2D)(0x9A).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x1E)(0x56)(0x31)(0xBC).convert_to_container<std::vector<unsigned char> >();
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
// Testnet
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
pchMessageStart[0] = 0xfb;
pchMessageStart[1] = 0xc0;
pchMessageStart[2] = 0xb6;
pchMessageStart[3] = 0xdd; // the "d" seperates test net from main net
nDefaultPort = 12337;
nRPCPort = 14243;
strDataDir = "testnet";
bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000
bnProofOfWorkLimit[ALGO_SCRYPT] = CBigNum(~uint256(0) >> 20);
bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311
bnProofOfWorkLimit[ALGO_SKEIN] = CBigNum(~uint256(0) >> 20); // 0.00195311
bnProofOfWorkLimit[ALGO_QUBIT] = CBigNum(~uint256(0) >> 20); // 0.00097655
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1448114586;
genesis.nNonce = 1979089;
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x54810bfb46c7b0d7bbe184faa10d2352810b29d1cdfa5169ce3aed387d80b921"));
// If genesis block hash does not match, then generate new genesis hash.
if (hashGenesisBlock != uint256("0x54810bfb46c7b0d7bbe184faa10d2352810b29d1cdfa5169ce3aed387d80b921"))
{
printf("Searching for testnet genesis block...\n");
// This will figure out a valid hash and Nonce if you're creating a different genesis block:
//uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
uint256 thash;
uint256 bestfound;
//static char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(bestfound));
while(true)
{
scrypt_1024_1_1_256(BEGIN(genesis.nVersion), BEGIN(thash));
//thash = scrypt_blockhash(BEGIN(block.nVersion));
if (thash <= hashTarget)
break;
//if ((genesis.nNonce & 0xFFF) == 0)
if (thash <= bestfound)
{
bestfound = thash;
printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
}
++genesis.nNonce;
if (genesis.nNonce == 0)
{
printf("NONCE WRAPPED, incrementing time\n");
++genesis.nTime;
}
}
printf("block.nTime = %u \n", genesis.nTime);
printf("block.nNonce = %u \n", genesis.nNonce);
printf("block.GetHash = %s\n", genesis.GetHash().ToString().c_str());
}
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("localtests", "localhost"));
//vSeeds.push_back(CDNSSeedData("testnet-united-states-east", "testnet1.auroraseed.com"));
//vSeeds.push_back(CDNSSeedData("testnet-united-states-west", "testnet2.criptoe.com"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,58); // Smileycoin addresses start with S
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,12);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,112); // 25 + 128
base58Prefixes[SECRET_KEY_OLD] = std::vector<unsigned char>(1,148);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x1E)(0x56)(0x2D)(0x9A).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = list_of(0x1E)(0x56)(0x31)(0xBC).convert_to_container<std::vector<unsigned char> >();
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
// Regression test
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xfa;
pchMessageStart[1] = 0xbf;
pchMessageStart[2] = 0xb5;
pchMessageStart[3] = 0xda;
//nSubsidyHalvingInterval = 150;
// bnProofOfWorkLimit = CBigNum();
genesis.nTime = 1296688602;
genesis.nBits = 0x207fffff;
genesis.nNonce = 0;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 19444;
strDataDir = "regtest";
//assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
| 10,169 | 4,045 |
#pragma once
/**
* @file b_tree.hpp
* @brief B-木
*/
#include <memory>
#include "config.hpp"
#include "simulator/disk_variable.hpp"
/**
* @brief B-木
* @details Cache Awareなデータ構造
* @note
* 中間ノードは以下のデータを持つ (根のキー数はK-1未満でもOK + 葉のsonsは空)
* - keys:k個のキー (キー数kは K-1 <= k <= 2K-1)
* - sons:k+1個の子ノード
*
* さらに探索木としての性質として以下が成立している
* - keysは昇順
* - sons[i]に含まれるキーは、keys[i-1]以上&keys[i]未満
*/
class b_tree
{
struct node_t
{
node_t() = default;
std::vector<disk_var<data_t>> keys{};
std::vector<disk_var<std::shared_ptr<node_t>>> sons{};
disk_var<bool> leaf{false};
};
public:
/**
* @brief コンストラクタ
* @param K[in] キー数に関する定数
*/
b_tree(const std::size_t K_);
/**
* @brief コンストラクタ
* @param K[in] キー数に関する定数
* @param datas[in] 初期データ
*/
b_tree(const std::vector<data_t>& datas, const std::size_t K_);
/**
* @brief 挿入
* @param key[in] キー
*/
void insert(const data_t key);
/**
* @brief LowerBound
* @param key[in] キー
*/
data_t lower_bound(const data_t key) const;
using node_t = node_t;
using ptr_t = std::shared_ptr<node_t>;
std::size_t K;
private:
void illegal_insert(const data_t key);
ptr_t m_root;
};
| 1,263 | 631 |
#include <v4r/segmentation/plane_utils.h>
#include <v4r/segmentation/segmenter_organized_connected_component.h>
#include <pcl/common/angles.h>
#include <pcl/pcl_config.h>
#include <pcl/segmentation/euclidean_cluster_comparator.h>
#include <pcl/segmentation/organized_connected_component_segmentation.h>
#include <pcl/impl/instantiate.hpp>
namespace v4r {
template <typename PointT>
void OrganizedConnectedComponentSegmenter<PointT>::segment() {
clusters_.clear();
pcl::PointCloud<pcl::Label>::Ptr labels(new pcl::PointCloud<pcl::Label>);
labels->points.resize(scene_->points.size());
for (pcl::Label &p : labels->points)
p.label = 1;
#if PCL_VERSION_COMPARE(<=, 1, 8, 1)
auto euclidean_cluster_comp = boost::make_shared<pcl::EuclideanClusterComparator<PointT, pcl::Normal, pcl::Label>>();
euclidean_cluster_comp->setAngularThreshold(pcl::deg2rad(param_.angular_threshold_deg_));
std::vector<bool> exclude_labels(scene_->points.size(), false);
euclidean_cluster_comp->setExcludeLabels(exclude_labels);
#else
auto euclidean_cluster_comp = boost::make_shared<pcl::EuclideanClusterComparator<PointT, pcl::Label>>();
#endif
euclidean_cluster_comp->setInputCloud(scene_);
euclidean_cluster_comp->setLabels(labels);
euclidean_cluster_comp->setDistanceThreshold(param_.distance_threshold_, true);
pcl::PointCloud<pcl::Label> euclidean_labels;
std::vector<pcl::PointIndices> euclidean_label_indices;
pcl::OrganizedConnectedComponentSegmentation<PointT, pcl::Label> seg(euclidean_cluster_comp);
seg.setInputCloud(scene_);
seg.segment(euclidean_labels, euclidean_label_indices);
for (size_t i = 0; i < euclidean_label_indices.size(); i++) {
if (euclidean_label_indices[i].indices.size() >= param_.min_cluster_size_)
clusters_.push_back(euclidean_label_indices[i].indices);
}
}
#define PCL_INSTANTIATE_OrganizedConnectedComponentSegmenter(T) \
template class V4R_EXPORTS OrganizedConnectedComponentSegmenter<T>;
PCL_INSTANTIATE(OrganizedConnectedComponentSegmenter, PCL_XYZ_POINT_TYPES)
} // namespace v4r
| 2,057 | 734 |
#include "static/Hello.h"
int main(int argc, char* argv[])
{
Hello hi_obj;
hi_obj.print();
return 0;
}
| 116 | 50 |
#include "IEngine.hpp"
#include "Vector.hpp"
#include "IRenderWorld.hpp"
#include "GameEntity.hpp"
#include <iostream>
#include <chrono>
#include "SDL.h"
#include "SDL_opengl.h"
#include "glm/gtc/matrix_transform.hpp"
#include "Engine.hpp"
namespace chrono = std::chrono;
IEngine* IEngine::AllocateInstance()
{
return new Engine();
}
void Engine::Init( const char* title, int width, int height )
{
gEngine = this;
// Init SDL and create a window
SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
// Set the OpenGL context version
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 5 );
// Create the window and context
window = SDL_CreateWindow( title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL );
SDL_GLContext glContext = SDL_GL_CreateContext( window );
// Initialise the render system with render init params
renderSystem = foxglbox::GetRenderSystem();
RenderInitParams rip {
width, height, // Resolution
RenderInitParams::Renderer_OpenGL45,// OpenGL 4.5 render backend
RenderInitParams::Windowing_SDL2, // SDL2 windowing
glContext // OpenGL 4.5 context
};
renderWorld = renderSystem->InitRenderer( rip );
windowWidth = width;
windowHeight = height;
// Turning on VSync here so my GPU (and yours) doesn't crash'n'burn
SDL_GL_SetSwapInterval( 0 );
// Set relative mouse mode
SDL_SetRelativeMouseMode( SDL_TRUE );
// Populate the world with entities
CreateGameEntities();
}
bool Engine::RunFrame()
{
auto startPoint = chrono::system_clock::now();
{
SDL_Event event;
while ( SDL_PollEvent( &event ) )
{
if ( event.type == SDL_QUIT )
{
return false;
}
if ( event.type == SDL_KEYDOWN )
{
if ( event.key.keysym.sym == SDLK_ESCAPE )
{
return false;
}
}
}
// Update all updateable entities
for ( auto& ent : gameEntities )
{
if ( nullptr != ent )
{
if ( ent->entityFlags.canThink )
{
ent->Update( frameTime );
}
}
}
// Present the entities to the user (i.e. just update render entities)
for ( auto& ent : gameEntities )
{
if ( nullptr != ent )
{
if ( ent->entityFlags.visible )
{
ent->Present();
}
}
}
// Render the frame!
renderWorld->RenderFrame( mainView );
SDL_GL_SwapWindow( window );
}
auto endPoint = chrono::system_clock::now();
auto microSeconds = chrono::duration_cast<chrono::microseconds>(endPoint - startPoint);
frameTime = (microSeconds.count() / (1000.0f * 1000.0f)) * timeScale;
float frameRate = 1.0f / frameTime;
printf( "## Frame time: %3.2f ms\n## Frame rate: %4.1f fps\n\n", (frameTime * 1000.0f), frameRate );
return true;
}
void Engine::Shutdown()
{
for ( auto& ent : gameEntities )
{
if ( nullptr != ent )
{
delete ent;
ent = nullptr;
}
}
if ( nullptr != renderWorld )
{
renderWorld->Shutdown();
delete renderWorld;
renderWorld = nullptr;
}
}
void Engine::Print( const char* string )
{
std::cout << string;
}
RenderModelHandle Engine::GetModel( const char* modelPath )
{
if ( nullptr == modelPath )
{
return RenderHandleInvalid;
}
RenderModelParams modelParams{ modelPath };
return renderWorld->CreateModel( modelParams );
}
void Engine::SubmitRenderView( const RenderView& view, bool isMain )
{
if ( isMain )
{
mainView = view;
return;
}
}
void Engine::CreateGameEntities()
{
using namespace Entities;
for ( auto& ent : gameEntities )
{
ent = nullptr;
}
RenderModelHandle terrainHandle = GetModel( "terrain.obj" );
RenderModelHandle amanHandle = GetModel( "aman.obj" ); // The A-Man
RenderModelHandle testCoverHandle = GetModel( "test_cover.obj" );
RenderModelHandle testRockHandle = GetModel( "testrock.obj" );
// Ideally, you'd wanna load some sorta level/scene file, but I decided to keep the sample very simple
CreateEntity<Prop>( fglVector::Zero, fglVector( 90.0f, 0.0f, 0.0f ), terrainHandle );
CreateEntity<Prop>( fglVector( 2.0f, 1.0f, 6.0f ), fglVector( 90.0f, 0.0f, 0.0f ), testCoverHandle );
CreateEntity<Prop>( fglVector( 2.0f, 1.0f, 2.3f ), fglVector( 90.0f, 0.0f, 0.0f ), testRockHandle );
CreateEntity<PropRotating>( fglVector( 2.0f, 0.0f, 3.0f ), fglVector::Zero, amanHandle );
CreateEntity<PropInstanced>( fglVector( 4.0f, -2.0f, 5.0f ), fglVector::Zero, testRockHandle );
CreateEntity<Player>( fglVector( -8.0f, 0.0f, 0.0f ), fglVector::Zero, 0 );
for ( auto& ent : gameEntities )
{
if ( nullptr != ent )
{
ent->Spawn();
}
}
}
template<typename EntityClass>
EntityClass* Engine::CreateEntity( fglVector position, fglVector angles, RenderModelHandle modelHandle )
{
for ( auto& ent : gameEntities )
{
if ( nullptr == ent )
{
EntityClass* entity = Entities::GameEntity::Instance<EntityClass>( position, angles, modelHandle );
ent = entity;
return entity;
}
}
return nullptr;
}
/*
Copyright (c) 2021 Admer456
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.
*/
| 6,967 | 2,304 |
#pragma once
#include <OgreInput.h>
#include <OgreSceneNode.h>
namespace pogre
{
class CameraStrategy
{
public:
CameraStrategy(Ogre::SceneNode *camNode = nullptr) : _camNode(camNode) {}
virtual ~CameraStrategy() = default;
public:
virtual void keyPressed(const OgreBites::KeyboardEvent &event) {}
virtual void keyReleased(const OgreBites::KeyboardEvent &event) {}
public:
virtual void mouseMoved(const OgreBites::MouseMotionEvent &event) {}
virtual void mousePressed(const OgreBites::MouseButtonEvent &event) {}
virtual void mouseReleased(const OgreBites::MouseButtonEvent &event) {}
public:
virtual void frameRendered(const Ogre::FrameEvent &event) {}
public:
void setCamNode(Ogre::SceneNode *node) { _camNode = node; }
Ogre::SceneNode *getCamNode() const { return _camNode; }
private:
Ogre::SceneNode *_camNode;
};
} | 949 | 288 |
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains basic "crash-and-recover" test support where the inferior
// crashes and then the cause of the crash is fixed in the debugger and then
// the inferior is resumed. The pieces of the test are abstracted out info
// this file as the test is done in a couple of places.
//
// The test consists of two parts:
// 1) Debugger side:
// Send RQST_CRASH_AND_RECOVER.
// In the exception handler:
// - call TestSegvPc()
// - call TestMemoryOps()
// - call FixInferiorSegv()
// - resume the inferior
// 2) Inferior side:
// On receipt of RQST_CRASH_AND_RECOVER:
// - call TestPrepAndSegv()
// - send RESP_RECOVERED_FROM_CRASH
#include "crash-and-recover.h"
#include <assert.h>
#include <inttypes.h>
#include <lib/backtrace-request/backtrace-request.h>
#include <lib/zx/thread.h>
#include <link.h>
#include <stdlib.h>
#include <string.h>
#include <zircon/process.h>
#include <zircon/processargs.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/debug.h>
#include <zircon/syscalls/exception.h>
#include <zircon/syscalls/object.h>
#include <zircon/syscalls/port.h>
#include <zircon/threads.h>
#include <atomic>
#include <test-utils/test-utils.h>
#include <zxtest/zxtest.h>
#include "debugger.h"
#include "inferior-control.h"
#include "inferior.h"
#include "utils.h"
namespace {
constexpr size_t kTestMemorySize = 8;
constexpr uint8_t kTestDataAdjust = 0x10;
} // namespace
bool test_prep_and_segv() {
uint8_t test_data[kTestMemorySize];
for (unsigned i = 0; i < sizeof(test_data); ++i)
test_data[i] = static_cast<uint8_t>(i);
#ifdef __x86_64__
void* segv_pc;
// Note: Fuchsia is always PIC.
__asm__("leaq .Lsegv_here(%%rip),%0" : "=r"(segv_pc));
printf("About to segv, pc %p\n", segv_pc);
// Set r9 to point to test_data so we can easily access it
// from the parent process. Likewise set r10 to segv_pc
// so the parent process can verify it matches the fault PC.
__asm__(
"\
movq %[zero],%%r8\n\
movq %[test_data],%%r9\n\
movq %[pc],%%r10\n\
.Lsegv_here:\n\
movq (%%r8),%%rax\
"
:
: [zero] "g"(0), [test_data] "g"(test_data), [pc] "g"(segv_pc)
: "rax", "r8", "r9", "r10");
#endif
#ifdef __aarch64__
void* segv_pc;
// Note: Fuchsia is always PIC.
__asm__(
"adrp %0, .Lsegv_here\n"
"add %0, %0, :lo12:.Lsegv_here"
: "=r"(segv_pc));
printf("About to segv, pc %p\n", segv_pc);
// Set r9 to point to test_data so we can easily access it
// from the parent process. Likewise set r10 to segv_pc
// so the parent process can verify it matches the fault PC.
__asm__(
"\
mov x8,xzr\n\
mov x9,%[test_data]\n\
mov x10,%[pc]\n\
.Lsegv_here:\n\
ldr x0,[x8]\
"
:
: [test_data] "r"(test_data), [pc] "r"(segv_pc)
: "x0", "x8", "x9", "x10");
#endif
// On resumption test_data should have had kTestDataAdjust added to each element.
// Note: This is the inferior process, it's not running under the test harness.
for (unsigned i = 0; i < sizeof(test_data); ++i) {
if (test_data[i] != i + kTestDataAdjust) {
printf("TestPrepAndSegv: bad data on resumption, test_data[%u] = 0x%x\n", i, test_data[i]);
return false;
}
}
printf("Inferior successfully resumed!\n");
return true;
}
void test_segv_pc(zx_handle_t thread) {
zx_thread_state_general_regs_t regs;
read_inferior_gregs(thread, ®s);
#if defined(__x86_64__)
ASSERT_EQ(regs.rip, regs.r10, "fault PC does not match r10");
#elif defined(__aarch64__)
ASSERT_EQ(regs.pc, regs.r[10], "fault PC does not match x10");
#endif
}
void test_memory_ops(zx_handle_t inferior, zx_handle_t thread) {
uint64_t test_data_addr = 0;
uint8_t test_data[kTestMemorySize];
zx_thread_state_general_regs_t regs;
read_inferior_gregs(thread, ®s);
#if defined(__x86_64__)
test_data_addr = regs.r9;
#elif defined(__aarch64__)
test_data_addr = regs.r[9];
#endif
size_t size = read_inferior_memory(inferior, test_data_addr, test_data, sizeof(test_data));
EXPECT_EQ(size, sizeof(test_data), "read_inferior_memory: short read");
for (unsigned i = 0; i < sizeof(test_data); ++i) {
EXPECT_EQ(test_data[i], i, "test_memory_ops");
}
for (unsigned i = 0; i < sizeof(test_data); ++i) {
test_data[i] = static_cast<uint8_t>(test_data[i] + kTestDataAdjust);
}
size = write_inferior_memory(inferior, test_data_addr, test_data, sizeof(test_data));
EXPECT_EQ(size, sizeof(test_data), "write_inferior_memory: short write");
// Note: Verification of the write is done in the inferior.
}
void fix_inferior_segv(zx_handle_t thread) {
printf("Fixing inferior segv\n");
// The segv was because r8 == 0, change it to a usable value. See TestPrepAndSegv.
zx_thread_state_general_regs_t regs;
read_inferior_gregs(thread, ®s);
#if defined(__x86_64__)
regs.r8 = regs.rsp;
#elif defined(__aarch64__)
regs.r[8] = regs.sp;
#endif
write_inferior_gregs(thread, ®s);
}
| 5,170 | 2,110 |
// base_proxy_impl_ch.cpp,v 1.2 2001/05/15 15:48:35 parsons Exp
#include "idl.h"
#include "idl_extern.h"
#include "be.h"
#include "be_visitor_operation.h"
ACE_RCSID(be_visitor_operation, x_proxy_impl_xh, "base_proxy_impl_ch.cpp,v 1.2 2001/05/15 15:48:35 parsons Exp")
be_visitor_operation_base_proxy_impl_ch::be_visitor_operation_base_proxy_impl_ch (be_visitor_context *ctx)
: be_visitor_scope (ctx)
{
}
be_visitor_operation_base_proxy_impl_ch::~be_visitor_operation_base_proxy_impl_ch (void)
{
}
int be_visitor_operation_base_proxy_impl_ch::visit_operation (be_operation *node)
{
TAO_OutStream *os; // output stream
be_type *bt; // type node representing the return type
os = this->ctx_->stream ();
this->ctx_->node (node); // save the node
// os->indent (); // start with the current indentation level
// every operation is declared virtual in the client code
*os << "virtual ";
// STEP I: generate the return type
bt = be_type::narrow_from_decl (node->return_type ());
if (!bt)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_sh::"
"visit_operation - "
"Bad return type\n"),
-1);
}
// grab the right visitor to generate the return type
be_visitor_context ctx (*this->ctx_);
ctx.state (TAO_CodeGen::TAO_OPERATION_RETTYPE_OTHERS);
be_visitor *visitor = tao_cg->make_visitor (&ctx);
if (!visitor)
{
ACE_ERROR_RETURN ((LM_ERROR,
"be_visitor_operation_sh::"
"visit_operation - "
"Bad visitor to return type\n"),
-1);
}
if (bt->accept (visitor) == -1)
{
delete visitor;
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_sh::"
"visit_operation - "
"codegen for return type failed\n"),
-1);
}
delete visitor;
// STEP 2: generate the operation name
*os << " " << node->local_name ();
// STEP 3: generate the argument list with the appropriate mapping. For these
// we grab a visitor that generates the parameter listing
ctx = *this->ctx_;
ctx.state (TAO_CodeGen::TAO_OPERATION_ARGLIST_BASE_PROXY_IMPL_CH);
visitor = tao_cg->make_visitor (&ctx);
if (!visitor)
{
ACE_ERROR_RETURN ((LM_ERROR,
"be_visitor_operation_sh::"
"visit_operation - "
"Bad visitor to return type\n"),
-1);
}
if (node->accept (visitor) == -1)
{
delete visitor;
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_sh::"
"visit_operation - "
"codegen for argument list failed\n"),
-1);
}
delete visitor;
return 0;
}
| 3,093 | 1,078 |
#include <aslam/backend/EuclideanExpressionNode.hpp>
#include <aslam/backend/HomogeneousExpressionNode.hpp>
#include <aslam/backend/VectorExpressionNode.hpp>
#include <sm/kinematics/homogeneous_coordinates.hpp>
#include <sm/kinematics/rotations.hpp>
namespace aslam {
namespace backend {
EuclideanExpressionNode::EuclideanExpressionNode() {}
EuclideanExpressionNode::~EuclideanExpressionNode() {}
/// \brief Evaluate the euclidean matrix.
Eigen::Vector3d EuclideanExpressionNode::toEuclidean() const { return toEuclideanImplementation(); }
/// \brief Evaluate the Jacobians
void EuclideanExpressionNode::evaluateJacobians(JacobianContainer& outJacobians) const {
evaluateJacobiansImplementation(outJacobians);
}
/// \brief Evaluate the Jacobians and apply the chain rule.
void EuclideanExpressionNode::evaluateJacobians(JacobianContainer& outJacobians,
const Eigen::MatrixXd& applyChainRule) const {
SM_ASSERT_EQ_DBG(Exception, applyChainRule.cols(), 3, "The chain rule matrix must have three columns");
evaluateJacobiansImplementation(outJacobians, applyChainRule);
}
void EuclideanExpressionNode::getDesignVariables(DesignVariable::set_t& designVariables) const {
getDesignVariablesImplementation(designVariables);
}
EuclideanExpressionNodeMultiply::EuclideanExpressionNodeMultiply(boost::shared_ptr<RotationExpressionNode> lhs,
boost::shared_ptr<EuclideanExpressionNode> rhs)
: _lhs(lhs), _rhs(rhs) {
_C_lhs = _lhs->toRotationMatrix();
_p_rhs = _rhs->toEuclidean();
}
EuclideanExpressionNodeMultiply::~EuclideanExpressionNodeMultiply() {}
void EuclideanExpressionNodeMultiply::getDesignVariablesImplementation(DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
_rhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeMultiply::toEuclideanImplementation() const {
_C_lhs = _lhs->toRotationMatrix();
_p_rhs = _rhs->toEuclidean();
return _C_lhs * _p_rhs;
}
void EuclideanExpressionNodeMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_lhs->evaluateJacobians(outJacobians, sm::kinematics::crossMx(_C_lhs * _p_rhs));
_rhs->evaluateJacobians(outJacobians, _C_lhs);
}
void EuclideanExpressionNodeMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians,
const Eigen::MatrixXd& applyChainRule) const {
_lhs->evaluateJacobians(outJacobians, applyChainRule * sm::kinematics::crossMx(_C_lhs * _p_rhs));
_rhs->evaluateJacobians(outJacobians, applyChainRule * _C_lhs);
}
// -------------------------------------------------------
// ## New Class for rotations with MatrixExpressions
EuclideanExpressionNodeMatrixMultiply::EuclideanExpressionNodeMatrixMultiply(
boost::shared_ptr<MatrixExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs)
: _lhs(lhs), _rhs(rhs) {
_A_lhs = _lhs->toMatrix3x3();
_p_rhs = _rhs->toEuclidean();
}
EuclideanExpressionNodeMatrixMultiply::~EuclideanExpressionNodeMatrixMultiply() {}
void EuclideanExpressionNodeMatrixMultiply::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
_rhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeMatrixMultiply::toEuclideanImplementation() const {
_A_lhs = _lhs->toMatrix3x3();
_p_rhs = _rhs->toEuclidean();
return _A_lhs * _p_rhs;
}
void EuclideanExpressionNodeMatrixMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
Eigen::Matrix<double, 3, 9> J_full;
J_full << _p_rhs(0) * Eigen::Matrix3d::Identity(), _p_rhs(1) * Eigen::Matrix3d::Identity(),
_p_rhs(2) * Eigen::Matrix3d::Identity();
_lhs->evaluateJacobians(outJacobians, J_full);
_rhs->evaluateJacobians(outJacobians, _A_lhs);
}
void EuclideanExpressionNodeMatrixMultiply::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
Eigen::Matrix<double, 3, 9> J_full;
J_full << _p_rhs(0) * Eigen::Matrix3d::Identity(), _p_rhs(1) * Eigen::Matrix3d::Identity(),
_p_rhs(2) * Eigen::Matrix3d::Identity();
_lhs->evaluateJacobians(outJacobians, applyChainRule * J_full);
_rhs->evaluateJacobians(outJacobians, applyChainRule * _A_lhs);
}
// ----------------------------
EuclideanExpressionNodeCrossEuclidean::EuclideanExpressionNodeCrossEuclidean(
boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs)
: _lhs(lhs), _rhs(rhs) {}
EuclideanExpressionNodeCrossEuclidean::~EuclideanExpressionNodeCrossEuclidean() {}
void EuclideanExpressionNodeCrossEuclidean::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
_rhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeCrossEuclidean::toEuclideanImplementation() const {
return sm::kinematics::crossMx(_lhs->toEuclidean()) * _rhs->toEuclidean();
;
}
void EuclideanExpressionNodeCrossEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_lhs->evaluateJacobians(outJacobians, -sm::kinematics::crossMx(_rhs->toEuclidean()));
_rhs->evaluateJacobians(outJacobians, sm::kinematics::crossMx(_lhs->toEuclidean()));
}
void EuclideanExpressionNodeCrossEuclidean::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
_lhs->evaluateJacobians(outJacobians, -applyChainRule * sm::kinematics::crossMx(_rhs->toEuclidean()));
_rhs->evaluateJacobians(outJacobians, applyChainRule * sm::kinematics::crossMx(_lhs->toEuclidean()));
}
EuclideanExpressionNodeAddEuclidean::EuclideanExpressionNodeAddEuclidean(boost::shared_ptr<EuclideanExpressionNode> lhs,
boost::shared_ptr<EuclideanExpressionNode> rhs)
: _lhs(lhs), _rhs(rhs) {}
EuclideanExpressionNodeAddEuclidean::~EuclideanExpressionNodeAddEuclidean() {}
void EuclideanExpressionNodeAddEuclidean::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
_rhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeAddEuclidean::toEuclideanImplementation() const {
return _lhs->toEuclidean() + _rhs->toEuclidean();
}
void EuclideanExpressionNodeAddEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_lhs->evaluateJacobians(outJacobians);
_rhs->evaluateJacobians(outJacobians);
}
void EuclideanExpressionNodeAddEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians,
const Eigen::MatrixXd& applyChainRule) const {
_lhs->evaluateJacobians(outJacobians, applyChainRule);
_rhs->evaluateJacobians(outJacobians, applyChainRule);
}
EuclideanExpressionNodeSubtractEuclidean::EuclideanExpressionNodeSubtractEuclidean(
boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs)
: _lhs(lhs), _rhs(rhs) {}
EuclideanExpressionNodeSubtractEuclidean::~EuclideanExpressionNodeSubtractEuclidean() {}
void EuclideanExpressionNodeSubtractEuclidean::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
_rhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeSubtractEuclidean::toEuclideanImplementation() const {
return _lhs->toEuclidean() - _rhs->toEuclidean();
}
void EuclideanExpressionNodeSubtractEuclidean::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_lhs->evaluateJacobians(outJacobians);
_rhs->evaluateJacobians(outJacobians, -Eigen::Matrix3d::Identity());
}
void EuclideanExpressionNodeSubtractEuclidean::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
_lhs->evaluateJacobians(outJacobians, applyChainRule);
_rhs->evaluateJacobians(outJacobians, -applyChainRule);
}
EuclideanExpressionNodeConstant::EuclideanExpressionNodeConstant(const Eigen::Vector3d& p) : _p(p) {}
EuclideanExpressionNodeConstant::~EuclideanExpressionNodeConstant() {}
void EuclideanExpressionNodeConstant::getDesignVariablesImplementation(
DesignVariable::set_t& /* designVariables */) const {}
Eigen::Vector3d EuclideanExpressionNodeConstant::toEuclideanImplementation() const { return _p; }
void EuclideanExpressionNodeConstant::evaluateJacobiansImplementation(JacobianContainer& /* outJacobians */) const {}
void EuclideanExpressionNodeConstant::evaluateJacobiansImplementation(
JacobianContainer& /* outJacobians */, const Eigen::MatrixXd& /* applyChainRule */) const {}
EuclideanExpressionNodeSubtractVector::EuclideanExpressionNodeSubtractVector(
boost::shared_ptr<EuclideanExpressionNode> lhs, const Eigen::Vector3d& rhs)
: _lhs(lhs), _rhs(rhs) {}
EuclideanExpressionNodeSubtractVector::~EuclideanExpressionNodeSubtractVector() {}
void EuclideanExpressionNodeSubtractVector::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeSubtractVector::toEuclideanImplementation() const {
return _lhs->toEuclidean() - _rhs;
}
void EuclideanExpressionNodeSubtractVector::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_lhs->evaluateJacobians(outJacobians);
}
void EuclideanExpressionNodeSubtractVector::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
_lhs->evaluateJacobians(outJacobians, applyChainRule);
}
EuclideanExpressionNodeNegated::EuclideanExpressionNodeNegated(boost::shared_ptr<EuclideanExpressionNode> operand)
: _operand(operand) {}
EuclideanExpressionNodeNegated::~EuclideanExpressionNodeNegated() {}
void EuclideanExpressionNodeNegated::getDesignVariablesImplementation(DesignVariable::set_t& designVariables) const {
_operand->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeNegated::toEuclideanImplementation() const { return -_operand->toEuclidean(); }
void EuclideanExpressionNodeNegated::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_operand->evaluateJacobians(outJacobians, -Eigen::Matrix3d::Identity());
}
void EuclideanExpressionNodeNegated::evaluateJacobiansImplementation(JacobianContainer& outJacobians,
const Eigen::MatrixXd& applyChainRule) const {
_operand->evaluateJacobians(outJacobians, -applyChainRule);
}
EuclideanExpressionNodeScalarMultiply::EuclideanExpressionNodeScalarMultiply(
boost::shared_ptr<EuclideanExpressionNode> p, boost::shared_ptr<ScalarExpressionNode> s)
: _p(p), _s(s) {}
EuclideanExpressionNodeScalarMultiply::~EuclideanExpressionNodeScalarMultiply() {}
void EuclideanExpressionNodeScalarMultiply::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_p->getDesignVariables(designVariables);
_s->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeScalarMultiply::toEuclideanImplementation() const {
return _p->toEuclidean() * _s->toScalar();
}
void EuclideanExpressionNodeScalarMultiply::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
_p->evaluateJacobians(outJacobians, Eigen::Matrix3d::Identity() * _s->toScalar());
_s->evaluateJacobians(outJacobians, _p->toEuclidean());
}
void EuclideanExpressionNodeScalarMultiply::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
_p->evaluateJacobians(outJacobians, applyChainRule * _s->toScalar());
_s->evaluateJacobians(outJacobians, applyChainRule * _p->toEuclidean());
}
VectorExpression2EuclideanExpressionAdapter::VectorExpression2EuclideanExpressionAdapter(
boost::shared_ptr<VectorExpressionNode<3> > vectorExpressionNode)
: _vectorExpressionNode(vectorExpressionNode) {}
VectorExpression2EuclideanExpressionAdapter::~VectorExpression2EuclideanExpressionAdapter() {}
void VectorExpression2EuclideanExpressionAdapter::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_vectorExpressionNode->getDesignVariables(designVariables);
}
Eigen::Vector3d VectorExpression2EuclideanExpressionAdapter::toEuclideanImplementation() const {
return _vectorExpressionNode->toVector();
}
void VectorExpression2EuclideanExpressionAdapter::evaluateJacobiansImplementation(
JacobianContainer& outJacobians) const {
_vectorExpressionNode->evaluateJacobians(outJacobians, Eigen::Matrix3d::Identity());
}
void VectorExpression2EuclideanExpressionAdapter::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
_vectorExpressionNode->evaluateJacobians(outJacobians, applyChainRule * Eigen::Matrix3d::Identity());
}
EuclideanExpressionNodeTranslation::EuclideanExpressionNodeTranslation(
boost::shared_ptr<TransformationExpressionNode> operand)
: _operand(operand) {}
EuclideanExpressionNodeTranslation::~EuclideanExpressionNodeTranslation() {}
Eigen::Vector3d EuclideanExpressionNodeTranslation::toEuclideanImplementation() const {
return _operand->toTransformationMatrix().topRightCorner<3, 1>();
}
void EuclideanExpressionNodeTranslation::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
Eigen::MatrixXd J = Eigen::MatrixXd::Identity(3, 6);
Eigen::Vector3d p = _operand->toTransformationMatrix().topRightCorner<3, 1>();
J.topRightCorner<3, 3>() = sm::kinematics::crossMx(p);
_operand->evaluateJacobians(outJacobians, J);
}
void EuclideanExpressionNodeTranslation::evaluateJacobiansImplementation(JacobianContainer& outJacobians,
const Eigen::MatrixXd& applyChainRule) const {
Eigen::MatrixXd J = Eigen::MatrixXd::Identity(3, 6);
Eigen::Vector3d p = _operand->toTransformationMatrix().topRightCorner<3, 1>();
J.topRightCorner<3, 3>() = sm::kinematics::crossMx(p);
_operand->evaluateJacobians(outJacobians, applyChainRule * J);
}
void EuclideanExpressionNodeTranslation::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
return _operand->getDesignVariables(designVariables);
}
EuclideanExpressionNodeRotationParameters::EuclideanExpressionNodeRotationParameters(
boost::shared_ptr<RotationExpressionNode> operand, sm::kinematics::RotationalKinematics::Ptr rk)
: _operand(operand), _rk(rk) {}
EuclideanExpressionNodeRotationParameters::~EuclideanExpressionNodeRotationParameters() {}
Eigen::Vector3d EuclideanExpressionNodeRotationParameters::toEuclideanImplementation() const {
return _rk->rotationMatrixToParameters(_operand->toRotationMatrix());
}
void EuclideanExpressionNodeRotationParameters::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
Eigen::MatrixXd J =
_rk->parametersToSMatrix(_rk->rotationMatrixToParameters(_operand->toRotationMatrix())).inverse();
_operand->evaluateJacobians(outJacobians, J);
}
void EuclideanExpressionNodeRotationParameters::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
Eigen::MatrixXd J =
_rk->parametersToSMatrix(_rk->rotationMatrixToParameters(_operand->toRotationMatrix())).inverse();
_operand->evaluateJacobians(outJacobians, applyChainRule * J);
}
void EuclideanExpressionNodeRotationParameters::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
return _operand->getDesignVariables(designVariables);
}
EuclideanExpressionNodeFromHomogeneous::EuclideanExpressionNodeFromHomogeneous(
boost::shared_ptr<HomogeneousExpressionNode> root)
: _root(root) {}
EuclideanExpressionNodeFromHomogeneous::~EuclideanExpressionNodeFromHomogeneous() {}
Eigen::Vector3d EuclideanExpressionNodeFromHomogeneous::toEuclideanImplementation() const {
return sm::kinematics::fromHomogeneous(_root->toHomogeneous());
}
void EuclideanExpressionNodeFromHomogeneous::evaluateJacobiansImplementation(JacobianContainer& outJacobians) const {
// Eigen::Vector3d fromHomogeneous(const Eigen::Vector4d & v, Eigen::Matrix<double,3,4> * jacobian = NULL);
Eigen::Matrix<double, 3, 4> Jh;
sm::kinematics::fromHomogeneous(_root->toHomogeneous(), &Jh);
_root->evaluateJacobians(outJacobians, Jh);
}
void EuclideanExpressionNodeFromHomogeneous::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
Eigen::Matrix<double, 3, 4> Jh;
sm::kinematics::fromHomogeneous(_root->toHomogeneous(), &Jh);
_root->evaluateJacobians(outJacobians, applyChainRule * Jh);
}
void EuclideanExpressionNodeFromHomogeneous::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_root->getDesignVariables(designVariables);
}
EuclideanExpressionNodeElementwiseMultiplyEuclidean::EuclideanExpressionNodeElementwiseMultiplyEuclidean(
boost::shared_ptr<EuclideanExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs)
: _lhs(lhs), _rhs(rhs) {}
EuclideanExpressionNodeElementwiseMultiplyEuclidean::~EuclideanExpressionNodeElementwiseMultiplyEuclidean() {}
void EuclideanExpressionNodeElementwiseMultiplyEuclidean::getDesignVariablesImplementation(
DesignVariable::set_t& designVariables) const {
_lhs->getDesignVariables(designVariables);
_rhs->getDesignVariables(designVariables);
}
Eigen::Vector3d EuclideanExpressionNodeElementwiseMultiplyEuclidean::toEuclideanImplementation() const {
return (_lhs->toEuclidean()).cwiseProduct(_rhs->toEuclidean());
}
void EuclideanExpressionNodeElementwiseMultiplyEuclidean::evaluateJacobiansImplementation(
JacobianContainer& outJacobians) const {
_lhs->evaluateJacobians(outJacobians, _rhs->toEuclidean().asDiagonal());
_rhs->evaluateJacobians(outJacobians, _lhs->toEuclidean().asDiagonal());
}
void EuclideanExpressionNodeElementwiseMultiplyEuclidean::evaluateJacobiansImplementation(
JacobianContainer& outJacobians, const Eigen::MatrixXd& applyChainRule) const {
_lhs->evaluateJacobians(outJacobians, applyChainRule * _rhs->toEuclidean().asDiagonal());
_rhs->evaluateJacobians(outJacobians, applyChainRule * _lhs->toEuclidean().asDiagonal());
}
} // namespace backend
} // namespace aslam
| 19,019 | 5,830 |
// Copyright 2015 Paddle Creek Games Inc. All Rights Reserved.
#include "HttpRpcRequest.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/util/type_resolver_util.h>
DEFINE_LOG_CATEGORY_STATIC(HttpRpcRequestLog, Log, All);
#define LOCTEXT_NAMESPACE "HttpRpcRequest"
using google::protobuf::Closure;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::Message;
using google::protobuf::MethodDescriptor;
using google::protobuf::RpcController;
using google::protobuf::Message;
using google::protobuf::MethodDescriptor;
using google::protobuf::util::JsonOptions;
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
using google::protobuf::util::TypeResolver;
static const char kTypeUrlPrefix[] = "type.googleapis.com";
static std::string GetTypeUrl(const Descriptor* message) {
return std::string(kTypeUrlPrefix) + "/" + message->full_name();
}
const FString HttpRpcRequest::kContentTypeJson = "application/json";
const FString HttpRpcRequest::kContentTypeBinary = "application/x-protobuf";
const FString HttpRpcRequest::kContentTypeASCII = "application/x-protobuf-text";
HttpRpcRequest::HttpRpcRequest(
HttpRpcRequestStrategy RequestStrategy, TypeResolver* ProtoTypeResolver, int64 RequestId, const FString& ServiceUri,
const MethodDescriptor* Method, RpcController* Controller, const Message* Request, Message* Response, Closure* Done)
: callState_(Method, Controller, Request, Response, Done),
httpRequest_(FHttpModule::Get().CreateRequest()),
requestId_(RequestId),
typeResolver_(ProtoTypeResolver),
requestStrategy_(RequestStrategy) {
httpRequest_->SetVerb(TEXT("POST"));
httpRequest_->SetURL(ServiceUri);
httpRequest_->SetHeader("X-Request-ID", FString::Printf(TEXT("%u"), RequestId));
httpRequest_->SetHeader("X-Method", FString(Method->name().c_str()));
}
HttpRpcRequest::~HttpRpcRequest() {}
bool HttpRpcRequest::Init() {
if (requestStrategy_ == HttpRpcRequestStrategy::HRRS_JSON) {
std::string jsonString;
JsonOptions jsonOptions;
jsonOptions.always_print_primitive_fields = true;
jsonOptions.add_whitespace = true;
Status status = google::protobuf::util::BinaryToJsonString(
typeResolver_, GetTypeUrl(callState_.GetRequest()->GetDescriptor()), callState_.GetRequest()->SerializeAsString(),
&jsonString, jsonOptions);
if (!status.ok()) {
UE_LOG(HttpRpcRequestLog,
Error,
TEXT("Failed to serialize to json (%s)"),
*FString(status.error_message().ToString().c_str()));
callState_.GetController()->SetFailed("JSON serialization failed");
return false;
}
httpRequest_->SetHeader("Content-Type", kContentTypeJson);
httpRequest_->SetContentAsString(FString(jsonString.c_str()));
} else if (requestStrategy_ == HttpRpcRequestStrategy::HRRS_PROTOASCII) {
std::string textString;
if (!google::protobuf::TextFormat::PrintToString(*callState_.GetRequest(), &textString)) {
UE_LOG(HttpRpcRequestLog, Error, TEXT("Failed to serialize to text"));
callState_.GetController()->SetFailed("Text serialization failed");
return false;
}
httpRequest_->SetHeader("Content-Type", kContentTypeASCII);
httpRequest_->SetContentAsString(FString(textString.c_str()));
} else if (requestStrategy_ == HttpRpcRequestStrategy::HRRS_PROTOBINARY) {
std::string binaryString = callState_.GetRequest()->SerializeAsString();
httpRequest_->SetHeader("Content-Type", kContentTypeBinary);
httpRequest_->SetContentAsString(FString(binaryString.c_str()));
} else {
UE_LOG(HttpRpcRequestLog, Error, TEXT("Invalid HTTP request strategy"));
callState_.GetController()->SetFailed("Invalid HTTP request strategy");
return false;
}
httpRequest_->OnProcessRequestComplete().BindRaw(this, &HttpRpcRequest::onHttpRequestCompleted);
return true;
}
bool HttpRpcRequest::Execute() {
if (!httpRequest_->ProcessRequest()) {
UE_LOG(HttpRpcRequestLog, Error, TEXT("ProcessRequest failed"));
callState_.GetController()->SetFailed("ProcessRequest failed");
return false;
}
return true;
}
void HttpRpcRequest::onHttpRequestCompleted(FHttpRequestPtr request, FHttpResponsePtr response, bool bWasSuccessful) {
if (!bWasSuccessful) {
UE_LOG(HttpRpcRequestLog, Error, TEXT("HTTP request failed"));
callState_.GetController()->SetFailed("HTTP request failed");
} else {
const int responseCode = response->GetResponseCode();
if (responseCode != 200) {
if ((responseCode >= 300) && (responseCode < 400)) {
// TODO(san): Handle redirects.
callState_.GetController()->SetFailed("Unsupported redirect");
} else {
UE_LOG(HttpRpcRequestLog, Error, TEXT("HTTP response code %d (%s)"), response->GetResponseCode(), *response->GetContentAsString());
callState_.GetController()->SetFailed("Bad HTTP response code");
}
} else {
// Successful HTTP response.
int requestId = ParseRequestIdFromResponse(response);
if (requestId == -1) {
UE_LOG(HttpRpcRequestLog, Error, TEXT("HTTP response missing request id"));
callState_.GetController()->SetFailed("Response missing request id");
// TODO(san): Think about whether we should be strict about this given we have the request handy.
} else if (requestId != FCString::Atoi(*request->GetHeader("X-Request-ID"))) {
// If this happens legitimately then we are most likely inheriting a 'threading issue' from the
// HTTP module - in which case we'll probably need to track outstanding requests ourselves.
UE_LOG(HttpRpcRequestLog, Error, TEXT("Mismatched Request/Response!"));
callState_.GetController()->SetFailed("Mismatched Request/Response ID");
} else {
// Request ID is valid. Extract the protobuf from the HTTP content buffer.
if (!ParseMessageFromResponse(response)) {
UE_LOG(HttpRpcRequestLog, Warning, TEXT("Failed to parse response protobuf"));
callState_.GetController()->SetFailed("Failed to parse response protobuf");
}
}
}
}
Closure* cachedClosure = callState_.GetDone();
delete this;
cachedClosure->Run();
}
int HttpRpcRequest::ParseRequestIdFromResponse(FHttpResponsePtr response) {
FString requestIdString = response->GetHeader("X-Request-ID");
if (requestIdString == "") {
return -1;
}
return FCString::Atoi(*requestIdString);
}
bool HttpRpcRequest::ParseMessageFromResponse(FHttpResponsePtr response) {
const FString contentType = response->GetContentType();
if (contentType.StartsWith(kContentTypeJson)) {
} else if (contentType.StartsWith(kContentTypeASCII)) {
if (!google::protobuf::TextFormat::ParseFromString(TCHAR_TO_UTF8(*response->GetContentAsString()), callState_.GetResponse())) {
UE_LOG(HttpRpcRequestLog, Error, TEXT("ASCII response parse failed"));
return false;
}
return true;
} else if (contentType.StartsWith(kContentTypeBinary)) {
} else {
UE_LOG(HttpRpcRequestLog, Error, TEXT("Invalid content type '%s'"), *contentType);
}
return false;
} | 7,099 | 2,272 |
// https://www.hackerrank.com/challenges/game-of-throne-ii
#include "common/modular/static/factorial.h"
#include "common/modular_io.h"
#include "common/stl/base.h"
#include <string>
using TFactorial = modular::mstatic::Factorial<TModularD, false>;
int main_game_of_thrones_ii() {
TFactorial f;
string s;
cin >> s;
sort(s.begin(), s.end());
unsigned n = unsigned(s.size());
s.push_back(' ');
unsigned ls = 0, so = 0;
TModularD r = 1;
for (unsigned i = 1; i <= n; ++i) {
if (s[i] == s[i - 1]) continue;
unsigned l = i - ls;
ls = i;
so += (l & 1);
r *= f(l / 2);
}
cout << ((so > 1) ? TModularD(0) : f(n / 2) / r) << endl;
return 0;
}
| 680 | 309 |
/*
* Copyright 2019 Google LLC
*
* 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 "app/src/base64.h"
#include "app/src/log.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "openssl/base64.h"
namespace firebase {
namespace internal {
size_t OpenSSHEncodedLength(size_t input_size) {
size_t length;
if (!EVP_EncodedLength(&length, input_size)) {
return 0;
}
return length;
}
bool OpenSSHEncode(const std::string& input, std::string* output) {
size_t base64_length = OpenSSHEncodedLength(input.size());
output->resize(base64_length);
if (EVP_EncodeBlock(reinterpret_cast<uint8_t*>(&(*output)[0]),
reinterpret_cast<const uint8_t*>(&input[0]),
input.size()) == 0u) {
return false;
}
// Trim the terminating null character.
output->resize(base64_length - 1);
return true;
}
size_t OpenSSHDecodedLength(size_t input_size) {
size_t length;
if (!EVP_DecodedLength(&length, input_size)) {
return 0;
}
return length;
}
bool OpenSSHDecode(const std::string& input, std::string* output) {
size_t decoded_length = OpenSSHDecodedLength(input.size());
output->resize(decoded_length);
if (EVP_DecodeBase64(reinterpret_cast<uint8_t*>(&(*output)[0]),
&decoded_length, decoded_length,
reinterpret_cast<const uint8_t*>(&(input)[0]),
input.size()) == 0) {
return false;
}
// Decoded length includes null termination, remove.
output->resize(decoded_length);
return true;
}
TEST(Base64TestAgainstOpenSSH, TestEncodingAgainstOpenSSH) {
// Run this test 100 times.
for (int i = 0; i < 100; i++) {
// Generate 1-10000 random bytes. OpenSSH can't encode an empty string.
size_t bytes = 1 + rand() % 9999; // NOLINT
std::string orig;
orig.resize(bytes);
for (int c = 0; c < orig.size(); ++c) {
orig[c] = rand() % 0xFF; // NOLINT
}
std::string encoded_firebase, encoded_openssh;
ASSERT_TRUE(Base64EncodeWithPadding(orig, &encoded_firebase));
ASSERT_TRUE(OpenSSHEncode(orig, &encoded_openssh));
EXPECT_EQ(encoded_firebase, encoded_openssh)
<< "Encoding mismatch on source buffer: " << orig;
std::string decoded_firebase_to_openssh;
std::string decoded_openssh_to_firebase;
ASSERT_TRUE(Base64Decode(encoded_openssh, &decoded_openssh_to_firebase));
ASSERT_TRUE(OpenSSHDecode(encoded_firebase, &decoded_firebase_to_openssh));
EXPECT_EQ(decoded_openssh_to_firebase, decoded_firebase_to_openssh)
<< "Cross-decoding mismatch on source buffer: " << orig;
EXPECT_EQ(orig, decoded_firebase_to_openssh);
EXPECT_EQ(orig, decoded_openssh_to_firebase);
}
}
} // namespace internal
} // namespace firebase
| 3,279 | 1,153 |
/*********************************************************************
* Rice University Software Distribution License
*
* Copyright (c) 2010, Rice University
* All Rights Reserved.
*
* For a full description see the file named LICENSE.
*
*********************************************************************/
/* Author: Mark Moll */
#include <ompl/control/planners/est/EST.h>
#include <ompl/control/planners/kpiece/KPIECE1.h>
#include <ompl/control/planners/pdst/PDST.h>
#include <ompl/control/planners/rrt/RRT.h>
#include <ompl/tools/benchmark/Benchmark.h>
#include <omplapp/apps/DynamicCarPlanning.h>
#include <omplapp/config.h>
using namespace ompl;
void dynamicCarSetup(app::DynamicCarPlanning &setup)
{
// plan for dynamic car in SE(2)
base::StateSpacePtr stateSpace(setup.getStateSpace());
// set the bounds for the R^2 part of SE(2)
base::RealVectorBounds bounds(2);
bounds.setLow(-10);
bounds.setHigh(10);
stateSpace->as<base::CompoundStateSpace>()->as<base::SE2StateSpace>(0)->setBounds(bounds);
// define start state
base::ScopedState<> start(stateSpace);
start[0] = start[1] = start[2] = start[3] = start[4] = 0.;
// define goal state
base::ScopedState<> goal(stateSpace);
goal[0] = goal[1] = 8.;
goal[2] = 0;
goal[3] = goal[4] = 0.;
// set the start & goal states
setup.setStartAndGoalStates(start, goal, .5);
// optionally, set a planner
// setup.setPlanner(std::make_shared<control::EST>(setup.getSpaceInformation()));
setup.setPlanner(std::make_shared<control::RRT>(setup.getSpaceInformation()));
// setup.setPlanner(std::make_shared<control::KPIECE1>(setup.getSpaceInformation()));
// setup.setPlanner(std::make_shared<control::PDST>(setup.getSpaceInformation()));
std::vector<double> cs(2);
cs[0] = cs[1] = 0.1;
setup.setup();
setup.getStateSpace()->getDefaultProjection()->setCellSizes(cs);
}
void dynamicCarDemo(app::DynamicCarPlanning &setup)
{
std::cout << "\n\n***** Planning for a " << setup.getName() << " *****\n" << std::endl;
// try to solve the problem
if (setup.solve(40))
{
// print the (approximate) solution path: print states along the path
// and controls required to get from one state to the next
control::PathControl &path(setup.getSolutionPath());
path.interpolate(); // uncomment if you want to plot the path
path.print(std::cout);
if (!setup.haveExactSolutionPath())
{
std::cout << "Solution is approximate. Distance to actual goal is "
<< setup.getProblemDefinition()->getSolutionDifference() << std::endl;
}
}
}
void dynamicCarBenchmark(app::DynamicCarPlanning &setup)
{
tools::Benchmark::Request request(100., 10000., 2); // runtime (s), memory (MB), run count
setup.setup();
tools::Benchmark b(setup, setup.getName());
b.addPlanner(std::make_shared<control::RRT>(setup.getSpaceInformation()));
b.addPlanner(std::make_shared<control::KPIECE1>(setup.getSpaceInformation()));
b.benchmark(request);
b.saveResultsToFile("J:\\result.txt");
}
int main(int argc, char ** /*unused*/)
{
app::DynamicCarPlanning car;
dynamicCarSetup(car);
// If any command line arguments are given, solve the problem multiple
// times with different planners and collect benchmark statistics.
// Otherwise, solve the problem once and print the path.
//if (argc > 1)
dynamicCarDemo(car);
//else
//dynamicCarDemo(car);
return 0;
}
| 3,561 | 1,153 |
#include "olcPixelGameEngine.h"
#include <cstdlib>
#include <memory>
#include "GameEngine.h"
#include "Card.h"
#include "Board.h"
int main()
{
clsEngine gameInstance;
if (gameInstance.Construct(1280, 720, 1, 1))
gameInstance.Start();
return 0;
} | 255 | 111 |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008 Andreas Gaida
Copyright (C) 2008 Ralph Schreyer
Copyright (C) 2008 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <ql/instruments/dividendbarrieroption.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <ql/exercise.hpp>
namespace QuantLib {
DividendBarrierOption::DividendBarrierOption(
Barrier::Type barrierType,
Real barrier,
Real rebate,
const ext::shared_ptr<StrikedTypePayoff>& payoff,
const ext::shared_ptr<Exercise>& exercise,
const std::vector<Date>& dividendDates,
const std::vector<Real>& dividends)
: BarrierOption(barrierType, barrier, rebate, payoff, exercise),
cashFlow_(DividendVector(dividendDates, dividends)) {}
void DividendBarrierOption::setupArguments(
PricingEngine::arguments* args) const {
BarrierOption::setupArguments(args);
auto* arguments = dynamic_cast<DividendBarrierOption::arguments*>(args);
QL_REQUIRE(arguments != nullptr, "wrong engine type");
arguments->cashFlow = cashFlow_;
}
void DividendBarrierOption::arguments::validate() const {
BarrierOption::arguments::validate();
Date exerciseDate = exercise->lastDate();
for (Size i = 0; i < cashFlow.size(); i++) {
QL_REQUIRE(cashFlow[i]->date() <= exerciseDate,
"the " << io::ordinal(i+1) << " dividend date ("
<< cashFlow[i]->date()
<< ") is later than the exercise date ("
<< exerciseDate << ")");
}
}
}
| 2,479 | 731 |