text
stringlengths 5
1.04M
|
|---|
/**
* @file new_sim_file_rdr.cpp
*
* The file includes an abstract class for parsing the special rdr data:\n
* NewSimulatorFileRdr
*
* @author Lars Wetzel <larswetzel@users.sourceforge.net>
* @version 0.1
* @date 2010
*
* 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. This
* file and program are licensed under a BSD style license. See
* the Copying file included with the OpenHPI distribution for
* full licensing terms.
*
*/
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <glib.h>
#include <SaHpi.h>
#include "new_sim_file_rdr.h"
#include "new_sim_file_util.h"
#include <oh_error.h>
/**
* Constructor
**/
NewSimulatorFileRdr::NewSimulatorFileRdr(GScanner *scanner)
: NewSimulatorFileUtil ( scanner ),
m_depth ( 0 ) {
memset( &m_rdr, 0, sizeof( SaHpiRdrT ));
}
/**
* Destructor
**/
NewSimulatorFileRdr::~NewSimulatorFileRdr() {
}
/**
* Read a RDR section
*
* Startpoint is token \c RDR_TOKEN_HANDLER. Endpoint is \c G_TOKEN_RIGHT_CURLY if
* no error occurs during parsing.\n
* Depend on wich RDR type is read, some helper functions are called.
*
* @return success bool
*
**/
bool NewSimulatorFileRdr::process_rdr_token( void ) {
guint cur_token = g_scanner_get_next_token(m_scanner);
char *rdrfield;
NewSimulatorEntityPath ep;
bool success = true;
bool commonBlock = true;
if (cur_token != G_TOKEN_LEFT_CURLY) {
err("Processing parse configuration: Expected left curly token.");
return false;
}
m_depth++;
while ( commonBlock && success) {
cur_token = g_scanner_get_next_token(m_scanner);
switch (cur_token) {
case G_TOKEN_EOF:
err("Processing parse rpt entry: File ends too early");
success = false;
break;
case G_TOKEN_RIGHT_CURLY:
m_depth--;
break;
case G_TOKEN_LEFT_CURLY:
m_depth++;
break;
case RDR_DETAIL_TOKEN_HANDLER:
commonBlock = false;
break;
case G_TOKEN_STRING:
rdrfield = g_strdup(m_scanner->value.v_string);
cur_token = g_scanner_get_next_token(m_scanner);
if (cur_token != G_TOKEN_EQUAL_SIGN) {
err("Processing parse rdr entry: Missing equal sign");
success = false;
}
cur_token = g_scanner_get_next_token(m_scanner);
if (!strcmp(rdrfield, "RecordId")) {
// will be assigned by the daemon -> ignore it
stdlog << "DBG: rdr - RecordId is ignored\n";
} else if (!strcmp(rdrfield, "RdrType")) {
if (cur_token == G_TOKEN_INT) {
m_rdr.RdrType = (SaHpiRdrTypeT) m_scanner->value.v_int;
stdlog << "DBG: rdr - RdrType " << m_rdr.RdrType << "\n";
} else {
err("Processing parse rpt entry: Wrong kind of RdrType");
}
} else if (!strcmp(rdrfield, "Entity")) {
if (cur_token == G_TOKEN_LEFT_CURLY)
success = process_entity( m_rdr.Entity );
if ( !success )
err("Error at parsing the entity path");
} else if (!strcmp(rdrfield, "IsFru")) {
if (cur_token == G_TOKEN_INT) {
m_rdr.IsFru = m_scanner->value.v_int;
stdlog << "DBG: rdr - IsFru " << m_rdr.IsFru << "\n";
} else {
success = false;
err("Processing parse rdr entry: Wrong kind of IsFru");
}
} else if (!strcmp(rdrfield, "IdString")) {
if ( cur_token == G_TOKEN_LEFT_CURLY ) {
success = process_textbuffer( m_rdr.IdString );
stdlog << "DBG: IdString " << m_rdr.IdString << "\n";
} else {
success = false;
err("Processing parse rdr entry: Couldn't parse IdSting");
}
} else {
// Unknown Token
err("Processing parse rdr entry: Unknown Rdr field %s", rdrfield);
success = false;
}
break;
default:
err("Processing parse rdr entry: Unknown token");
success = false;
break;
}
}
return success;
}
|
#include "GoalDodgeStrike.h"
#include "GoalType.h"
#include "MyTeam.h"
#include "GoalCover.h"
#include "HelperFunctions.h"
#include "Globals.h"
#include "GoalMoveToPosition.h"
GoalDodgeStrike::GoalDodgeStrike(MyTank* pOwner):
GoalComposite<MyTank>(pOwner, goal_dodge_strike)
{
}
GoalDodgeStrike::~GoalDodgeStrike()
{
}
void GoalDodgeStrike::Activate()
{
m_iStatus = active;
RemoveAllSubgoals();
std::vector<glm::vec2> dangrousPos =
MyTeamMgr->GetDangerouseStrikePosToTank(m_pOwner->GetPosition());
// std::cout << "RUN RUN RUN.\n";
// PrintVector("Tank pos: ", m_pOwner->GetPosition());
// PrintVector("Danger strike pos: ", dangrousPos[0]);
if (!dangrousPos.empty())
{
glm::vec2 bestPosToRun = CalculateBestPosToRunAway(dangrousPos[0]);
// PrintVector("Best pos to go: ", bestPosToRun);
// AddSubgoal(new GoalMoveToPosition(m_pOwner, bestPosToRun));
m_pOwner->MoveOn();
m_pOwner->GetSteering()->SeekOn();
m_pOwner->GetSteering()->SetTarget(bestPosToRun);
}
}
int GoalDodgeStrike::Process()
{
ActivateIfInactive();
m_iStatus = ProcessSubgoals();
m_pOwner->StopInTheNextStepIsDangerous();
ReactivateIfFailed();
return m_iStatus;
}
void GoalDodgeStrike::Terminate()
{
m_pOwner->MoveOff();
m_pOwner->GetSteering()->SeekOff();
}
glm::vec2 GoalDodgeStrike::CalculateBestPosToRunAway(glm::vec2 strikePos)
{
glm::vec2 bestPos;
float farestDistance = 0;
for (glm::vec2 dir : dirs)
{
glm::vec2 futurePos = m_pOwner->GetPosition() + m_pOwner->GetSpeed() * dir;
float distance = Manhattan(futurePos, strikePos);
if (distance > farestDistance && TargetMgr->isValidTankPosition(futurePos)
&& !TargetMgr->isTheSamePositionWithOtherTank(m_pOwner->GetPosition(), futurePos))
{
farestDistance = distance;
bestPos = futurePos;
}
}
return bestPos;
}
|
// Copyright (c) 2006-2008 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 "webkit/glue/plugins/test/plugin_test.h"
#include "base/string_util.h"
#include "webkit/glue/plugins/test/npapi_constants.h"
namespace NPAPIClient {
PluginTest::PluginTest(NPP id, NPNetscapeFuncs *host_functions) {
id_ = id;
id_->pdata = this;
host_functions_ = host_functions;
}
NPError PluginTest::New(uint16 mode, int16 argc, const char* argn[],
const char* argv[], NPSavedData* saved) {
test_name_ = this->GetArgValue("name", argc, argn, argv);
test_id_ = this->GetArgValue("id", argc, argn, argv);
return NPERR_NO_ERROR;
}
NPError PluginTest::SetWindow(NPWindow* pNPWindow) {
return NPERR_NO_ERROR;
}
// It's a shame I have to implement URLEncode. But, using webkit's
// or using chrome's means a ball of string of dlls and dependencies that
// is very very long. After spending far too much time on it,
// I'll just encode it myself. Too bad Microsoft doesn't implement
// this in a reusable way either. Both webkit and chrome will
// end up using libicu, which is a string of dependencies we don't
// want.
inline unsigned char toHex(const unsigned char x) {
return x > 9 ? (x + 'A' - 10) : (x + '0');
}
std::string URLEncode(const std::string &sIn) {
std::string sOut;
const size_t length = sIn.length();
for (size_t idx = 0; idx < length;) {
const char ch = sIn.at(idx);
if (isalnum(ch)) {
sOut.append(1, ch);
} else if (isspace(ch) && ((ch != '\n') && (ch != '\r'))) {
sOut.append(1, '+');
} else {
sOut.append(1, '%');
sOut.append(1, toHex(ch>>4));
sOut.append(1, toHex(ch%16));
}
idx++;
}
return sOut;
}
void PluginTest::SignalTestCompleted() {
// To signal test completion, we expect a couple of
// javascript functions to be defined in the webpage
// which hosts this plugin:
// onSuccess(test_name, test_id)
// onFailure(test_name, test_id, error_message)
std::string script_result;
std::string script_url;
if (Succeeded()) {
script_url.append("onSuccess(\"");
script_url.append(test_name_);
script_url.append("\",\"");
script_url.append(test_id_);
script_url.append("\");");
} else {
script_url.append("onFailure(\"");
script_url.append(test_name_);
script_url.append("\",\"");
script_url.append(test_id_);
script_url.append("\",\"");
script_url.append(test_status_);
script_url.append("\");");
}
script_url = URLEncode(script_url);
script_result.append("javascript:");
script_result.append(script_url);
host_functions_->geturl(id_, script_result.c_str(), "_self");
}
const char *PluginTest::GetArgValue(const char *name, const int16 argc,
const char *argn[], const char *argv[]) {
for (int idx = 0; idx < argc; idx++)
if (base::strcasecmp(argn[idx], name) == 0)
return argv[idx];
return NULL;
}
void PluginTest::SetError(const std::string &msg) {
test_status_.append(msg);
}
NPError PluginTest::NewStream(NPMIMEType type, NPStream* stream,
NPBool seekable, uint16* stype) {
// There is no default action here.
return NPERR_NO_ERROR;
}
int32 PluginTest::WriteReady(NPStream *stream) {
// Take data in small chunks
return 4096;
}
int32 PluginTest::Write(NPStream *stream, int32 offset, int32 len,
void *buffer) {
// Pretend that we took all the data.
return len;
}
NPError PluginTest::DestroyStream(NPStream *stream, NPError reason) {
// There is no default action.
return NPERR_NO_ERROR;
}
void PluginTest::StreamAsFile(NPStream* stream, const char* fname) {
// There is no default action.
}
void PluginTest::URLNotify(const char* url, NPReason reason, void* data) {
// There is no default action
}
int16 PluginTest::HandleEvent(void* event) {
// There is no default action
return 0;
}
} // namespace NPAPIClient
|
/** @file
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "HttpHeader.h"
#include "slice.h"
#include <cstdlib>
#include <cstring>
TSHttpType
HttpHeader::type() const
{
if (isValid()) {
return TSHttpHdrTypeGet(m_buffer, m_lochdr);
} else {
return TS_HTTP_TYPE_UNKNOWN;
}
}
TSHttpStatus
HttpHeader::status() const
{
TSHttpStatus res = TS_HTTP_STATUS_NONE;
if (isValid()) {
res = TSHttpHdrStatusGet(m_buffer, m_lochdr);
}
return res;
}
bool
HttpHeader::setStatus(TSHttpStatus const newstatus)
{
if (!isValid()) {
return false;
}
return TS_SUCCESS == TSHttpHdrStatusSet(m_buffer, m_lochdr, newstatus);
}
char *
HttpHeader::urlString(int *const urllen) const
{
char *urlstr = nullptr;
TSAssert(nullptr != urllen);
TSMLoc locurl = nullptr;
TSReturnCode const rcode = TSHttpHdrUrlGet(m_buffer, m_lochdr, &locurl);
if (nullptr != locurl) {
if (TS_SUCCESS == rcode) {
urlstr = TSUrlStringGet(m_buffer, locurl, urllen);
} else {
*urllen = 0;
}
TSHandleMLocRelease(m_buffer, m_lochdr, locurl);
}
return urlstr;
}
bool
HttpHeader::setUrl(TSMBuffer const bufurl, TSMLoc const locurl)
{
if (!isValid()) {
return false;
}
TSMLoc locurlout = nullptr;
TSReturnCode rcode = TSHttpHdrUrlGet(m_buffer, m_lochdr, &locurlout);
if (TS_SUCCESS != rcode) {
return false;
}
// copy the url
rcode = TSUrlCopy(m_buffer, locurlout, bufurl, locurl);
// set url active
if (TS_SUCCESS == rcode) {
rcode = TSHttpHdrUrlSet(m_buffer, m_lochdr, locurlout);
}
TSHandleMLocRelease(m_buffer, m_lochdr, locurlout);
return TS_SUCCESS == rcode;
}
bool
HttpHeader::setReason(char const *const valstr, int const vallen)
{
if (isValid()) {
return TS_SUCCESS == TSHttpHdrReasonSet(m_buffer, m_lochdr, valstr, vallen);
} else {
return false;
}
}
char const *
HttpHeader::getCharPtr(CharPtrGetFunc func, int *const len) const
{
char const *res = nullptr;
if (isValid()) {
int reslen = 0;
res = func(m_buffer, m_lochdr, &reslen);
if (nullptr != len) {
*len = reslen;
}
}
if (nullptr == res && nullptr != len) {
*len = 0;
}
return res;
}
bool
HttpHeader::hasKey(char const *const key, int const keylen) const
{
if (!isValid()) {
return false;
}
TSMLoc const locfield(TSMimeHdrFieldFind(m_buffer, m_lochdr, key, keylen));
if (nullptr != locfield) {
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
return true;
}
return false;
}
bool
HttpHeader::removeKey(char const *const keystr, int const keylen)
{
if (!isValid()) {
return false;
}
bool status = true;
TSMLoc const locfield = TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen);
if (nullptr != locfield) {
int const rcode = TSMimeHdrFieldRemove(m_buffer, m_lochdr, locfield);
status = (TS_SUCCESS == rcode);
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
}
return status;
}
bool
HttpHeader::valueForKey(char const *const keystr, int const keylen, char *const valstr, int *const vallen, int const index) const
{
if (!isValid()) {
*vallen = 0;
return false;
}
bool status = false;
TSMLoc const locfield = TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen);
if (nullptr != locfield) {
int getlen = 0;
char const *const getstr = TSMimeHdrFieldValueStringGet(m_buffer, m_lochdr, locfield, index, &getlen);
int const valcap = *vallen;
if (nullptr != getstr && 0 < getlen && getlen < (valcap - 1)) {
char *const endp = stpncpy(valstr, getstr, getlen);
*vallen = endp - valstr;
status = (*vallen < valcap);
if (status) {
*endp = '\0';
}
}
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
} else {
*vallen = 0;
}
return status;
}
bool
HttpHeader::setKeyVal(char const *const keystr, int const keylen, char const *const valstr, int const vallen, int const index)
{
if (!isValid()) {
return false;
}
bool status(false);
TSMLoc locfield(TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen));
if (nullptr != locfield) {
status = TS_SUCCESS == TSMimeHdrFieldValueStringSet(m_buffer, m_lochdr, locfield, index, valstr, vallen);
} else {
int rcode = TSMimeHdrFieldCreateNamed(m_buffer, m_lochdr, keystr, keylen, &locfield);
if (TS_SUCCESS == rcode) {
rcode = TSMimeHdrFieldValueStringSet(m_buffer, m_lochdr, locfield, index, valstr, vallen);
if (TS_SUCCESS == rcode) {
rcode = TSMimeHdrFieldAppend(m_buffer, m_lochdr, locfield);
status = (TS_SUCCESS == rcode);
}
}
}
if (nullptr != locfield) {
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
}
return status;
}
std::string
HttpHeader::toString() const
{
std::string res;
if (!isValid()) {
return "<null>";
}
TSHttpType const htype(type());
switch (htype) {
case TS_HTTP_TYPE_REQUEST: {
res.append(method());
int urllen = 0;
char *const urlstr = urlString(&urllen);
if (nullptr != urlstr) {
res.append(" ");
res.append(urlstr, urllen);
TSfree(urlstr);
} else {
res.append(" UnknownURL");
}
res.append(" HTTP/unparsed");
} break;
case TS_HTTP_TYPE_RESPONSE: {
char bufstr[1024];
/*
int const version = TSHttpHdrVersionGet(m_buffer, m_lochdr);
snprintf(bufstr, 1023, "%d ", version);
res.append(bufstr);
*/
res.append("HTTP/unparsed");
int const status = TSHttpHdrStatusGet(m_buffer, m_lochdr);
snprintf(bufstr, 1023, " %d ", status);
res.append(bufstr);
int reasonlen = 0;
char const *const hreason = reason(&reasonlen);
res.append(hreason, reasonlen);
} break;
default:
case TS_HTTP_TYPE_UNKNOWN:
res.append("UNKNOWN");
break;
}
res.append("\r\n");
int const numhdrs = TSMimeHdrFieldsCount(m_buffer, m_lochdr);
for (int indexhdr = 0; indexhdr < numhdrs; ++indexhdr) {
TSMLoc const locfield = TSMimeHdrFieldGet(m_buffer, m_lochdr, indexhdr);
int keylen = 0;
char const *const keystr = TSMimeHdrFieldNameGet(m_buffer, m_lochdr, locfield, &keylen);
res.append(keystr, keylen);
res.append(": ");
int vallen = 0;
char const *const valstr = TSMimeHdrFieldValueStringGet(m_buffer, m_lochdr, locfield, -1, &vallen);
res.append(valstr, vallen);
res.append("\r\n");
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
}
res.append("\r\n");
return res;
}
/////// HdrMgr
TSParseResult
HdrMgr::populateFrom(TSHttpParser const http_parser, TSIOBufferReader const reader, HeaderParseFunc const parsefunc,
int64_t *const bytes)
{
TSParseResult parse_res = TS_PARSE_CONT;
if (nullptr == m_buffer) {
m_buffer = TSMBufferCreate();
}
if (nullptr == m_lochdr) {
m_lochdr = TSHttpHdrCreate(m_buffer);
}
int64_t avail = TSIOBufferReaderAvail(reader);
if (0 < avail) {
TSIOBufferBlock block = TSIOBufferReaderStart(reader);
int64_t consumed = 0;
parse_res = TS_PARSE_CONT;
while (nullptr != block && 0 < avail) {
int64_t blockbytes = 0;
char const *const bstart = TSIOBufferBlockReadStart(block, reader, &blockbytes);
char const *ptr = bstart;
char const *endptr = ptr + blockbytes;
parse_res = parsefunc(http_parser, m_buffer, m_lochdr, &ptr, endptr);
int64_t const bytes_parsed(ptr - bstart);
consumed += bytes_parsed;
avail -= bytes_parsed;
if (TS_PARSE_CONT == parse_res) {
block = TSIOBufferBlockNext(block);
} else {
break;
}
}
TSIOBufferReaderConsume(reader, consumed);
if (nullptr != bytes) {
*bytes = consumed;
}
} else if (nullptr != bytes) {
*bytes = 0;
}
return parse_res;
}
|
// 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 "ui/base/test/ui_controls.h"
#include "base/callback.h"
#include "base/message_loop/message_loop.h"
#include "ui/base/test/ui_controls_internal_win.h"
#include "ui/gfx/geometry/point.h"
namespace ui_controls {
bool g_ui_controls_enabled = false;
void EnableUIControls() {
g_ui_controls_enabled = true;
}
bool SendKeyPress(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command) {
CHECK(g_ui_controls_enabled);
DCHECK(!command); // No command key on Windows
return internal::SendKeyPressImpl(window, key, control, shift, alt,
base::Closure());
}
bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
ui::KeyboardCode key,
bool control,
bool shift,
bool alt,
bool command,
const base::Closure& task) {
CHECK(g_ui_controls_enabled);
DCHECK(!command); // No command key on Windows
return internal::SendKeyPressImpl(window, key, control, shift, alt, task);
}
bool SendMouseMove(long x, long y) {
CHECK(g_ui_controls_enabled);
return internal::SendMouseMoveImpl(x, y, base::Closure());
}
bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& task) {
CHECK(g_ui_controls_enabled);
return internal::SendMouseMoveImpl(x, y, task);
}
bool SendMouseEvents(MouseButton type, int state) {
CHECK(g_ui_controls_enabled);
return internal::SendMouseEventsImpl(type, state, base::Closure());
}
bool SendMouseEventsNotifyWhenDone(MouseButton type, int state,
const base::Closure& task) {
CHECK(g_ui_controls_enabled);
return internal::SendMouseEventsImpl(type, state, task);
}
bool SendMouseClick(MouseButton type) {
CHECK(g_ui_controls_enabled);
return internal::SendMouseEventsImpl(type, UP | DOWN, base::Closure());
}
void RunClosureAfterAllPendingUIEvents(const base::Closure& closure) {
// On windows, posting UI events is synchronous so just post the closure.
base::MessageLoopForUI::current()->PostTask(FROM_HERE, closure);
}
} // namespace ui_controls
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPointSetWriterService.h"
#include "mitkIOMimeTypes.h"
#include <iostream>
#include <fstream>
#include <locale>
//
// Initialization of the xml tags.
//
const std::string mitk::PointSetWriterService::XML_POINT_SET_FILE = "point_set_file" ;
const std::string mitk::PointSetWriterService::XML_FILE_VERSION = "file_version" ;
const std::string mitk::PointSetWriterService::XML_POINT_SET = "point_set" ;
const std::string mitk::PointSetWriterService::XML_TIME_SERIES = "time_series";
const std::string mitk::PointSetWriterService::XML_TIME_SERIES_ID = "time_series_id";
const std::string mitk::PointSetWriterService::XML_POINT = "point" ;
const std::string mitk::PointSetWriterService::XML_ID = "id" ;
const std::string mitk::PointSetWriterService::XML_SPEC = "specification" ;
const std::string mitk::PointSetWriterService::XML_X = "x" ;
const std::string mitk::PointSetWriterService::XML_Y = "y" ;
const std::string mitk::PointSetWriterService::XML_Z = "z" ;
const std::string mitk::PointSetWriterService::VERSION_STRING = "0.1" ;
mitk::PointSetWriterService::PointSetWriterService()
: AbstractFileWriter(PointSet::GetStaticNameOfClass(),
CustomMimeType(IOMimeTypes::POINTSET_MIMETYPE()),
"MITK Point Set Writer")
, m_IndentDepth(0)
, m_Indent(2)
{
RegisterService();
}
mitk::PointSetWriterService::PointSetWriterService(const mitk::PointSetWriterService& other)
: AbstractFileWriter(other)
, m_IndentDepth(other.m_IndentDepth)
, m_Indent(other.m_Indent)
{
}
mitk::PointSetWriterService::~PointSetWriterService()
{}
void mitk::PointSetWriterService::Write()
{
OutputStream out(this);
if ( !out.good() )
{
mitkThrow() << "Stream not good.";
}
std::locale previousLocale(out.getloc());
std::locale I("C");
out.imbue(I);
//
// Here the actual xml writing begins
//
WriteXMLHeader( out );
WriteStartElement( XML_POINT_SET_FILE, out );
WriteStartElement( XML_FILE_VERSION, out );
out << VERSION_STRING;
WriteEndElement( XML_FILE_VERSION, out, false );
WriteXML( static_cast<const PointSet*>(this->GetInput()), out );
WriteEndElement( XML_POINT_SET_FILE, out );
out.imbue(previousLocale);
if ( !out.good() ) // some error during output
{
mitkThrow() << "Some error during point set writing.";
}
}
mitk::PointSetWriterService*mitk::PointSetWriterService::Clone() const
{
return new PointSetWriterService(*this);
}
void mitk::PointSetWriterService::WriteXML( const mitk::PointSet* pointSet, std::ostream& out )
{
WriteStartElement( XML_POINT_SET, out );
unsigned int timecount = pointSet->GetTimeSteps();
for(unsigned int i=0; i< timecount; i++)
{
WriteStartElement( XML_TIME_SERIES, out );
WriteStartElement( XML_TIME_SERIES_ID, out );
out << ConvertToString( i );
WriteEndElement( XML_TIME_SERIES_ID, out, false );
mitk::PointSet::PointsContainer* pointsContainer = pointSet->GetPointSet(i)->GetPoints();
mitk::PointSet::PointsContainer::Iterator it;
for ( it = pointsContainer->Begin(); it != pointsContainer->End(); ++it )
{
WriteStartElement( XML_POINT, out );
WriteStartElement( XML_ID, out );
out << ConvertToString( it->Index() );
WriteEndElement( XML_ID, out, false );
mitk::PointSet::PointType point = it->Value();
WriteStartElement( XML_SPEC, out );
out << ConvertToString( pointSet->GetSpecificationTypeInfo(it->Index(), i) );
WriteEndElement( XML_SPEC, out, false );
WriteStartElement( XML_X, out );
out << ConvertToString( point[ 0 ] );
WriteEndElement( XML_X, out, false );
WriteStartElement( XML_Y, out );
out << ConvertToString( point[ 1 ] );
WriteEndElement( XML_Y, out, false );
WriteStartElement( XML_Z, out );
out << ConvertToString( point[ 2 ] );
WriteEndElement( XML_Z, out, false );
WriteEndElement( XML_POINT, out );
}
WriteEndElement( XML_TIME_SERIES, out );
}
WriteEndElement( XML_POINT_SET, out );
}
template < typename T>
std::string mitk::PointSetWriterService::ConvertToString( T value )
{
std::ostringstream o;
std::locale I("C");
o.imbue(I);
if ( o << value )
{
return o.str();
}
else
{
return "conversion error";
}
}
void mitk::PointSetWriterService::WriteXMLHeader( std::ostream &file )
{
file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
}
void mitk::PointSetWriterService::WriteStartElement( const std::string& tag, std::ostream &file )
{
file << std::endl;
WriteIndent( file );
file << '<' << tag << '>';
m_IndentDepth++;
}
void mitk::PointSetWriterService::WriteEndElement( const std::string& tag, std::ostream &file, const bool& indent )
{
m_IndentDepth--;
if ( indent )
{
file << std::endl;
WriteIndent( file );
}
file << '<' << '/' << tag << '>';
}
void mitk::PointSetWriterService::WriteIndent( std::ostream& file )
{
std::string spaces( m_IndentDepth * m_Indent, ' ' );
file << spaces;
}
|
// LAME test program
//
// Copyright (c) 2010 Robert Hegemann
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
#include <lame.h>
#include <wchar.h>
#include <stdlib.h>
class PcmGenerator
{
float* m_buffer_ch0;
float* m_buffer_ch1;
int m_size;
float m_a;
float m_b;
static double random()
{
int const range_max = 32768;
int const range_min = -32767;
return (double)rand() / (RAND_MAX + 1) * (range_max - range_min) + range_min;
}
PcmGenerator( PcmGenerator const& );
PcmGenerator& operator = ( PcmGenerator const& );
public:
explicit PcmGenerator(int size)
{
m_size = size >= 0 ? size : 0;
m_buffer_ch0 = new float [m_size];
m_buffer_ch1 = new float [m_size];
m_a = 0;
m_b = 0;
advance(0);
}
~PcmGenerator()
{
delete[] m_buffer_ch0;
delete[] m_buffer_ch1;
}
float const* ch0() const { return m_buffer_ch0; }
float const* ch1() const { return m_buffer_ch1; }
void advance( int x ) {
float a = m_a;
float b = m_b;
for (int i = 0; i < m_size; ++i) {
a += 10;
if (a > 32768) a = random();
b -= 10;
if (b < -32767) b = random();
m_buffer_ch0[i] = a;
m_buffer_ch1[i] = b;
}
m_a = a;
m_b = b;
}
};
class OutFile
{
FILE* m_file_handle;
public:
OutFile()
: m_file_handle(0)
{}
explicit OutFile(wchar_t const* filename)
: m_file_handle(0)
{
m_file_handle = _wfopen(filename, L"wb");
}
~OutFile()
{
close();
}
bool isOpen() const {
return 0 != m_file_handle;
}
void close() {
if (isOpen()) {
fclose(m_file_handle);
m_file_handle = 0;
}
}
void write(unsigned char const* data, int n) {
fwrite(data, 1, n, m_file_handle);
}
};
class Lame
{
lame_t m_gf;
bool m_init_params_called;
void ensureInitialized() {
if (isOpen()) {
if (!m_init_params_called) {
m_init_params_called = true;
lame_init_params(m_gf);
}
}
}
public:
Lame()
: m_gf( lame_init() )
, m_init_params_called( false )
{}
~Lame()
{
close();
}
void close() {
if (isOpen()) {
lame_close(m_gf);
m_gf = 0;
}
}
bool isOpen() const {
return m_gf != 0;
}
operator lame_t () const {
return m_gf;
}
void setInSamplerate( int rate ) {
lame_set_in_samplerate(m_gf, rate);
}
void setOutSamplerate( int rate ) {
lame_set_out_samplerate(m_gf, rate);
}
void setNumChannels( int num_channel ) {
lame_set_num_channels(m_gf, num_channel);
}
int encode(float const* ch0, float const* ch1, int n_in, unsigned char* out_buffer, int m_out_free) {
ensureInitialized();
return lame_encode_buffer_float(m_gf, ch0, ch1, n_in, out_buffer, m_out_free);
}
int flush(unsigned char* out_buffer, int m_out_free) {
ensureInitialized();
return lame_encode_flush(m_gf, out_buffer, m_out_free);
}
int getLameTag(unsigned char* out_buffer, int m_out_free) {
ensureInitialized();
return lame_get_lametag_frame(m_gf, out_buffer, m_out_free);
}
};
class OutBuffer
{
unsigned char* m_data;
int m_size;
int m_used;
OutBuffer( OutBuffer const& );
OutBuffer& operator = ( OutBuffer const& );
public:
OutBuffer()
{
m_size = 1000 * 1000;
m_data = new unsigned char[ m_size ];
m_used = 0;
}
~OutBuffer()
{
delete[] m_data;
}
void advance( int i ) {
m_used += i;
}
int used() const {
return m_used;
}
int unused() const {
return m_size - m_used;
}
unsigned char* current() { return m_data + m_used; }
unsigned char* begin() { return m_data; }
};
void generateFile(wchar_t const* filename, size_t n)
{
int const chunk = 1152;
PcmGenerator src(chunk);
OutFile mp3_stream( filename );
if (!mp3_stream.isOpen()) return;
Lame lame;
if (!lame.isOpen()) return;
OutBuffer mp3_stream_buffer;
int rc = 0;
lame.setInSamplerate(44100);
lame.setOutSamplerate(44100);
lame.setNumChannels(2);
while (n > 0) {
int const m = n < chunk ? n : chunk;
if ( n < chunk ) n = 0; else n -= chunk;
rc = lame.encode(src.ch0(), src.ch1(), m, mp3_stream_buffer.current(), mp3_stream_buffer.unused());
wprintf(L"rc=%d %d %d\n",rc,mp3_stream_buffer.used(),mp3_stream_buffer.unused());
if (rc < 0) return;
mp3_stream_buffer.advance( rc );
src.advance(m);
}
rc = lame.flush(mp3_stream_buffer.current(), mp3_stream_buffer.unused());
wprintf(L"flush rc=%d\n",rc);
if (rc < 0) return;
mp3_stream_buffer.advance( rc );
int lametag_size = lame.getLameTag(0,0);
wprintf(L"lametag_size=%d\n",lametag_size);
rc = lame.getLameTag(mp3_stream_buffer.begin(), lametag_size);
wprintf(L"rc=%d\n",rc);
if (rc < 0) return;
mp3_stream.write(mp3_stream_buffer.begin(), mp3_stream_buffer.used());
lame.close();
}
int wmain(int argc, wchar_t** argv)
{
if (argc != 3) {
wprintf(L"usage: %ws <filename> <number pcm samples>\n", argv[0]);
return -1;
}
wprintf(L"open file %ws\n", argv[1]);
int n = _wtoi(argv[2]);
wprintf(L"synthesize %d samples long mp3 file\n",n);
generateFile(argv[1], n);
return 0;
}
|
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh_builder.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
/**
* @brief Cylinder With Texture Scene. Example demonstrating how to wrap an image image around a
* cylinder.
* @see https://www.babylonjs-playground.com/#VA2AC#3
* @see https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
*/
struct CylinderWithTextureScene : public IRenderableScene {
CylinderWithTextureScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
{
}
~CylinderWithTextureScene() override = default;
const char* getName() override
{
return "Cylinder With Texture Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
auto camera = ArcRotateCamera::New("Camera", Math::PI_2, 7.f * Math::PI / 16.f, 2.5f,
Vector3::Zero(), scene);
camera->attachControl(canvas, true);
auto light1 = HemisphericLight::New("hemiLight1", Vector3(-1.f, 10.f, -5.f), scene);
light1->intensity = 0.97f;
auto light2 = HemisphericLight::New("hemiLight2", Vector3(-10.f, -10.f, -5.f), scene);
light2->intensity = 0.97f;
auto canMaterial = StandardMaterial::New("material", scene);
canMaterial->diffuseTexture = Texture::New("textures/cannedJam.jpg", scene);
std::vector<Vector4> faceUV{
Vector4(0.f, 0.f, 0.f, 0.f), //
Vector4(1.f, 0.f, 0.32f, 1.f), //
Vector4(0.f, 0.f, 0.25f, 1.f) //
};
std::vector<Color4> faceColors{Color4(0.5, 0.5, 0.5, 1)};
CylinderOptions options;
options.height = 1.16f;
options.faceUV = std::move(faceUV);
options.faceColors = std::move(faceColors);
auto can = MeshBuilder::CreateCylinder("can", options, scene);
can->material = canMaterial;
}
}; // end of struct CylinderWithTextureScene
BABYLON_REGISTER_SAMPLE("Textures", CylinderWithTextureScene)
} // end of namespace Samples
} // end of namespace BABYLON
|
#include "_glm.h"
namespace autowig {
}
void wrapper_473db32424065b56b6f464f44bfd1500(pybind11::module& module)
{
pybind11::class_<class ::statiskit::glm::QuantitativeScalarRegressionFisherEstimation< class ::statiskit::glm::NegativeBinomialRegression, struct ::statiskit::DiscreteUnivariateConditionalDistributionEstimation >, autowig::HolderType< class ::statiskit::glm::QuantitativeScalarRegressionFisherEstimation< class ::statiskit::glm::NegativeBinomialRegression, struct ::statiskit::DiscreteUnivariateConditionalDistributionEstimation > >::Type, class ::statiskit::glm::ScalarRegressionFisherEstimation< class ::statiskit::glm::NegativeBinomialRegression, struct ::statiskit::DiscreteUnivariateConditionalDistributionEstimation > > class_473db32424065b56b6f464f44bfd1500(module, "_QuantitativeScalarRegressionFisherEstimation_473db32424065b56b6f464f44bfd1500", "");
class_473db32424065b56b6f464f44bfd1500.def(pybind11::init< >());
class_473db32424065b56b6f464f44bfd1500.def(pybind11::init< class ::statiskit::glm::NegativeBinomialRegression const *, class ::statiskit::UnivariateConditionalData const * >());
class_473db32424065b56b6f464f44bfd1500.def(pybind11::init< class ::statiskit::glm::QuantitativeScalarRegressionFisherEstimation< class ::statiskit::glm::NegativeBinomialRegression, struct ::statiskit::DiscreteUnivariateConditionalDistributionEstimation > const & >());
}
|
//------------------------------------------------------------------------------
// File: WXList.cpp
//
// Desc: DirectShow base classes - implements a non-MFC based generic list
// template class.
// Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
/* A generic list of pointers to objects.
Objectives: avoid using MFC libraries in ndm kernel mode and
provide a really useful list type.
The class is thread safe in that separate threads may add and
delete items in the list concurrently although the application
must ensure that constructor and destructor access is suitably
synchronised.
The list name must not conflict with MFC classes as an
application may use both
The nodes form a doubly linked, NULL terminated chain with an anchor
block (the list object per se) holding pointers to the first and last
nodes and a count of the nodes.
There is a node cache to reduce the allocation and freeing overhead.
It optionally (determined at construction time) has an Event which is
set whenever the list becomes non-empty and reset whenever it becomes
empty.
It optionally (determined at construction time) has a Critical Section
which is entered during the important part of each operation. (About
all you can do outside it is some parameter checking).
The node cache is a repository of nodes that are NOT in the list to speed
up storage allocation. Each list has its own cache to reduce locking and
serialising. The list accesses are serialised anyway for a given list - a
common cache would mean that we would have to separately serialise access
of all lists within the cache. Because the cache only stores nodes that are
not in the list, releasing the cache does not release any list nodes. This
means that list nodes can be copied or rechained from one list to another
without danger of creating a dangling reference if the original cache goes
away.
Questionable design decisions:
1. Retaining the warts for compatibility
2. Keeping an element count -i.e. counting whenever we do anything
instead of only when we want the count.
3. Making the chain pointers NULL terminated. If the list object
itself looks just like a node and the list is kept as a ring then
it reduces the number of special cases. All inserts look the same.
*/
#include <streams.h>
/* set cursor to the position of each element of list in turn */
#define INTERNALTRAVERSELIST(list, cursor) \
for ( cursor = (list).GetHeadPositionI() \
; cursor!=NULL \
; cursor = (list).Next(cursor) \
)
/* set cursor to the position of each element of list in turn
in reverse order
*/
#define INTERNALREVERSETRAVERSELIST(list, cursor) \
for ( cursor = (list).GetTailPositionI() \
; cursor!=NULL \
; cursor = (list).Prev(cursor) \
)
/* Constructor calls a separate initialisation function that
creates a node cache, optionally creates a lock object
and optionally creates a signaling object.
By default we create a locking object, a DEFAULTCACHE sized
cache but no event object so the list cannot be used in calls
to WaitForSingleObject
*/
CBaseList::CBaseList(__in_opt LPCTSTR pName, // Descriptive list name
INT iItems) : // Node cache size
#ifdef DEBUG
CBaseObject(pName),
#endif
m_pFirst(NULL),
m_pLast(NULL),
m_Count(0),
m_Cache(iItems)
{
} // constructor
CBaseList::CBaseList(__in_opt LPCTSTR pName) : // Descriptive list name
#ifdef DEBUG
CBaseObject(pName),
#endif
m_pFirst(NULL),
m_pLast(NULL),
m_Count(0),
m_Cache(DEFAULTCACHE)
{
} // constructor
#ifdef UNICODE
CBaseList::CBaseList(__in_opt LPCSTR pName, // Descriptive list name
INT iItems) : // Node cache size
#ifdef DEBUG
CBaseObject(pName),
#endif
m_pFirst(NULL),
m_pLast(NULL),
m_Count(0),
m_Cache(iItems)
{
} // constructor
CBaseList::CBaseList(__in_opt LPCSTR pName) : // Descriptive list name
#ifdef DEBUG
CBaseObject(pName),
#endif
m_pFirst(NULL),
m_pLast(NULL),
m_Count(0),
m_Cache(DEFAULTCACHE)
{
} // constructor
#endif
/* The destructor enumerates all the node objects in the list and
in the cache deleting each in turn. We do not do any processing
on the objects that the list holds (i.e. points to) so if they
represent interfaces for example the creator of the list should
ensure that each of them is released before deleting us
*/
CBaseList::~CBaseList()
{
/* Delete all our list nodes */
RemoveAll();
} // destructor
/* Remove all the nodes from the list but don't do anything
with the objects that each node looks after (this is the
responsibility of the creator).
Aa a last act we reset the signalling event
(if available) to indicate to clients that the list
does not have any entries in it.
*/
void CBaseList::RemoveAll()
{
/* Free up all the CNode objects NOTE we don't bother putting the
deleted nodes into the cache as this method is only really called
in serious times of change such as when we are being deleted at
which point the cache will be deleted anway */
CNode* pn = m_pFirst;
while (pn)
{
CNode* op = pn;
pn = pn->Next();
delete op;
}
/* Reset the object count and the list pointers */
m_Count = 0;
m_pFirst = m_pLast = NULL;
} // RemoveAll
/* Return a position enumerator for the entire list.
A position enumerator is a pointer to a node object cast to a
transparent type so all we do is return the head/tail node
pointer in the list.
WARNING because the position is a pointer to a node there is
an implicit assumption for users a the list class that after
deleting an object from the list that any other position
enumerators that you have may be invalid (since the node
may be gone).
*/
__out_opt POSITION CBaseList::GetHeadPositionI() const
{
return (POSITION) m_pFirst;
} // GetHeadPosition
__out_opt POSITION CBaseList::GetTailPositionI() const
{
return (POSITION) m_pLast;
} // GetTailPosition
/* Get the number of objects in the list,
Get the lock before accessing the count.
Locking may not be entirely necessary but it has the side effect
of making sure that all operations are complete before we get it.
So for example if a list is being added to this list then that
will have completed in full before we continue rather than seeing
an intermediate albeit valid state
*/
int CBaseList::GetCountI() const
{
return m_Count;
} // GetCount
/* Return the object at rp, update rp to the next object from
the list or NULL if you have moved over the last object.
You may still call this function once we return NULL but
we will continue to return a NULL position value
*/
__out void* CBaseList::GetNextI(__inout POSITION& rp) const
{
/* have we reached the end of the list */
if (rp == NULL)
{
return NULL;
}
/* Lock the object before continuing */
void* pObject;
/* Copy the original position then step on */
CNode* pn = (CNode*) rp;
ASSERT(pn != NULL);
rp = (POSITION) pn->Next();
/* Get the object at the original position from the list */
pObject = pn->GetData();
// ASSERT(pObject != NULL); // NULL pointers in the list are allowed.
return pObject;
} //GetNext
/* Return the object at p.
Asking for the object at NULL ASSERTs then returns NULL
The object is NOT locked. The list is not being changed
in any way. If another thread is busy deleting the object
then locking would only result in a change from one bad
behaviour to another.
*/
__out_opt void* CBaseList::GetI(__in_opt POSITION p) const
{
if (p == NULL)
{
return NULL;
}
CNode* pn = (CNode*) p;
void* pObject = pn->GetData();
// ASSERT(pObject != NULL); // NULL pointers in the list are allowed.
return pObject;
} //Get
__out void* CBaseList::GetValidI(__in POSITION p) const
{
CNode* pn = (CNode*) p;
void* pObject = pn->GetData();
// ASSERT(pObject != NULL); // NULL pointers in the list are allowed.
return pObject;
} //Get
/* Return the first position in the list which holds the given pointer.
Return NULL if it's not found.
*/
__out_opt POSITION CBaseList::FindI( __in void* pObj) const
{
POSITION pn;
INTERNALTRAVERSELIST(*this, pn)
{
if (GetI(pn)==pObj)
{
return pn;
}
}
return NULL;
} // Find
/* Remove the first node in the list (deletes the pointer to its object
from the list, does not free the object itself).
Return the pointer to its object or NULL if empty
*/
__out_opt void* CBaseList::RemoveHeadI()
{
/* All we do is get the head position and ask for that to be deleted.
We could special case this since some of the code path checking
in Remove() is redundant as we know there is no previous
node for example but it seems to gain little over the
added complexity
*/
return RemoveI((POSITION)m_pFirst);
} // RemoveHead
/* Remove the last node in the list (deletes the pointer to its object
from the list, does not free the object itself).
Return the pointer to its object or NULL if empty
*/
__out_opt void* CBaseList::RemoveTailI()
{
/* All we do is get the tail position and ask for that to be deleted.
We could special case this since some of the code path checking
in Remove() is redundant as we know there is no previous
node for example but it seems to gain little over the
added complexity
*/
return RemoveI((POSITION)m_pLast);
} // RemoveTail
/* Remove the pointer to the object in this position from the list.
Deal with all the chain pointers
Return a pointer to the object removed from the list.
The node object that is freed as a result
of this operation is added to the node cache where
it can be used again.
Remove(NULL) is a harmless no-op - but probably is a wart.
*/
__out_opt void* CBaseList::RemoveI(__in_opt POSITION pos)
{
/* Lock the critical section before continuing */
// ASSERT (pos!=NULL); // Removing NULL is to be harmless!
if (pos==NULL) return NULL;
CNode* pCurrent = (CNode*) pos;
ASSERT(pCurrent != NULL);
/* Update the previous node */
CNode* pNode = pCurrent->Prev();
if (pNode == NULL)
{
m_pFirst = pCurrent->Next();
}
else
{
pNode->SetNext(pCurrent->Next());
}
/* Update the following node */
pNode = pCurrent->Next();
if (pNode == NULL)
{
m_pLast = pCurrent->Prev();
}
else
{
pNode->SetPrev(pCurrent->Prev());
}
/* Get the object this node was looking after */
void* pObject = pCurrent->GetData();
// ASSERT(pObject != NULL); // NULL pointers in the list are allowed.
/* Try and add the node object to the cache -
a NULL return code from the cache means we ran out of room.
The cache size is fixed by a constructor argument when the
list is created and defaults to DEFAULTCACHE.
This means that the cache will have room for this many
node objects. So if you have a list of media samples
and you know there will never be more than five active at
any given time of them for example then override the default
constructor
*/
m_Cache.AddToCache(pCurrent);
/* If the list is empty then reset the list event */
--m_Count;
ASSERT(m_Count >= 0);
return pObject;
} // Remove
/* Add this object to the tail end of our list
Return the new tail position.
*/
__out_opt POSITION CBaseList::AddTailI(__in void* pObject)
{
/* Lock the critical section before continuing */
CNode* pNode;
// ASSERT(pObject); // NULL pointers in the list are allowed.
/* If there is a node objects in the cache then use
that otherwise we will have to create a new one */
pNode = (CNode*) m_Cache.RemoveFromCache();
if (pNode == NULL)
{
pNode = new CNode;
}
/* Check we have a valid object */
if (pNode == NULL)
{
return NULL;
}
/* Initialise all the CNode object
just in case it came from the cache
*/
pNode->SetData(pObject);
pNode->SetNext(NULL);
pNode->SetPrev(m_pLast);
if (m_pLast == NULL)
{
m_pFirst = pNode;
}
else
{
m_pLast->SetNext(pNode);
}
/* Set the new last node pointer and also increment the number
of list entries, the critical section is unlocked when we
exit the function
*/
m_pLast = pNode;
++m_Count;
return (POSITION) pNode;
} // AddTail(object)
/* Add this object to the head end of our list
Return the new head position.
*/
__out_opt POSITION CBaseList::AddHeadI(__in void* pObject)
{
CNode* pNode;
// ASSERT(pObject); // NULL pointers in the list are allowed.
/* If there is a node objects in the cache then use
that otherwise we will have to create a new one */
pNode = (CNode*) m_Cache.RemoveFromCache();
if (pNode == NULL)
{
pNode = new CNode;
}
/* Check we have a valid object */
if (pNode == NULL)
{
return NULL;
}
/* Initialise all the CNode object
just in case it came from the cache
*/
pNode->SetData(pObject);
/* chain it in (set four pointers) */
pNode->SetPrev(NULL);
pNode->SetNext(m_pFirst);
if (m_pFirst == NULL)
{
m_pLast = pNode;
}
else
{
m_pFirst->SetPrev(pNode);
}
m_pFirst = pNode;
++m_Count;
return (POSITION) pNode;
} // AddHead(object)
/* Add all the elements in *pList to the tail of this list.
Return TRUE if it all worked, FALSE if it didn't.
If it fails some elements may have been added.
*/
BOOL CBaseList::AddTail(__in CBaseList* pList)
{
/* lock the object before starting then enumerate
each entry in the source list and add them one by one to
our list (while still holding the object lock)
Lock the other list too.
*/
POSITION pos = pList->GetHeadPositionI();
while (pos)
{
if (NULL == AddTailI(pList->GetNextI(pos)))
{
return FALSE;
}
}
return TRUE;
} // AddTail(list)
/* Add all the elements in *pList to the head of this list.
Return TRUE if it all worked, FALSE if it didn't.
If it fails some elements may have been added.
*/
BOOL CBaseList::AddHead(__in CBaseList* pList)
{
/* lock the object before starting then enumerate
each entry in the source list and add them one by one to
our list (while still holding the object lock)
Lock the other list too.
To avoid reversing the list, traverse it backwards.
*/
POSITION pos;
INTERNALREVERSETRAVERSELIST(*pList, pos)
{
if (NULL== AddHeadI(pList->GetValidI(pos)))
{
return FALSE;
}
}
return TRUE;
} // AddHead(list)
/* Add the object after position p
p is still valid after the operation.
AddAfter(NULL,x) adds x to the start - same as AddHead
Return the position of the new object, NULL if it failed
*/
__out_opt POSITION CBaseList::AddAfterI(__in_opt POSITION pos, __in void* pObj)
{
if (pos==NULL)
return AddHeadI(pObj);
/* As someone else might be furkling with the list -
Lock the critical section before continuing
*/
CNode* pAfter = (CNode*) pos;
ASSERT(pAfter != NULL);
if (pAfter==m_pLast)
return AddTailI(pObj);
/* set pnode to point to a new node, preferably from the cache */
CNode* pNode = (CNode*) m_Cache.RemoveFromCache();
if (pNode == NULL)
{
pNode = new CNode;
}
/* Check we have a valid object */
if (pNode == NULL)
{
return NULL;
}
/* Initialise all the CNode object
just in case it came from the cache
*/
pNode->SetData(pObj);
/* It is to be added to the middle of the list - there is a before
and after node. Chain it after pAfter, before pBefore.
*/
CNode* pBefore = pAfter->Next();
ASSERT(pBefore != NULL);
/* chain it in (set four pointers) */
pNode->SetPrev(pAfter);
pNode->SetNext(pBefore);
pBefore->SetPrev(pNode);
pAfter->SetNext(pNode);
++m_Count;
return (POSITION) pNode;
} // AddAfter(object)
BOOL CBaseList::AddAfter(__in_opt POSITION p, __in CBaseList* pList)
{
POSITION pos;
INTERNALTRAVERSELIST(*pList, pos)
{
/* p follows along the elements being added */
p = AddAfterI(p, pList->GetValidI(pos));
if (p==NULL) return FALSE;
}
return TRUE;
} // AddAfter(list)
/* Mirror images:
Add the element or list after position p.
p is still valid after the operation.
AddBefore(NULL,x) adds x to the end - same as AddTail
*/
__out_opt POSITION CBaseList::AddBeforeI(__in_opt POSITION pos, __in void* pObj)
{
if (pos==NULL)
return AddTailI(pObj);
/* set pnode to point to a new node, preferably from the cache */
CNode* pBefore = (CNode*) pos;
ASSERT(pBefore != NULL);
if (pBefore==m_pFirst)
return AddHeadI(pObj);
CNode* pNode = (CNode*) m_Cache.RemoveFromCache();
if (pNode == NULL)
{
pNode = new CNode;
}
/* Check we have a valid object */
if (pNode == NULL)
{
return NULL;
}
/* Initialise all the CNode object
just in case it came from the cache
*/
pNode->SetData(pObj);
/* It is to be added to the middle of the list - there is a before
and after node. Chain it after pAfter, before pBefore.
*/
CNode* pAfter = pBefore->Prev();
ASSERT(pAfter != NULL);
/* chain it in (set four pointers) */
pNode->SetPrev(pAfter);
pNode->SetNext(pBefore);
pBefore->SetPrev(pNode);
pAfter->SetNext(pNode);
++m_Count;
return (POSITION) pNode;
} // Addbefore(object)
BOOL CBaseList::AddBefore(__in_opt POSITION p, __in CBaseList* pList)
{
POSITION pos;
INTERNALREVERSETRAVERSELIST(*pList, pos)
{
/* p follows along the elements being added */
p = AddBeforeI(p, pList->GetValidI(pos));
if (p==NULL) return FALSE;
}
return TRUE;
} // AddBefore(list)
/* Split *this after position p in *this
Retain as *this the tail portion of the original *this
Add the head portion to the tail end of *pList
Return TRUE if it all worked, FALSE if it didn't.
e.g.
foo->MoveToTail(foo->GetHeadPosition(), bar);
moves one element from the head of foo to the tail of bar
foo->MoveToTail(NULL, bar);
is a no-op
foo->MoveToTail(foo->GetTailPosition, bar);
concatenates foo onto the end of bar and empties foo.
A better, except excessively long name might be
MoveElementsFromHeadThroughPositionToOtherTail
*/
BOOL CBaseList::MoveToTail
(__in_opt POSITION pos, __in CBaseList* pList)
{
/* Algorithm:
Note that the elements (including their order) in the concatenation
of *pList to the head of *this is invariant.
1. Count elements to be moved
2. Join *pList onto the head of this to make one long chain
3. Set first/Last pointers in *this and *pList
4. Break the chain at the new place
5. Adjust counts
6. Set/Reset any events
*/
if (pos==NULL) return TRUE; // no-op. Eliminates special cases later.
/* Make cMove the number of nodes to move */
CNode* p = (CNode*)pos;
int cMove = 0; // number of nodes to move
while(p!=NULL)
{
p = p->Prev();
++cMove;
}
/* Join the two chains together */
if (pList->m_pLast!=NULL)
pList->m_pLast->SetNext(m_pFirst);
if (m_pFirst!=NULL)
m_pFirst->SetPrev(pList->m_pLast);
/* set first and last pointers */
p = (CNode*)pos;
if (pList->m_pFirst==NULL)
pList->m_pFirst = m_pFirst;
m_pFirst = p->Next();
if (m_pFirst==NULL)
m_pLast = NULL;
pList->m_pLast = p;
/* Break the chain after p to create the new pieces */
if (m_pFirst!=NULL)
m_pFirst->SetPrev(NULL);
p->SetNext(NULL);
/* Adjust the counts */
m_Count -= cMove;
pList->m_Count += cMove;
return TRUE;
} // MoveToTail
/* Mirror image of MoveToTail:
Split *this before position p in *this.
Retain in *this the head portion of the original *this
Add the tail portion to the start (i.e. head) of *pList
Return TRUE if it all worked, FALSE if it didn't.
e.g.
foo->MoveToHead(foo->GetTailPosition(), bar);
moves one element from the tail of foo to the head of bar
foo->MoveToHead(NULL, bar);
is a no-op
foo->MoveToHead(foo->GetHeadPosition, bar);
concatenates foo onto the start of bar and empties foo.
*/
BOOL CBaseList::MoveToHead
(__in_opt POSITION pos, __in CBaseList* pList)
{
/* See the comments on the algorithm in MoveToTail */
if (pos==NULL) return TRUE; // no-op. Eliminates special cases later.
/* Make cMove the number of nodes to move */
CNode* p = (CNode*)pos;
int cMove = 0; // number of nodes to move
while(p!=NULL)
{
p = p->Next();
++cMove;
}
/* Join the two chains together */
if (pList->m_pFirst!=NULL)
pList->m_pFirst->SetPrev(m_pLast);
if (m_pLast!=NULL)
m_pLast->SetNext(pList->m_pFirst);
/* set first and last pointers */
p = (CNode*)pos;
if (pList->m_pLast==NULL)
pList->m_pLast = m_pLast;
m_pLast = p->Prev();
if (m_pLast==NULL)
m_pFirst = NULL;
pList->m_pFirst = p;
/* Break the chain after p to create the new pieces */
if (m_pLast!=NULL)
m_pLast->SetNext(NULL);
p->SetPrev(NULL);
/* Adjust the counts */
m_Count -= cMove;
pList->m_Count += cMove;
return TRUE;
} // MoveToHead
/* Reverse the order of the [pointers to] objects in *this
*/
void CBaseList::Reverse()
{
/* algorithm:
The obvious booby trap is that you flip pointers around and lose
addressability to the node that you are going to process next.
The easy way to avoid this is do do one chain at a time.
Run along the forward chain,
For each node, set the reverse pointer to the one ahead of us.
The reverse chain is now a copy of the old forward chain, including
the NULL termination.
Run along the reverse chain (i.e. old forward chain again)
For each node set the forward pointer of the node ahead to point back
to the one we're standing on.
The first node needs special treatment,
it's new forward pointer is NULL.
Finally set the First/Last pointers
*/
CNode* p;
// Yes we COULD use a traverse, but it would look funny!
p = m_pFirst;
while (p!=NULL)
{
CNode* q;
q = p->Next();
p->SetNext(p->Prev());
p->SetPrev(q);
p = q;
}
p = m_pFirst;
m_pFirst = m_pLast;
m_pLast = p;
#if 0 // old version
if (m_pFirst==NULL) return; // empty list
if (m_pFirst->Next()==NULL) return; // single node list
/* run along forward chain */
for ( p = m_pFirst
; p!=NULL
; p = p->Next()
)
{
p->SetPrev(p->Next());
}
/* special case first element */
m_pFirst->SetNext(NULL); // fix the old first element
/* run along new reverse chain i.e. old forward chain again */
for ( p = m_pFirst // start at the old first element
; p->Prev()!=NULL // while there's a node still to be set
; p = p->Prev() // work in the same direction as before
)
{
p->Prev()->SetNext(p);
}
/* fix forward and reverse pointers
- the triple XOR swap would work but all the casts look hideous */
p = m_pFirst;
m_pFirst = m_pLast;
m_pLast = p;
#endif
} // Reverse
|
// [WriteFile Name=SearchDictionarySymbolStyle, Category=Search]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "SearchDictionarySymbolStyle.h"
#include "DictionarySymbolStyle.h"
#include <QQmlProperty>
using namespace Esri::ArcGISRuntime;
SearchDictionarySymbolStyle::SearchDictionarySymbolStyle(QQuickItem* parent) :
QQuickItem(parent),
m_dictionarySymbolStyle(nullptr),
m_searchResults(nullptr)
{
}
SearchDictionarySymbolStyle::~SearchDictionarySymbolStyle()
{
}
void SearchDictionarySymbolStyle::init()
{
qmlRegisterType<SearchDictionarySymbolStyle>("Esri.Samples", 1, 0, "SearchDictionarySymbolStyleSample");
qmlRegisterUncreatableType<QAbstractListModel>("Esri.Samples", 1, 0, "AbstractListModel", "AbstractListModel is uncreateable");
}
void SearchDictionarySymbolStyle::componentComplete()
{
QQuickItem::componentComplete();
//Get the data path
QString datapath = QQmlProperty::read(this, "dataPath").toUrl().toLocalFile();
//Create the dictionary from datapath
m_dictionarySymbolStyle = new DictionarySymbolStyle("mil2525d", datapath, this);
//Connect to the search completed signal of the dictionary
connect(m_dictionarySymbolStyle, &DictionarySymbolStyle::searchSymbolsCompleted, this, [this](QUuid, SymbolStyleSearchResultListModel* results)
{
m_searchResults = results;
emit searchResultsListModelChanged();
emit searchCompleted(results->size());
});
}
QAbstractListModel* SearchDictionarySymbolStyle::searchResultsListModel() const
{
return m_searchResults;
}
void SearchDictionarySymbolStyle::search(const QStringList& namesSearchParam, const QStringList& tagsSearchParam,
const QStringList& classesSearchParam,const QStringList& categoriesSearchParam,
const QStringList& keysSearchParam)
{
//Create search parameters and search with the parameters
SymbolStyleSearchParameters searchParameters;
searchParameters.setCategories(categoriesSearchParam);
searchParameters.setKeys(keysSearchParam);
searchParameters.setNames(namesSearchParam);
searchParameters.setSymbolClasses(classesSearchParam);
searchParameters.setTags(tagsSearchParam);
m_dictionarySymbolStyle->searchSymbols(searchParameters);
}
|
//============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2016 by Bradford W. Mott, Stephen Anthony
// and the Stella Team
//
// See the file "License.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: Cart3EPlus.hxx 3316 2016-08-24 23:57:07Z stephena $
//============================================================================
#ifndef CARTRIDGE_3EPLUS_HXX
#define CARTRIDGE_3EPLUS_HXX
class System;
#include "bspf.hxx"
#include "Cart.hxx"
#ifdef DEBUGGER_SUPPORT
class Cartridge3EPlusWidget;
#include "Cart3EPlusWidget.hxx"
#endif
/**
Cartridge class from Thomas Jentzsch, mostly based on the 'DASH' scheme
with the following changes:
RAM areas:
- read $x000, write $x200
- read $x400, write $x600
- read $x800, write $xa00
- read $xc00, write $xe00
@author Thomas Jentzsch and Stephen Anthony
*/
class Cartridge3EPlus : public Cartridge
{
friend class Cartridge3EPlusWidget;
public:
/**
Create a new cartridge using the specified image and size
@param image Pointer to the ROM image
@param size The size of the ROM image
@param settings A reference to the various settings (read-only)
*/
Cartridge3EPlus(const uInt8* image, uInt32 size, const Settings& settings);
virtual ~Cartridge3EPlus() = default;
public:
/** Reset device to its power-on state */
void reset() override;
/**
Install cartridge in the specified system. Invoked by the system
when the cartridge is attached to it.
@param system The system the device should install itself in
*/
void install(System& system) override;
/**
Patch the cartridge ROM.
@param address The ROM address to patch
@param value The value to place into the address
@return Success or failure of the patch operation
*/
bool patch(uInt16 address, uInt8 value) override;
/**
Access the internal ROM image for this cartridge.
@param size Set to the size of the internal ROM image data
@return A pointer to the internal ROM image data
*/
const uInt8* getImage(int& size) const override;
/**
Save the current state of this cart to the given Serializer.
@param out The Serializer object to use
@return False on any errors, else true
*/
bool save(Serializer& out) const override;
/**
Load the current state of this cart from the given Serializer.
@param in The Serializer object to use
@return False on any errors, else true
*/
bool load(Serializer& in) override;
/**
Get a descriptor for the device name (used in error checking).
@return The name of the object
*/
string name() const override { return "Cartridge3E+"; }
#ifdef DEBUGGER_SUPPORT
/**
Get debugger widget responsible for accessing the inner workings
of the cart.
*/
CartDebugWidget* debugWidget(GuiObject* boss, const GUI::Font& lfont,
const GUI::Font& nfont, int x, int y, int w, int h) override
{
return new Cartridge3EPlusWidget(boss, lfont, nfont, x, y, w, h, *this);
}
#endif
public:
/**
Get the byte at the specified address
@return The byte at the specified address
*/
uInt8 peek(uInt16 address) override;
/**
Change the byte at the specified address to the given value
@param address The address where the value should be stored
@param value The value to be stored at the address
@return True if the poke changed the device address space, else false
*/
bool poke(uInt16 address, uInt8 value) override;
private:
bool bankRAM(uInt8 bank); // switch a RAM bank
bool bankROM(uInt8 bank); // switch a ROM bank
void bankRAMSlot(uInt16 bank); // switch in a 512b RAM slot (lower or upper 1/2 bank)
void bankROMSlot(uInt16 bank); // switch in a 512b RAM slot (read or write port)
void initializeBankState(); // set all banks according to current bankInUse state
// We have an array that indicates for each of the 8 512 byte areas of the address space, which ROM/RAM
// bank is used in that area. ROM switches 1K so occupies 2 successive entries for each switch. RAM occupies
// two as well, one 512 byte for read and one for write. The RAM locations are +0x800 apart, and the ROM
// are consecutive. This allows us to determine on a read/write exactly where the data is.
static constexpr uInt16 BANK_UNDEFINED = 0x8000; // bank is undefined and inaccessible
uInt16 bankInUse[8]; // bank being used for ROM/RAM (eight 512 byte areas)
static constexpr uInt16 BANK_SWITCH_HOTSPOT_RAM = 0x3E; // writes to this address cause bankswitching
static constexpr uInt16 BANK_SWITCH_HOTSPOT_ROM = 0x3F; // writes to this address cause bankswitching
static constexpr uInt8 BANK_BITS = 6; // # bits for bank
static constexpr uInt8 BIT_BANK_MASK = (1 << BANK_BITS) - 1; // mask for those bits
static constexpr uInt16 BITMASK_LOWERUPPER = 0x100; // flags lower or upper section of bank (1==upper)
static constexpr uInt16 BITMASK_ROMRAM = 0x200; // flags ROM or RAM bank switching (1==RAM)
static constexpr uInt16 MAXIMUM_BANK_COUNT = (1 << BANK_BITS);
static constexpr uInt16 RAM_BANK_TO_POWER = 9; // 2^n = 512
static constexpr uInt16 RAM_BANK_SIZE = (1 << RAM_BANK_TO_POWER);
static constexpr uInt16 BITMASK_RAM_BANK = (RAM_BANK_SIZE - 1);
static constexpr uInt32 RAM_TOTAL_SIZE = MAXIMUM_BANK_COUNT * RAM_BANK_SIZE;
static constexpr uInt16 ROM_BANK_TO_POWER = 10; // 2^n = 1024
static constexpr uInt16 ROM_BANK_SIZE = (1 << ROM_BANK_TO_POWER);
static constexpr uInt16 BITMASK_ROM_BANK = (ROM_BANK_SIZE - 1);
static constexpr uInt16 ROM_BANK_COUNT = 64;
static constexpr uInt16 RAM_WRITE_OFFSET = 0x200;
BytePtr myImage; // Pointer to a dynamically allocated ROM image of the cartridge
uInt32 mySize; // Size of the ROM image
uInt8 myRAM[RAM_TOTAL_SIZE];
private:
// Following constructors and assignment operators not supported
Cartridge3EPlus() = delete;
Cartridge3EPlus(const Cartridge3EPlus&) = delete;
Cartridge3EPlus(Cartridge3EPlus&&) = delete;
Cartridge3EPlus& operator=(const Cartridge3EPlus&) = delete;
Cartridge3EPlus& operator=(Cartridge3EPlus&&) = delete;
};
#endif
|
/* -------------------------------------------------------------------------- *
* OpenSim: InverseDynamicsSolver.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Ajay Seth *
* *
* 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 "InverseDynamicsSolver.h"
#include "Model/Model.h"
#include <OpenSim/Common/FunctionSet.h>
using namespace std;
using namespace SimTK;
namespace OpenSim {
//______________________________________________________________________________
/**
* An implementation of the InverseDynamicsSolver
*
* @param model to assemble
*/
InverseDynamicsSolver::InverseDynamicsSolver(const Model &model) : Solver(model)
{
setAuthors("Ajay Seth");
}
/** Solve the inverse dynamics system of equations for generalized coordinate forces, Tau.
Applied loads are computed by the model from the state. */
Vector InverseDynamicsSolver::solve(const SimTK::State &s, const SimTK::Vector &udot)
{
// Default is a statics inverse dynamics analysis, udot = 0;
Vector knownUdots(getModel().getNumSpeeds(), 0.0);
// If valid accelerations provided then use for inverse dynamics
if(udot.size() == getModel().getNumSpeeds()){
knownUdots = udot;
}
else if (udot.size() != 0){
throw Exception("InverseDynamicsSolver::solve with input 'udot' of invalid size.");
}
// Realize to dynamics stage so that all model forces are computed
getModel().getMultibodySystem().realize(s,SimTK::Stage::Dynamics);
// Get applied mobility (generalized) forces generated by components of the model, like actuators
const Vector &appliedMobilityForces = getModel().getMultibodySystem().getMobilityForces(s, Stage::Dynamics);
// Get all applied body forces like those from contact
const Vector_<SpatialVec>& appliedBodyForces = getModel().getMultibodySystem().getRigidBodyForces(s, Stage::Dynamics);
// Perform general inverse dynamics
return solve(s, knownUdots, appliedMobilityForces, appliedBodyForces);
}
/** Solve the inverse dynamics system of equations for generalized coordinate forces, Tau.
Applied loads are explicitly provided as generalized coordinate forces (MobilityForces)
and/or a Vector of Spatial-body forces */
Vector InverseDynamicsSolver::solve(const SimTK::State &s, const SimTK::Vector &udot,
const SimTK::Vector &appliedMobilityForces, const SimTK::Vector_<SimTK::SpatialVec>& appliedBodyForces)
{
//Results of the inverse dynamics for the generalized forces to satisfy accelerations
Vector residualMobilityForces;
if(s.getSystemStage() < SimTK::Stage::Dynamics)
getModel().getMultibodySystem().realize(s,SimTK::Stage::Dynamics);
// Perform inverse dynamics
getModel().getMultibodySystem().getMatterSubsystem().calcResidualForceIgnoringConstraints(s,
appliedMobilityForces, appliedBodyForces, udot, residualMobilityForces);
return residualMobilityForces;
}
/** Solve the inverse dynamics system of equations for generalized coordinate forces, Tau.
Now the state is not given, but is constructed from known coordinates, q as functions of time.
Coordinate functions must be twice differentiable.
NOTE: state dependent forces and other applied loads are NOT computed since these may depend on
state variables (like muscle fiber lengths) that are not known */
Vector InverseDynamicsSolver::solve(SimTK::State &s, const FunctionSet &Qs, double time)
{
int nq = getModel().getNumCoordinates();
if(Qs.getSize() != nq){
throw Exception("InverseDynamicsSolver::solve invalid number of q functions.");
}
if( nq != getModel().getNumSpeeds()){
throw Exception("InverseDynamicsSolver::solve using FunctionSet, nq != nu not supported.");
}
// update the State so we get the correct gravity and Coriolis effects
// direct references into the state so no allocation required
s.updTime() = time;
Vector &q = s.updQ();
Vector &u = s.updU();
Vector &udot = s.updUDot();
for(int i=0; i<nq; i++){
q[i] = Qs.evaluate(i, 0, time);
u[i] = Qs.evaluate(i, 1, time);
udot[i] = Qs.evaluate(i, 2, time);
}
// Perform general inverse dynamics
return solve(s, udot);
}
/** Same as above but for a given time series */
void InverseDynamicsSolver::solve(SimTK::State &s, const FunctionSet &Qs, const Array_<double> ×, Array_<Vector> &genForceTrajectory)
{
int nq = getModel().getNumCoordinates();
int nt = times.size();
//Preallocate if not done already
genForceTrajectory.resize(nt, Vector(nq));
AnalysisSet& analysisSet = const_cast<AnalysisSet&>(getModel().getAnalysisSet());
//fill in results for each time
for(int i=0; i<nt; i++){
genForceTrajectory[i] = solve(s, Qs, times[i]);
analysisSet.step(s, i);
}
}
} // end of namespace OpenSim
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "display_random_state");
bool valid = false;
bool invalid = false;
for (int i = 0; i < argc; ++i)
{
if (strcmp(argv[i], "--valid") == 0)
{
valid = true;
break;
}
if (strcmp(argv[i], "--invalid") == 0)
{
invalid = true;
break;
}
}
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
robot_model_loader::RobotModelLoader::Options opt;
opt.robot_description_ = "robot_description";
robot_model_loader::RobotModelLoaderPtr rml(new robot_model_loader::RobotModelLoader(opt));
planning_scene_monitor::PlanningSceneMonitor psm(rml);
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
ros::Publisher pub_scene = nh.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
ros::Duration(0.5).sleep();
do
{
if (!psm.getPlanningScene())
{
ROS_ERROR("Planning scene did not load properly, exiting...");
break;
}
std::cout << "Type a number and hit Enter. That number of ";
if (valid)
std::cout << "valid ";
else if (invalid)
std::cout << "invalid ";
std::cout << "states will be randomly generated at an interval of one second and published as a planning scene."
<< std::endl;
std::size_t n;
std::cin >> n;
for (std::size_t i = 0; i < n; ++i)
{
if (valid)
{
bool found = false;
unsigned int attempts = 0;
do
{
attempts++;
psm.getPlanningScene()->getCurrentStateNonConst().setToRandomPositions();
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
psm.getPlanningScene()->checkCollision(req, res);
found = !res.collision;
} while (!found && attempts < 100);
if (!found)
{
std::cout << "Unable to find valid state" << std::endl;
continue;
}
}
else if (invalid)
{
bool found = false;
unsigned int attempts = 0;
do
{
attempts++;
psm.getPlanningScene()->getCurrentStateNonConst().setToRandomPositions();
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
psm.getPlanningScene()->checkCollision(req, res);
found = res.collision;
} while (!found && attempts < 100);
if (!found)
{
std::cout << "Unable to find invalid state" << std::endl;
continue;
}
}
else
psm.getPlanningScene()->getCurrentStateNonConst().setToRandomPositions();
moveit_msgs::PlanningScene psmsg;
psm.getPlanningScene()->getPlanningSceneMsg(psmsg);
pub_scene.publish(psmsg);
std::cout << psm.getPlanningScene()->getCurrentState() << std::endl;
sleep(1);
}
} while (nh.ok());
ros::shutdown();
return 0;
}
|
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google 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 "v8.h"
#include "platform.h"
#include "cctest.h"
TEST(Preemption) {
v8::Locker locker;
v8::V8::Initialize();
v8::HandleScope scope;
v8::Context::Scope context_scope(v8::Context::New());
v8::Locker::StartPreemption(100);
v8::Handle<v8::Script> script = v8::Script::Compile(
v8::String::New("var count = 0; var obj = new Object(); count++;\n"));
script->Run();
v8::Locker::StopPreemption();
v8::internal::OS::Sleep(500); // Make sure the timer fires.
script->Run();
}
|
/* Copyright © 2017-2020 ABBYY Production 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 <common.h>
#pragma hdrstop
#include <CpuMathEngine.h>
#include <MathEngineDeviceStackAllocator.h>
#include <MathEngineHostStackAllocator.h>
#include <MemoryHandleInternal.h>
#include <MathEngineCommon.h>
#include <NeoMathEngine/SimdMathEngine.h>
#include <DllLoader.h>
#include <CPUInfo.h>
#if FINE_PLATFORM( FINE_ANDROID ) || FINE_PLATFORM( FINE_LINUX )
#include <PerformanceCountersCpuLinux.h>
#elif FINE_PLATFORM( FINE_WINDOWS ) || FINE_PLATFORM( FINE_DARWIN ) || FINE_PLATFORM( FINE_IOS )
#include <PerformanceCountersDefault.h>
#else
#error "Platform is not supported!";
#endif
#ifdef NEOML_USE_MKL
#if FINE_PLATFORM( FINE_WINDOWS ) || FINE_PLATFORM( FINE_LINUX ) || FINE_PLATFORM( FINE_DARWIN )
#include <mkl.h>
#else
#error Unknown platform
#endif
#endif // NEOML_USE_MKL
namespace NeoML {
static int FloatAlignment = CCPUInfo::DefineFloatAlignment();
static CCPUInfo::TCpuArch CPUArch = CCPUInfo::GetCpuArch();
CCpuMathEngine::CCpuMathEngine( int _threadCount, size_t _memoryLimit ) :
threadCount( _threadCount <= 0 ? OmpGetMaxThreadCount() : _threadCount ),
floatAlignment( FloatAlignment ),
memoryAlignment( floatAlignment * sizeof(float) ),
memoryPool( new CMemoryPool( _memoryLimit == 0 ? SIZE_MAX : _memoryLimit, this, false ) ),
stackAllocator( new CDeviceStackAllocator( *memoryPool, memoryAlignment ) ),
dllLoader( CDllLoader::AVX_DLL ),
simdMathEngine( nullptr ),
customSgemmFunction( nullptr )
{
#ifdef NEOML_USE_AVX
if( dllLoader.IsLoaded( CDllLoader::AVX_DLL ) ) {
simdMathEngine = unique_ptr<ISimdMathEngine>( CDllLoader::avxDll->CreateSimdMathEngine( this, threadCount ) );
// Don't use custom sgemm function when we are compiled with MKL and when we are on Intel CPU.
if( CPUArch == CCPUInfo::TCpuArch::Intel ) {
#ifndef NEOML_USE_MKL
customSgemmFunction = simdMathEngine->GetSgemmFunction();
#endif
} else {
// Non Intel architectures
customSgemmFunction = simdMathEngine->GetSgemmFunction();
}
}
#else // NEOML_USE_AVX
// warning fix
(void)customSgemmFunction;
#endif
#ifdef NEOML_USE_MKL
vmlSetMode( VML_ERRMODE_NOERR );
#endif
}
CCpuMathEngine::~CCpuMathEngine()
{
CleanUp();
}
void CCpuMathEngine::SetReuseMemoryMode( bool enable )
{
std::lock_guard<std::mutex> lock( mutex );
memoryPool->SetReuseMemoryMode( enable );
}
CMemoryHandle CCpuMathEngine::HeapAlloc( size_t size )
{
std::lock_guard<std::mutex> lock( mutex );
CMemoryHandle result = memoryPool->Alloc( size );
if( result.IsNull() ) {
THROW_MEMORY_EXCEPTION;
}
return result;
}
void CCpuMathEngine::HeapFree( const CMemoryHandle& handle )
{
ASSERT_EXPR( handle.GetMathEngine() == this );
std::lock_guard<std::mutex> lock( mutex );
memoryPool->Free( handle );
}
CMemoryHandle CCpuMathEngine::StackAlloc( size_t size )
{
std::lock_guard<std::mutex> lock( mutex );
CMemoryHandle result = stackAllocator->Alloc(size);
if( result.IsNull() ) {
THROW_MEMORY_EXCEPTION;
}
return result;
}
void CCpuMathEngine::StackFree( const CMemoryHandle& ptr )
{
std::lock_guard<std::mutex> lock( mutex );
stackAllocator->Free( ptr );
}
size_t CCpuMathEngine::GetFreeMemorySize() const
{
std::lock_guard<std::mutex> lock( mutex );
return memoryPool->GetFreeMemorySize();
}
size_t CCpuMathEngine::GetPeakMemoryUsage() const
{
std::lock_guard<std::mutex> lock( mutex );
return memoryPool->GetPeakMemoryUsage();
}
size_t CCpuMathEngine::GetMemoryInPools() const
{
std::lock_guard<std::mutex> lock( mutex );
return memoryPool->GetMemoryInPools();
}
void CCpuMathEngine::CleanUp()
{
std::lock_guard<std::mutex> lock( mutex );
stackAllocator->CleanUp();
memoryPool->CleanUp();
#ifdef NEOML_USE_MKL
NEOML_OMP_NUM_THREADS( threadCount )
{
mkl_thread_free_buffers();
}
#endif
}
void* CCpuMathEngine::GetBuffer( const CMemoryHandle& handle, size_t pos, size_t, bool exchange )
{
(void) exchange; // always returned, no need to copy
return reinterpret_cast<char*>( GetRaw( handle ) ) + pos;
}
void CCpuMathEngine::ReleaseBuffer( const CMemoryHandle&, void*, bool )
{
// no action needed
}
void CCpuMathEngine::DataExchangeRaw(const CMemoryHandle& handle, const void* data, size_t size)
{
ASSERT_EXPR( handle.GetMathEngine() == this );
::memcpy( GetRaw(handle), data, size);
}
void CCpuMathEngine::DataExchangeRaw(void* data, const CMemoryHandle& handle, size_t size)
{
ASSERT_EXPR( handle.GetMathEngine() == this );
::memcpy( data, GetRaw(handle), size );
}
CMemoryHandle CCpuMathEngine::CopyFrom( const CMemoryHandle& handle, size_t size )
{
CMemoryHandle result = HeapAlloc( size );
IMathEngine* otherMathEngine = handle.GetMathEngine();
otherMathEngine->DataExchangeRaw( GetRaw( result ), handle, size );
return result;
}
CMemoryHandle CCpuMathEngine::Alloc( size_t size )
{
// Ensure the correct alignment
void* ptr = 0;
if( MEMORY_ALLOCATION_ALIGNMENT % memoryAlignment == 0 ) {
ptr = malloc(size);
} else {
char* p = static_cast<char*>(malloc(size + memoryAlignment));
if( p != 0 ) {
const intptr_t delta = memoryAlignment - std::abs( ( reinterpret_cast<intptr_t>( p ) % memoryAlignment ) );
ASSERT_EXPR( delta > 0 && delta <= static_cast<intptr_t>( memoryAlignment ) );
p[delta - 1] = static_cast<char>( delta - 1 );
ptr = p + delta;
}
}
if( ptr == 0 ) {
return CMemoryHandle();
}
return CMemoryHandleInternal::CreateMemoryHandle( this, ptr );
}
void CCpuMathEngine::Free( const CMemoryHandle& handle )
{
ASSERT_EXPR( handle.GetMathEngine() == this );
char* ptr = GetRaw( CTypedMemoryHandle<char>( handle ) );
if( MEMORY_ALLOCATION_ALIGNMENT % memoryAlignment == 0 ) {
free(ptr);
return;
}
ptr = ptr - ptr[-1] - 1;
free(ptr);
}
void CCpuMathEngine::GetMathEngineInfo( CMathEngineInfo& info ) const
{
info.Type = MET_Cpu;
::strcpy( info.Name, "CPU" );
info.Id = 0;
info.AvailableMemory = SIZE_MAX;
}
IPerformanceCounters* CCpuMathEngine::CreatePerformanceCounters() const
{
#if FINE_PLATFORM( FINE_ANDROID ) || FINE_PLATFORM( FINE_LINUX )
return new CPerformanceCountersCpuLinux();
#elif FINE_PLATFORM( FINE_WINDOWS ) || FINE_PLATFORM( FINE_DARWIN ) || FINE_PLATFORM( FINE_IOS )
return new CPerformanceCountersDefault();
#else
#error "Platform is not supported!";
return 0;
#endif
}
void CCpuMathEngine::SetDistributedCommunicator( std::shared_ptr<CMultiThreadDistributedCommunicator> comm, const CMathEngineDistributedInfo& info )
{
communicator = comm;
distributedInfo = info;
}
void CCpuMathEngine::AllReduce( const CFloatHandle& handle, int size )
{
if( communicator != nullptr ){
communicator->AllReduce( handle, size );
}
}
void CCpuMathEngine::Broadcast( const CFloatHandle& handle, int size, int root )
{
if( communicator != nullptr ){
communicator->Broadcast( handle, size, root );
}
}
void CpuMathEngineCleanUp()
{
#ifdef NEOML_USE_MKL
// mkl_thread_free_buffers does not free the memory completely
// Looks like a bug in mkl
mkl_free_buffers();
#endif
}
} // namespace NeoML
|
#include "Globals.h"
#include "Application.h"
#include "ModulePhysics.h"
#include "ModuleInput.h"
#include <cmath>
// TODO 1: Include Box 2 header and library
#include "Box2D\Box2D\Box2D.h"
#ifdef _DEBUG
#pragma comment (lib,"Box2D/libx86/Debug/Box2D.lib")
#else
#pragma comment (lib,"Box2D/libx86/Release/Box2D.lib")
#endif
#define METER_TO_PIXEL(meters) {int (meters * 10)}
#define PIXEL_TO_METER(pixels) {float (pixels * 0.1)}
ModulePhysics::ModulePhysics(Application* app, bool start_enabled) : Module(app, start_enabled)
{
debug = true;
world = nullptr;
}
// Destructor
ModulePhysics::~ModulePhysics()
{
}
bool ModulePhysics::Start()
{
LOG("Creating Physics 2D environment");
// TODO 2: Create a private variable for the world
// - You need to send it a default gravity
// - You need init the world in the constructor
// - Remember to destroy the world after using it
b2Vec2 gravity(0.0f, 10.0f);
world = new b2World(gravity);
// TODO 4: Create a a big static circle as "ground"
b2BodyDef groundBodyDef;
groundBodyDef.type = b2_staticBody;
groundBodyDef.position.Set(50.0f, 45.0f);
b2Body* groundBody = world->CreateBody(&groundBodyDef);
b2CircleShape circle;
circle.m_radius = PIXEL_TO_METER(250);
groundBody->CreateFixture(&circle, 0.0f);
return true;
}
//
update_status ModulePhysics::PreUpdate()
{
// TODO 3: Update the simulation ("step" the world)
float32 timeStep = 1.0f / 60.0f;
int32 velocityIterations = 8;
int32 positionIterations = 3;
world->Step(timeStep, velocityIterations, positionIterations);
return UPDATE_CONTINUE;
}
//
update_status ModulePhysics::PostUpdate()
{
// TODO 5: On space bar press, create a circle on mouse position
// - You need to transform the position / radius
if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) {
b2BodyDef pushCircle;
pushCircle.type = b2_dynamicBody;
pushCircle.position.Set(PIXEL_TO_METER(App->input->GetMouseX()), PIXEL_TO_METER(App->input->GetMouseY()));
pushCircle.angle = 0;
b2Body* dynamicBody = world->CreateBody(&pushCircle);
b2CircleShape circleShape;
circleShape.m_radius = PIXEL_TO_METER(30);
b2FixtureDef fixture;
fixture.shape = &circleShape;
dynamicBody->CreateFixture(&fixture);
}
debug = !debug;
if(!debug)
return UPDATE_CONTINUE;
// Bonus code: this will iterate all objects in the world and draw the circles
// You need to provide your own macro to translate meters to pixels
for(b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
for(b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
{
switch(f->GetType())
{
case b2Shape::e_circle:
{
b2CircleShape* shape = (b2CircleShape*)f->GetShape();
b2Vec2 pos = f->GetBody()->GetPosition();
App->renderer->DrawCircle(METER_TO_PIXEL(pos.x), METER_TO_PIXEL(pos.y), METER_TO_PIXEL(shape->m_radius), 255, 255, 255);
}
break;
// You will have to add more cases to draw boxes, edges, and polygons ...
}
}
}
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModulePhysics::CleanUp()
{
LOG("Destroying physics world");
// Delete the whole physics world!
delete world;
return true;
}
|
#ifndef CHECK_BASICS_HANDLER_HPP
#define CHECK_BASICS_HANDLER_HPP
#include <iostream>
#include <unordered_set>
#include <osmium/handler.hpp>
#include <osmium/osm.hpp>
/**
* Check some basics of the input data:
*
* 1. Correct number of nodes, ways, and relations
* 2. Correct ID space used by nodes, ways, and relations
* 3. No ID used more than once
*/
class CheckBasicsHandler : public osmium::handler::Handler {
// Lower bound for the id range allowed in this test.
int m_id_range;
// In the beginning these contains the number of nodes, ways, and relations
// supposedly in the data.osm file. They will be decremented on each object
// and have to be 0 at the end.
int m_num_nodes;
int m_num_ways;
int m_num_relations;
// All IDs encountered in the data.osm file will be stored in this set and
// checked for duplicates.
std::unordered_set<osmium::object_id_type> m_ids;
// Check id is in range [min, max] and that it isn't more than once in input.
void id_check(osmium::object_id_type id, osmium::object_id_type min, osmium::object_id_type max) {
if (id < m_id_range + min || id > m_id_range + max) {
std::cerr << " id " << id << " out of range for this test case\n";
std::exit(1);
}
auto r = m_ids.insert(id);
if (!r.second) {
std::cerr << " id " << id << " contained twice in data.osm\n";
std::exit(1);
}
}
public:
static const int ids_per_testcase = 1000;
CheckBasicsHandler(int testcase, int nodes, int ways, int relations) :
osmium::handler::Handler(),
m_id_range(testcase * ids_per_testcase),
m_num_nodes(nodes),
m_num_ways(ways),
m_num_relations(relations) {
}
~CheckBasicsHandler() {
if (m_num_nodes != 0) {
std::cerr << " wrong number of nodes in data.osm\n";
std::exit(1);
}
if (m_num_ways != 0) {
std::cerr << " wrong number of ways in data.osm\n";
std::exit(1);
}
if (m_num_relations != 0) {
std::cerr << " wrong number of relations in data.osm\n";
std::exit(1);
}
}
void node(const osmium::Node& node) {
id_check(node.id(), 0, 799);
--m_num_nodes;
}
void way(const osmium::Way& way) {
id_check(way.id(), 800, 899);
--m_num_ways;
}
void relations(const osmium::Relation& relation) {
id_check(relation.id(), 900, 999);
--m_num_relations;
}
}; // CheckBasicsHandler
#endif // CHECK_BASICS_HANDLER_HPP
|
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
// Test that header file is self-contained.
#include <boost/beast/http/basic_parser.hpp>
#include "message_fuzz.hpp"
#include "test_parser.hpp"
#include <boost/beast/core/buffer_traits.hpp>
#include <boost/beast/core/buffers_cat.hpp>
#include <boost/beast/core/buffers_prefix.hpp>
#include <boost/beast/core/buffers_suffix.hpp>
#include <boost/beast/core/multi_buffer.hpp>
#include <boost/beast/core/ostream.hpp>
#include <boost/beast/http/parser.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/test/fuzz.hpp>
#include <boost/beast/_experimental/unit_test/suite.hpp>
namespace boost {
namespace beast {
namespace http {
class basic_parser_test : public beast::unit_test::suite
{
public:
enum parse_flag
{
chunked = 1,
connection_keep_alive = 2,
connection_close = 4,
connection_upgrade = 8,
upgrade = 16,
};
class expect_version
{
suite& s_;
int version_;
public:
expect_version(suite& s, int version)
: s_(s)
, version_(version)
{
}
template<class Parser>
void
operator()(Parser const& p) const
{
s_.BEAST_EXPECT(p.version == version_);
}
};
class expect_status
{
suite& s_;
int status_;
public:
expect_status(suite& s, int status)
: s_(s)
, status_(status)
{
}
template<class Parser>
void
operator()(Parser const& p) const
{
s_.BEAST_EXPECT(p.status == status_);
}
};
class expect_flags
{
suite& s_;
unsigned flags_;
public:
expect_flags(suite& s, unsigned flags)
: s_(s)
, flags_(flags)
{
}
template<class Parser>
void
operator()(Parser const& p) const
{
if(flags_ & parse_flag::chunked)
s_.BEAST_EXPECT(p.chunked());
if(flags_ & parse_flag::connection_keep_alive)
s_.BEAST_EXPECT(p.keep_alive());
if(flags_ & parse_flag::connection_close)
s_.BEAST_EXPECT(! p.keep_alive());
if(flags_ & parse_flag::upgrade)
s_.BEAST_EXPECT(! p.upgrade());
}
};
class expect_keepalive
{
suite& s_;
bool v_;
public:
expect_keepalive(suite& s, bool v)
: s_(s)
, v_(v)
{
}
template<class Parser>
void
operator()(Parser const& p) const
{
s_.BEAST_EXPECT(p.keep_alive() == v_);
}
};
class expect_body
{
suite& s_;
std::string const& body_;
public:
expect_body(expect_body&&) = default;
expect_body(suite& s, std::string const& v)
: s_(s)
, body_(v)
{
}
template<class Parser>
void
operator()(Parser const& p) const
{
s_.BEAST_EXPECT(p.body == body_);
}
};
//--------------------------------------------------------------------------
template<class Parser, class ConstBufferSequence, class Test>
typename std::enable_if<
net::is_const_buffer_sequence<ConstBufferSequence>::value>::type
parsegrind(ConstBufferSequence const& buffers,
Test const& test, bool skip = false)
{
auto const size = buffer_bytes(buffers);
for(std::size_t i = 1; i < size - 1; ++i)
{
Parser p;
p.eager(true);
p.skip(skip);
error_code ec;
buffers_suffix<ConstBufferSequence> cb{buffers};
auto n = p.put(buffers_prefix(i, cb), ec);
if(! BEAST_EXPECTS(! ec ||
ec == error::need_more, ec.message()))
continue;
if(! BEAST_EXPECT(! p.is_done()))
continue;
cb.consume(n);
n = p.put(cb, ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
continue;
if(! BEAST_EXPECT(n == buffer_bytes(cb)))
continue;
if(p.need_eof())
{
p.put_eof(ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
continue;
}
if(! BEAST_EXPECT(p.is_done()))
continue;
test(p);
}
for(std::size_t i = 1; i < size - 1; ++i)
{
Parser p;
p.eager(true);
error_code ec;
buffers_suffix<ConstBufferSequence> cb{buffers};
cb.consume(i);
auto n = p.put(buffers_cat(
buffers_prefix(i, buffers), cb), ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
continue;
if(! BEAST_EXPECT(n == size))
continue;
if(p.need_eof())
{
p.put_eof(ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
continue;
}
test(p);
}
}
template<class Parser, class Test>
void
parsegrind(string_view msg, Test const& test, bool skip = false)
{
parsegrind<Parser>(net::const_buffer{
msg.data(), msg.size()}, test, skip);
}
template<class Parser, class ConstBufferSequence>
typename std::enable_if<
net::is_const_buffer_sequence<ConstBufferSequence>::value>::type
parsegrind(ConstBufferSequence const& buffers)
{
parsegrind<Parser>(buffers, [](Parser const&){});
}
template<class Parser>
void
parsegrind(string_view msg)
{
parsegrind<Parser>(msg, [](Parser const&){});
}
template<class Parser>
void
failgrind(string_view msg, error_code const& result)
{
for(std::size_t i = 1; i < msg.size() - 1; ++i)
{
Parser p;
p.eager(true);
error_code ec;
buffers_suffix<net::const_buffer> cb{
boost::in_place_init, msg.data(), msg.size()};
auto n = p.put(buffers_prefix(i, cb), ec);
if(ec == result)
{
pass();
continue;
}
if(! BEAST_EXPECTS(
ec == error::need_more, ec.message()))
continue;
if(! BEAST_EXPECT(! p.is_done()))
continue;
cb.consume(n);
n = p.put(cb, ec);
if(! ec)
p.put_eof(ec);
BEAST_EXPECTS(ec == result, ec.message());
}
for(std::size_t i = 1; i < msg.size() - 1; ++i)
{
Parser p;
p.eager(true);
error_code ec;
p.put(buffers_cat(
net::const_buffer{msg.data(), i},
net::const_buffer{
msg.data() + i, msg.size() - i}), ec);
if(! ec)
p.put_eof(ec);
BEAST_EXPECTS(ec == result, ec.message());
}
}
//--------------------------------------------------------------------------
void
testFlatten()
{
parsegrind<test_parser<true>>(
"GET / HTTP/1.1\r\n"
"\r\n"
);
parsegrind<test_parser<true>>(
"POST / HTTP/1.1\r\n"
"Content-Length: 5\r\n"
"\r\n"
"*****"
);
parsegrind<test_parser<false>>(
"HTTP/1.1 403 Not Found\r\n"
"\r\n"
);
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Content-Length: 5\r\n"
"\r\n"
"*****"
);
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5;x\r\n*****\r\n"
"0\r\nMD5: 0xff30\r\n"
"\r\n"
);
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"\r\n"
"*****"
);
}
void
testObsFold()
{
auto const check =
[&](std::string const& s, string_view value)
{
std::string m =
"GET / HTTP/1.1\r\n"
"f: " + s + "\r\n"
"\r\n";
parsegrind<request_parser<string_body>>(m,
[&](request_parser<string_body> const& p)
{
BEAST_EXPECT(p.get()["f"] == value);
});
};
check("x", "x");
check(" x", "x");
check("\tx", "x");
check(" \tx", "x");
check("\t x", "x");
check("x ", "x");
check(" x\t", "x");
check("\tx \t", "x");
check(" \tx\t ", "x");
check("\t x \t ", "x");
check("\r\n x", "x");
check(" \r\n x", "x");
check(" \r\n\tx", "x");
check(" \r\n\t x", "x");
check(" \r\n \tx", "x");
check(" \r\n \r\n \r\n x \t", "x");
check("xy", "xy");
check("\r\n x", "x");
check("\r\n x", "x");
check("\r\n xy", "xy");
check("\r\n \r\n \r\n x", "x");
check("\r\n \r\n \r\n xy", "xy");
check("x\r\n y", "x y");
check("x\r\n y\r\n z ", "x y z");
}
// Check that all callbacks are invoked
void
testCallbacks()
{
parsegrind<test_parser<true>>(
"GET / HTTP/1.1\r\n"
"User-Agent: test\r\n"
"Content-Length: 1\r\n"
"\r\n"
"*",
[&](test_parser<true> const& p)
{
BEAST_EXPECT(p.got_on_begin == 1);
BEAST_EXPECT(p.got_on_field == 2);
BEAST_EXPECT(p.got_on_header == 1);
BEAST_EXPECT(p.got_on_body == 1);
BEAST_EXPECT(p.got_on_chunk == 0);
BEAST_EXPECT(p.got_on_complete == 1);
});
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Content-Length: 1\r\n"
"\r\n"
"*",
[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.got_on_begin == 1);
BEAST_EXPECT(p.got_on_field == 2);
BEAST_EXPECT(p.got_on_header == 1);
BEAST_EXPECT(p.got_on_body == 1);
BEAST_EXPECT(p.got_on_chunk == 0);
BEAST_EXPECT(p.got_on_complete == 1);
});
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"1\r\n*\r\n"
"0\r\n\r\n",
[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.got_on_begin == 1);
BEAST_EXPECT(p.got_on_field == 2);
BEAST_EXPECT(p.got_on_header == 1);
BEAST_EXPECT(p.got_on_body == 1);
BEAST_EXPECT(p.got_on_chunk == 2);
BEAST_EXPECT(p.got_on_complete == 1);
});
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"1;x\r\n*\r\n"
"0\r\n\r\n",
[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.got_on_begin == 1);
BEAST_EXPECT(p.got_on_field == 2);
BEAST_EXPECT(p.got_on_header == 1);
BEAST_EXPECT(p.got_on_body == 1);
BEAST_EXPECT(p.got_on_chunk == 2);
BEAST_EXPECT(p.got_on_complete == 1);
});
}
void
testRequestLine()
{
using P = test_parser<true>;
parsegrind<P>("GET /x HTTP/1.0\r\n\r\n");
parsegrind<P>("!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz / HTTP/1.0\r\n\r\n");
parsegrind<P>("GET / HTTP/1.0\r\n\r\n", expect_version{*this, 10});
parsegrind<P>("G / HTTP/1.1\r\n\r\n", expect_version{*this, 11});
// VFALCO TODO various forms of good request-target (uri)
failgrind<P>("\tGET / HTTP/1.0\r\n" "\r\n", error::bad_method);
failgrind<P>("GET\x01 / HTTP/1.0\r\n" "\r\n", error::bad_method);
failgrind<P>("GET / HTTP/1.0\r\n" "\r\n", error::bad_target);
failgrind<P>("GET \x01 HTTP/1.0\r\n" "\r\n", error::bad_target);
failgrind<P>("GET /\x01 HTTP/1.0\r\n" "\r\n", error::bad_target);
// VFALCO TODO various forms of bad request-target (uri)
failgrind<P>("GET / HTTP/1.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / _TTP/1.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / H_TP/1.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HT_P/1.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTT_/1.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP_1.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/01.2\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/3.45\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/67.89\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/x.0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/1.x\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/1.0 \r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/1_0\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/1.0\n\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/1.0\n\r\r\n" "\r\n", error::bad_version);
failgrind<P>("GET / HTTP/1.0\r\r\n" "\r\n", error::bad_version);
}
void
testStatusLine()
{
using P = test_parser<false>;
parsegrind<P>("HTTP/1.0 000 OK\r\n" "\r\n", expect_status{*this, 0});
parsegrind<P>("HTTP/1.1 012 OK\r\n" "\r\n", expect_status{*this, 12});
parsegrind<P>("HTTP/1.0 345 OK\r\n" "\r\n", expect_status{*this, 345});
parsegrind<P>("HTTP/1.0 678 OK\r\n" "\r\n", expect_status{*this, 678});
parsegrind<P>("HTTP/1.0 999 OK\r\n" "\r\n", expect_status{*this, 999});
parsegrind<P>("HTTP/1.0 200 \tX\r\n" "\r\n", expect_version{*this, 10});
parsegrind<P>("HTTP/1.1 200 X\r\n" "\r\n", expect_version{*this, 11});
parsegrind<P>("HTTP/1.0 200 \r\n" "\r\n");
parsegrind<P>("HTTP/1.1 200 X \r\n" "\r\n");
parsegrind<P>("HTTP/1.1 200 X\t\r\n" "\r\n");
parsegrind<P>("HTTP/1.1 200 \x80\x81...\xfe\xff\r\n\r\n");
parsegrind<P>("HTTP/1.1 200 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n\r\n");
failgrind<P>("\rHTTP/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("\nHTTP/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>(" HTTP/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("_TTP/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("H_TP/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HT_P/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTT_/1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP_1.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/01.2 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/3.45 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/67.89 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/x.0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/1.x 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/1_0 200 OK\r\n" "\r\n", error::bad_version);
failgrind<P>("HTTP/1.0 200 OK\r\n" "\r\n", error::bad_status);
failgrind<P>("HTTP/1.0 0 OK\r\n" "\r\n", error::bad_status);
failgrind<P>("HTTP/1.0 12 OK\r\n" "\r\n", error::bad_status);
failgrind<P>("HTTP/1.0 3456 OK\r\n" "\r\n", error::bad_status);
failgrind<P>("HTTP/1.0 200\r\n" "\r\n", error::bad_status);
failgrind<P>("HTTP/1.0 200 \n\r\n" "\r\n", error::bad_reason);
failgrind<P>("HTTP/1.0 200 \x01\r\n" "\r\n", error::bad_reason);
failgrind<P>("HTTP/1.0 200 \x7f\r\n" "\r\n", error::bad_reason);
failgrind<P>("HTTP/1.0 200 OK\n\r\n" "\r\n", error::bad_reason);
failgrind<P>("HTTP/1.0 200 OK\r\r\n" "\r\n", error::bad_line_ending);
}
void
testFields()
{
auto const m =
[](std::string const& s)
{
return "GET / HTTP/1.1\r\n" + s + "\r\n";
};
using P = test_parser<true>;
parsegrind<P>(m("f:\r\n"));
parsegrind<P>(m("f: \r\n"));
parsegrind<P>(m("f:\t\r\n"));
parsegrind<P>(m("f: \t\r\n"));
parsegrind<P>(m("f: v\r\n"));
parsegrind<P>(m("f:\tv\r\n"));
parsegrind<P>(m("f:\tv \r\n"));
parsegrind<P>(m("f:\tv\t\r\n"));
parsegrind<P>(m("f:\tv\t \r\n"));
parsegrind<P>(m("f:\r\n \r\n"));
parsegrind<P>(m("f:v\r\n"));
parsegrind<P>(m("f: v\r\n u\r\n"));
parsegrind<P>(m("!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz: v\r\n"));
parsegrind<P>(m("f: !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x80\x81...\xfe\xff\r\n"));
failgrind<P>(m(" f: v\r\n"), error::bad_field);
failgrind<P>(m("\tf: v\r\n"), error::bad_field);
failgrind<P>(m("f : v\r\n"), error::bad_field);
failgrind<P>(m("f\t: v\r\n"), error::bad_field);
failgrind<P>(m("f: \n\r\n"), error::bad_value);
failgrind<P>(m("f: v\r \r\n"), error::bad_line_ending);
failgrind<P>(m("f: \r v\r\n"), error::bad_line_ending);
failgrind<P>(
"GET / HTTP/1.1\r\n"
"\r \n\r\n"
"\r\n", error::bad_line_ending);
}
void
testConnectionField()
{
auto const m = [](std::string const& s)
{ return "GET / HTTP/1.1\r\n" + s + "\r\n"; };
auto const cn = [](std::string const& s)
{ return "GET / HTTP/1.1\r\nConnection: " + s + "\r\n"; };
#if 0
auto const keepalive = [&](bool v)
{ //return keepalive_f{*this, v}; return true; };
#endif
using P = test_parser<true>;
parsegrind<P>(cn("close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn(",close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn(" close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("\tclose\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close,\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close\t\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn(" ,\t,,close,, ,\t,,\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("\r\n close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close\r\n \r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("any,close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close,any\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("any\r\n ,close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close\r\n ,any\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(cn("close,close\r\n"), expect_flags{*this, parse_flag::connection_close}); // weird but allowed
parsegrind<P>(cn("keep-alive\r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("keep-alive \r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("keep-alive\t \r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("keep-alive\t ,x\r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("\r\n keep-alive \t\r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("keep-alive \r\n \t \r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("keep-alive\r\n \r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(cn("upgrade\r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(cn("upgrade \r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(cn("upgrade\t \r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(cn("upgrade\t ,x\r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(cn("\r\n upgrade \t\r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(cn("upgrade \r\n \t \r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(cn("upgrade\r\n \r\n"), expect_flags{*this, parse_flag::connection_upgrade});
// VFALCO What's up with these?
//parsegrind<P>(cn("close,keep-alive\r\n"), expect_flags{*this, parse_flag::connection_close | parse_flag::connection_keep_alive});
parsegrind<P>(cn("upgrade,keep-alive\r\n"), expect_flags{*this, parse_flag::connection_upgrade | parse_flag::connection_keep_alive});
parsegrind<P>(cn("upgrade,\r\n keep-alive\r\n"), expect_flags{*this, parse_flag::connection_upgrade | parse_flag::connection_keep_alive});
//parsegrind<P>(cn("close,keep-alive,upgrade\r\n"), expect_flags{*this, parse_flag::connection_close | parse_flag::connection_keep_alive | parse_flag::connection_upgrade});
parsegrind<P>("GET / HTTP/1.1\r\n\r\n", expect_keepalive(*this, true));
parsegrind<P>("GET / HTTP/1.0\r\n\r\n", expect_keepalive(*this, false));
parsegrind<P>("GET / HTTP/1.0\r\n"
"Connection: keep-alive\r\n\r\n", expect_keepalive(*this, true));
parsegrind<P>("GET / HTTP/1.1\r\n"
"Connection: close\r\n\r\n", expect_keepalive(*this, false));
parsegrind<P>(cn("x\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("x,y\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("x ,y\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("x\t,y\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keep\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn(",keep\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn(" keep\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("\tnone\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keep,\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keep\t\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keep\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn(" ,\t,,keep,, ,\t,,\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("\r\n keep\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keep\r\n \r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("closet\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn(",closet\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn(" closet\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("\tcloset\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("closet,\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("closet\t\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("closet\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn(" ,\t,,closet,, ,\t,,\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("\r\n closet\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("closet\r\n \r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("clog\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("key\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("uptown\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keeper\r\n \r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("keep-alively\r\n \r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("up\r\n \r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("upgrader\r\n \r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("none\r\n"), expect_flags{*this, 0});
parsegrind<P>(cn("\r\n none\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("ConnectioX: close\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Condor: close\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Connect: close\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Connections: close\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Proxy-Connection: close\r\n"), expect_flags{*this, parse_flag::connection_close});
parsegrind<P>(m("Proxy-Connection: keep-alive\r\n"), expect_flags{*this, parse_flag::connection_keep_alive});
parsegrind<P>(m("Proxy-Connection: upgrade\r\n"), expect_flags{*this, parse_flag::connection_upgrade});
parsegrind<P>(m("Proxy-ConnectioX: none\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Proxy-Connections: 1\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Proxy-Connotes: see-also\r\n"), expect_flags{*this, 0});
failgrind<P>(cn("[\r\n"), error::bad_value);
failgrind<P>(cn("close[\r\n"), error::bad_value);
failgrind<P>(cn("close [\r\n"), error::bad_value);
failgrind<P>(cn("close, upgrade [\r\n"), error::bad_value);
failgrind<P>(cn("upgrade[]\r\n"), error::bad_value);
failgrind<P>(cn("keep\r\n -alive\r\n"), error::bad_value);
failgrind<P>(cn("keep-alive[\r\n"), error::bad_value);
failgrind<P>(cn("keep-alive []\r\n"), error::bad_value);
failgrind<P>(cn("no[ne]\r\n"), error::bad_value);
}
void
testContentLengthField()
{
using P = test_parser<true>;
auto const c = [](std::string const& s)
{ return "GET / HTTP/1.1\r\nContent-Length: " + s + "\r\n"; };
auto const m = [](std::string const& s)
{ return "GET / HTTP/1.1\r\n" + s + "\r\n"; };
auto const check =
[&](std::string const& s, std::uint64_t v)
{
parsegrind<P>(c(s),
[&](P const& p)
{
BEAST_EXPECT(p.content_length());
BEAST_EXPECT(p.content_length() && *p.content_length() == v);
}, true);
};
check("0\r\n", 0);
check("00\r\n", 0);
check("1\r\n", 1);
check("01\r\n", 1);
check("9\r\n", 9);
check("42 \r\n", 42);
check("42\t\r\n", 42);
check("42 \t \r\n", 42);
check("42\r\n \t \r\n", 42);
parsegrind<P>(m("Content-LengtX: 0\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Content-Lengths: many\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Content: full\r\n"), expect_flags{*this, 0});
failgrind<P>(c("\r\n"), error::bad_content_length);
failgrind<P>(c("18446744073709551616\r\n"), error::bad_content_length);
failgrind<P>(c("0 0\r\n"), error::bad_content_length);
failgrind<P>(c("0 1\r\n"), error::bad_content_length);
failgrind<P>(c(",\r\n"), error::bad_content_length);
failgrind<P>(c("0,\r\n"), error::bad_content_length);
failgrind<P>(m(
"Content-Length: 0\r\nContent-Length: 0\r\n"), error::bad_content_length);
}
void
testTransferEncodingField()
{
auto const m = [](std::string const& s)
{ return "GET / HTTP/1.1\r\n" + s + "\r\n"; };
auto const ce = [](std::string const& s)
{ return "GET / HTTP/1.1\r\nTransfer-Encoding: " + s + "\r\n0\r\n\r\n"; };
auto const te = [](std::string const& s)
{ return "GET / HTTP/1.1\r\nTransfer-Encoding: " + s + "\r\n"; };
using P = test_parser<true>;
parsegrind<P>(ce("chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked \r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked\t\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked \t\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce(" chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("\tchunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked,\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked ,\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked, \r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce(",chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce(", chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce(" ,chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("chunked\r\n \r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("\r\n chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce(",\r\n chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("\r\n ,chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce(",\r\n chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("gzip, chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("gzip, chunked \r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(ce("gzip, \r\n chunked\r\n"), expect_flags{*this, parse_flag::chunked});
// Technically invalid but beyond the parser's scope to detect
// VFALCO Look into this
//parsegrind<P>(ce("custom;key=\",chunked\r\n"), expect_flags{*this, parse_flag::chunked});
parsegrind<P>(te("gzip\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("chunked, gzip\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("chunked\r\n , gzip\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("chunked,\r\n gzip\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("chunked,\r\n ,gzip\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("bigchunked\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("chunk\r\n ked\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("bar\r\n ley chunked\r\n"), expect_flags{*this, 0});
parsegrind<P>(te("barley\r\n chunked\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Transfer-EncodinX: none\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Transfer-Encodings: 2\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Transfer-Encoded: false\r\n"), expect_flags{*this, 0});
failgrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Content-Length: 1\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n", error::bad_transfer_encoding);
}
void
testUpgradeField()
{
auto const m = [](std::string const& s)
{ return "GET / HTTP/1.1\r\n" + s + "\r\n"; };
using P = test_parser<true>;
parsegrind<P>(m("Upgrade:\r\n"), expect_flags{*this, parse_flag::upgrade});
parsegrind<P>(m("Upgrade: \r\n"), expect_flags{*this, parse_flag::upgrade});
parsegrind<P>(m("Upgrade: yes\r\n"), expect_flags{*this, parse_flag::upgrade});
parsegrind<P>(m("Up: yes\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("UpgradX: none\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Upgrades: 2\r\n"), expect_flags{*this, 0});
parsegrind<P>(m("Upsample: 4x\r\n"), expect_flags{*this, 0});
parsegrind<P>(
"GET / HTTP/1.1\r\n"
"Connection: upgrade\r\n"
"Upgrade: WebSocket\r\n"
"\r\n",
[&](P const& p)
{
BEAST_EXPECT(p.upgrade());
});
}
void
testPartial()
{
// Make sure the slow-loris defense works and that
// we don't get duplicate or missing fields on a split.
parsegrind<test_parser<true>>(
"GET / HTTP/1.1\r\n"
"a: 0\r\n"
"b: 1\r\n"
"c: 2\r\n"
"d: 3\r\n"
"e: 4\r\n"
"f: 5\r\n"
"g: 6\r\n"
"h: 7\r\n"
"i: 8\r\n"
"j: 9\r\n"
"\r\n",
[&](test_parser<true> const& p)
{
BEAST_EXPECT(p.fields.size() == 10);
BEAST_EXPECT(p.fields.at("a") == "0");
BEAST_EXPECT(p.fields.at("b") == "1");
BEAST_EXPECT(p.fields.at("c") == "2");
BEAST_EXPECT(p.fields.at("d") == "3");
BEAST_EXPECT(p.fields.at("e") == "4");
BEAST_EXPECT(p.fields.at("f") == "5");
BEAST_EXPECT(p.fields.at("g") == "6");
BEAST_EXPECT(p.fields.at("h") == "7");
BEAST_EXPECT(p.fields.at("i") == "8");
BEAST_EXPECT(p.fields.at("j") == "9");
});
}
void
testLimits()
{
{
multi_buffer b;
ostream(b) <<
"POST / HTTP/1.1\r\n"
"Content-Length: 2\r\n"
"\r\n"
"**";
error_code ec;
test_parser<true> p;
p.header_limit(10);
p.eager(true);
p.put(b.data(), ec);
BEAST_EXPECTS(ec == error::header_limit, ec.message());
}
{
multi_buffer b;
ostream(b) <<
"POST / HTTP/1.1\r\n"
"Content-Length: 2\r\n"
"\r\n"
"**";
error_code ec;
test_parser<true> p;
p.body_limit(1);
p.eager(true);
p.put(b.data(), ec);
BEAST_EXPECTS(ec == error::body_limit, ec.message());
}
{
multi_buffer b;
ostream(b) <<
"HTTP/1.1 200 OK\r\n"
"\r\n"
"**";
error_code ec;
test_parser<false> p;
p.body_limit(1);
p.eager(true);
p.put(b.data(), ec);
BEAST_EXPECTS(ec == error::body_limit, ec.message());
}
{
multi_buffer b;
ostream(b) <<
"POST / HTTP/1.1\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"2\r\n"
"**\r\n"
"0\r\n\r\n";
error_code ec;
test_parser<true> p;
p.body_limit(1);
p.eager(true);
p.put(b.data(), ec);
BEAST_EXPECTS(ec == error::body_limit, ec.message());
}
}
//--------------------------------------------------------------------------
static
net::const_buffer
buf(string_view s)
{
return {s.data(), s.size()};
}
template<class ConstBufferSequence, bool isRequest>
std::size_t
feed(ConstBufferSequence const& buffers,
basic_parser<isRequest>& p, error_code& ec)
{
p.eager(true);
return p.put(buffers, ec);
}
void
testBody()
{
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n"
"4\r\nabcd\r\n"
"0\r\n\r\n"
,[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.body == "abcd");
});
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Server: test\r\n"
"Expect: Expires, MD5-Fingerprint\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"5\r\n"
"*****\r\n"
"2;a;b=1;c=\"2\"\r\n"
"--\r\n"
"0;d;e=3;f=\"4\"\r\n"
"Expires: never\r\n"
"MD5-Fingerprint: -\r\n"
"\r\n"
,[&](test_parser<false> const& p)
{
BEAST_EXPECT(p.body == "*****--");
});
parsegrind<test_parser<true>>(
"GET / HTTP/1.1\r\n"
"Content-Length: 1\r\n"
"\r\n"
"1",
expect_body(*this, "1"));
parsegrind<test_parser<false>>(
"HTTP/1.0 200 OK\r\n"
"\r\n"
"hello",
expect_body(*this, "hello"));
parsegrind<test_parser<true>>(buffers_cat(
buf("GET / HTTP/1.1\r\n"
"Content-Length: 10\r\n"
"\r\n"),
buf("12"),
buf("345"),
buf("67890")));
// request without Content-Length or
// Transfer-Encoding: chunked has no body.
{
error_code ec;
test_parser<true> p;
feed(buf(
"GET / HTTP/1.0\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(p.is_done());
}
{
error_code ec;
test_parser<true> p;
feed(buf(
"GET / HTTP/1.1\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(p.is_done());
}
// response without Content-Length or
// Transfer-Encoding: chunked requires eof.
{
error_code ec;
test_parser<false> p;
feed(buf(
"HTTP/1.0 200 OK\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(! p.is_done());
BEAST_EXPECT(p.need_eof());
}
// 304 "Not Modified" response does not require eof
{
error_code ec;
test_parser<false> p;
feed(buf(
"HTTP/1.0 304 Not Modified\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(p.is_done());
}
// Chunked response does not require eof
{
error_code ec;
test_parser<false> p;
feed(buf(
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(! p.is_done());
feed(buf(
"0\r\n\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(p.is_done());
}
// restart: 1.0 assumes Connection: close
{
error_code ec;
test_parser<true> p;
feed(buf(
"GET / HTTP/1.0\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(p.is_done());
}
// restart: 1.1 assumes Connection: keep-alive
{
error_code ec;
test_parser<true> p;
feed(buf(
"GET / HTTP/1.1\r\n"
"\r\n"
), p, ec);
BEAST_EXPECTS(! ec, ec.message());
BEAST_EXPECT(p.is_done());
}
failgrind<test_parser<true>>(
"GET / HTTP/1.1\r\n"
"Content-Length: 1\r\n"
"\r\n",
error::partial_message);
}
//--------------------------------------------------------------------------
// https://github.com/boostorg/beast/issues/430
void
testIssue430()
{
parsegrind<test_parser<false>>(
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n"
"4\r\nabcd\r\n"
"0\r\n\r\n");
}
// https://github.com/boostorg/beast/issues/452
void
testIssue452()
{
error_code ec;
test_parser<true> p;
p.eager(true);
string_view s =
"GET / HTTP/1.1\r\n"
"\r\n"
"die!";
p.put(net::buffer(
s.data(), s.size()), ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
return;
BEAST_EXPECT(p.is_done());
}
// https://github.com/boostorg/beast/issues/496
void
testIssue496()
{
// The bug affected hex parsing with leading zeroes
using P = test_parser<false>;
parsegrind<P>(
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n"
"0004\r\nabcd\r\n"
"0\r\n\r\n"
,[&](P const& p)
{
BEAST_EXPECT(p.body == "abcd");
});
}
// https://github.com/boostorg/beast/issues/692
void
testIssue692()
{
error_code ec;
test_parser<false> p;
p.eager(true);
string_view s =
"HTTP/1.1 101 Switching Protocols\r\n"
"Content-Length: 2147483648\r\n"
"\r\n";
p.put(net::buffer(
s.data(), s.size()), ec);
if(! BEAST_EXPECTS(! ec, ec.message()))
return;
BEAST_EXPECT(p.is_done());
}
//--------------------------------------------------------------------------
void
testFuzz()
{
auto const grind =
[&](string_view s)
{
static_string<100> ss{s};
test::fuzz_rand r;
test::fuzz(ss, 4, 5, r,
[&](string_view s)
{
error_code ec;
test_parser<false> p;
p.eager(true);
p.put(net::const_buffer{
s.data(), s.size()}, ec);
});
};
auto const good =
[&](string_view s)
{
std::string msg =
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"0" + std::string(s) + "\r\n"
"\r\n";
error_code ec;
test_parser<false> p;
p.eager(true);
p.put(net::const_buffer{
msg.data(), msg.size()}, ec);
BEAST_EXPECTS(! ec, ec.message());
grind(msg);
};
auto const bad =
[&](string_view s)
{
std::string msg =
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"0" + std::string(s) + "\r\n"
"\r\n";
error_code ec;
test_parser<false> p;
p.eager(true);
p.put(net::const_buffer{
msg.data(), msg.size()}, ec);
BEAST_EXPECT(ec);
grind(msg);
};
chunkExtensionsTest(good, bad);
}
//--------------------------------------------------------------------------
void
testRegression1()
{
// crash_00cda0b02d5166bd1039ddb3b12618cd80da75f3
unsigned char buf[] ={
0x4C,0x4F,0x43,0x4B,0x20,0x2F,0x25,0x65,0x37,0x6C,0x59,0x3B,0x2F,0x3B,0x3B,0x25,0x30,0x62,0x38,0x3D,0x70,0x2F,0x72,0x20,
0x48,0x54,0x54,0x50,0x2F,0x31,0x2E,0x31,0x0D,0x0A,0x41,0x63,0x63,0x65,0x70,0x74,0x2D,0x45,0x6E,0x63,0x6F,0x64,0x69,0x6E,
0x67,0x3A,0x0D,0x0A,0x09,0x20,0xEE,0x0D,0x0A,0x4F,0x72,0x69,0x67,0x69,0x6E,0x61,0x6C,0x2D,0x4D,0x65,0x73,0x73,0x61,0x67,
0x65,0x2D,0x49,0x44,0x3A,0xEB,0x09,0x09,0x09,0x09,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x3A,0x20,0x0D,0x0A,0x09,0x20,
0xF7,0x44,0x9B,0xA5,0x06,0x9F,0x0D,0x0A,0x52,0x65,0x73,0x65,0x6E,0x74,0x2D,0x44,0x61,0x74,0x65,0x3A,0xF4,0x0D,0x0A,0x41,
0x6C,0x74,0x2D,0x53,0x76,0x63,0x3A,0x20,0x0D,0x0A,0x54,0x72,0x61,0x69,0x6C,0x65,0x72,0x3A,0x20,0x20,0x09,0x20,0x20,0x20,
0x0D,0x0A,0x4C,0x69,0x73,0x74,0x2D,0x49,0x44,0x3A,0xA6,0x6B,0x86,0x09,0x09,0x20,0x09,0x0D,0x0A,0x41,0x6C,0x74,0x65,0x72,
0x6E,0x61,0x74,0x65,0x2D,0x52,0x65,0x63,0x69,0x70,0x69,0x65,0x6E,0x74,0x3A,0xF3,0x13,0xE3,0x22,0x9D,0xEF,0xFB,0x84,0x71,
0x4A,0xCC,0xBC,0x96,0xF7,0x5B,0x72,0xF1,0xF2,0x0D,0x0A,0x4C,0x6F,0x63,0x61,0x74,0x69,0x6F,0x6E,0x3A,0x20,0x0D,0x0A,0x41,
0x63,0x63,0x65,0x70,0x74,0x2D,0x41,0x64,0x64,0x69,0x74,0x69,0x6F,0x6E,0x73,0x3A,0x20,0x0D,0x0A,0x4D,0x4D,0x48,0x53,0x2D,
0x4F,0x72,0x69,0x67,0x69,0x6E,0x61,0x74,0x6F,0x72,0x2D,0x50,0x4C,0x41,0x44,0x3A,0x20,0x0D,0x0A,0x4F,0x72,0x69,0x67,0x69,
0x6E,0x61,0x6C,0x2D,0x53,0x65,0x6E,0x64,0x65,0x72,0x3A,0x20,0x0D,0x0A,0x4F,0x72,0x69,0x67,0x69,0x6E,0x61,0x6C,0x2D,0x53,
0x65,0x6E,0x64,0x65,0x72,0x3A,0x0D,0x0A,0x50,0x49,0x43,0x53,0x2D,0x4C,0x61,0x62,0x65,0x6C,0x3A,0x0D,0x0A,0x20,0x09,0x0D,
0x0A,0x49,0x66,0x3A,0x20,0x40,0xC1,0x50,0x5C,0xD6,0xC3,0x86,0xFC,0x8D,0x5C,0x7C,0x96,0x45,0x0D,0x0A,0x4D,0x4D,0x48,0x53,
0x2D,0x45,0x78,0x65,0x6D,0x70,0x74,0x65,0x64,0x2D,0x41,0x64,0x64,0x72,0x65,0x73,0x73,0x3A,0x0D,0x0A,0x49,0x6E,0x6A,0x65,
0x63,0x74,0x69,0x6F,0x6E,0x2D,0x49,0x6E,0x66,0x6F,0x3A,0x20,0x0D,0x0A,0x43,0x6F,0x6E,0x74,0x65,0x74,0x6E,0x2D,0x4C,0x65,
0x6E,0x67,0x74,0x68,0x3A,0x20,0x30,0x0D,0x0A,0x0D,0x0A
};
error_code ec;
test_parser<true> p;
feed(net::buffer(buf, sizeof(buf)), p, ec);
BEAST_EXPECT(ec);
}
void
testIssue1211()
{
using base = detail::basic_parser_base;
auto const good =
[&](string_view s, std::uint32_t v0)
{
std::uint32_t v;
auto const result =
base::parse_dec(s.begin(), s.end(), v);
if(BEAST_EXPECTS(result, s))
BEAST_EXPECTS(v == v0, s);
};
auto const bad =
[&](string_view s)
{
std::uint32_t v;
auto const result =
base::parse_dec(s.begin(), s.end(), v);
BEAST_EXPECTS(! result, s);
};
good("0", 0);
good("00", 0);
good("001", 1);
good("255", 255);
good("65535", 65535);
good("65536", 65536);
good("4294967295", 4294967295);
bad ("");
bad (" ");
bad (" 0");
bad ("0 ");
bad ("-1");
bad ("4294967296");
}
void
testIssue1267()
{
using base = detail::basic_parser_base;
auto const good =
[&](string_view s, std::uint64_t v0)
{
std::uint64_t v;
auto it = s.begin();
auto const result =
base::parse_hex(it, v);
if(BEAST_EXPECTS(result, s))
BEAST_EXPECTS(v == v0, s);
};
auto const bad =
[&](string_view s)
{
std::uint64_t v;
auto it = s.begin();
auto const result =
base::parse_hex(it, v);
BEAST_EXPECTS(! result, s);
};
good("f\r\n", 15);
good("ff\r\n", 255);
good("ffff\r\n", 65535);
good("ffffffffr\n", 4294967295);
good("ffffffffffffffff\r\n", 18446744073709551615ULL);
bad ("\r\n");
bad ("g\r\n");
bad ("10000000000000000\r\n");
bad ("ffffffffffffffffffffff\r\n");
}
//--------------------------------------------------------------------------
void
run() override
{
testFlatten();
testObsFold();
testCallbacks();
testRequestLine();
testStatusLine();
testFields();
testConnectionField();
testContentLengthField();
testTransferEncodingField();
testUpgradeField();
testPartial();
testLimits();
testBody();
testIssue430();
testIssue452();
testIssue496();
testIssue692();
testFuzz();
testRegression1();
testIssue1211();
testIssue1267();
}
};
BEAST_DEFINE_TESTSUITE(beast,http,basic_parser);
} // http
} // beast
} // boost
|
/*-----------------------------------------------------------------------
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 "SeismicLineFeature.h"
#include "SeismicLineSetFeature.h"
using namespace std;
using namespace RESQML2_0_1_NS;
using namespace gsoap_resqml2_0_1;
const char* SeismicLineFeature::XML_TAG = "SeismicLineFeature";
SeismicLineFeature::SeismicLineFeature(COMMON_NS::DataObjectRepository* repo, const std::string & guid, const std::string & title,
int traceIndexIncrement, int firstTraceIndex, unsigned int traceCount)
{
if (repo == nullptr) {
throw invalid_argument("The soap context cannot be null.");
}
gsoapProxy2_0_1 = soap_new_resqml20__obj_USCORESeismicLineFeature(repo->getGsoapContext());
_resqml20__SeismicLineFeature* seismicLine = static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1);
seismicLine->TraceIndexIncrement = traceIndexIncrement;
seismicLine->FirstTraceIndex = firstTraceIndex;
seismicLine->TraceCount = traceCount;
initMandatoryMetadata();
setMetadata(guid, title, std::string(), -1, std::string(), std::string(), -1, std::string());
repo->addOrReplaceDataObject(this);
}
int SeismicLineFeature::getTraceIndexIncrement() const
{
return static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1)->TraceIndexIncrement;
}
int SeismicLineFeature::getFirstTraceIndex() const
{
return static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1)->FirstTraceIndex;
}
unsigned int SeismicLineFeature::getTraceCount() const
{
return static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1)->TraceCount;
}
void SeismicLineFeature::setSeismicLineSet(SeismicLineSetFeature * seisLineSet)
{
getRepository()->addRelationship(this, seisLineSet);
static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1)->IsPartOf = seisLineSet->newResqmlReference();
}
SeismicLineSetFeature* SeismicLineFeature::getSeismicLineSet() const
{
_resqml20__SeismicLineFeature* seismicLine = static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1);
return seismicLine->IsPartOf == nullptr ? nullptr : getRepository()->getDataObjectByUuid<SeismicLineSetFeature>(seismicLine->IsPartOf->UUID);
}
void SeismicLineFeature::loadTargetRelationships()
{
_resqml20__SeismicLineFeature* seismicLine = static_cast<_resqml20__SeismicLineFeature*>(gsoapProxy2_0_1);
if (seismicLine->IsPartOf != nullptr) {
convertDorIntoRel<SeismicLineSetFeature>(seismicLine->IsPartOf);
}
}
|
// Copyright 2013-2021 Phokham Nonava
//
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <model/color.h>
#include <model/castlingtype.h>
#include "model/castling.h"
#include "gtest/gtest.h"
using namespace pulse;
TEST(castlingtest, testValueOf) {
EXPECT_EQ(+castling::WHITE_KINGSIDE, castling::valueOf(color::WHITE, castlingtype::KINGSIDE));
EXPECT_EQ(+castling::WHITE_QUEENSIDE, castling::valueOf(color::WHITE, castlingtype::QUEENSIDE));
EXPECT_EQ(+castling::BLACK_KINGSIDE, castling::valueOf(color::BLACK, castlingtype::KINGSIDE));
EXPECT_EQ(+castling::BLACK_QUEENSIDE, castling::valueOf(color::BLACK, castlingtype::QUEENSIDE));
}
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @brief A file defines names to be used by plugins to create execution graph.
* It's an API between plugin and WorkBench tool.
* @file exec_graph_info.hpp
*/
#pragma once
#include <ie_api.h>
#include <ie_parameter.hpp>
#include <string>
#include <ngraph/node.hpp>
/**
* @brief A namespace with const values for Execution Graph parameters names.
*
* Executable Graph Info is represented in ICNNNetwork format with general CNNLayer nodes inside
* including connections between the nodes. Each node describes an executable hardware-specific
* primitive and stores its parameters within CNNLayer::params map.
* There is a list of general keys for the parameters map.
*/
namespace ExecGraphInfoSerialization {
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get a string of layer names separated by a comma
* from the original IR, which were fused/merged to the current executable primitive.
*/
static const char ORIGINAL_NAMES[] = "originalLayersNames";
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get a type of the executable primitive.
*/
static const char IMPL_TYPE[] = "primitiveType";
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get output precisions of the executable primitive.
*/
static const char OUTPUT_PRECISIONS[] = "outputPrecisions";
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get a value of execution time of the executable primitive.
*/
static const char PERF_COUNTER[] = "execTimeMcs";
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get output layouts of primitive.
*/
static const char OUTPUT_LAYOUTS[] = "outputLayouts";
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get an execution order of primitive.
*/
static const char EXECUTION_ORDER[] = "execOrder";
/**
* @ingroup ie_dev_exec_graph
* @brief Used to get a type of primitive.
*/
static const char LAYER_TYPE[] = "layerType";
/**
* @ingroup ie_dev_exec_graph
* @brief The Execution node which is used to represent node in execution graph.
*
* It contains the following type of information in node runtime information:
* - ExecGraphInfoSerialization::ORIGINAL_NAMES
* - ExecGraphInfoSerialization::IMPL_TYPE
* - ExecGraphInfoSerialization::OUTPUT_PRECISIONS
* - ExecGraphInfoSerialization::PERF_COUNTER
* - ExecGraphInfoSerialization::OUTPUT_LAYOUTS
* - ExecGraphInfoSerialization::EXECUTION_ORDER
* - ExecGraphInfoSerialization::LAYER_TYPE
*/
class INFERENCE_ENGINE_API_CLASS(ExecutionNode) : public ngraph::Node {
public:
static constexpr ngraph::NodeTypeInfo type_info { "ExecutionNode", 0 };
const ngraph::NodeTypeInfo& get_type_info() const override;
/**
* A default constructor with no node inputs and 0 output ports.
*/
ExecutionNode() = default;
/**
* @brief Constructs a new execution node with a given parameters
*
* @param[in] arguments Inputs nodes
* @param[in] output_size A number of output ports
*/
ExecutionNode(const ngraph::OutputVector& arguments, size_t output_size = 1) :
Node(arguments, output_size) { }
/**
* @brief Creates a new execution node with the same state, but different input nodes
*
* @param[in] inputs The input nodes
*
* @return A newly created execution node
*/
std::shared_ptr<ngraph::Node> clone_with_new_inputs(const ngraph::OutputVector& inputs) const override {
auto cloned = std::make_shared<ExecutionNode>();
cloned->set_arguments(inputs);
for (auto kvp : get_rt_info())
cloned->get_rt_info()[kvp.first] = kvp.second;
for (size_t i = 0; i < get_output_size(); ++i)
cloned->set_output_type(i, get_output_element_type(i), get_output_partial_shape(i));
return cloned;
}
};
} // namespace ExecGraphInfoSerialization
|
/*
* FileRecordMergeMgr.cpp
*
* Created on: Mar 19, 2014
* Author: nek3d
*/
#include "FileRecordMergeMgr.h"
FileRecordMergeMgr::FileRecordMergeMgr(const string & filename)
: FileRecordMgr(filename),
_desiredStrand(ANY_STRAND),
_maxDistance(0)
{
}
//Record *FileRecordMergeMgr::allocateAndGetNextMergedRecord(WANT_STRAND_TYPE desiredStrand, int maxDistance) {
// RecordKeyVector recList;
// if (!allocateAndGetNextMergedRecord(recList, desiredStrand, maxDistance)) {
// return NULL;
// }
// deleteAllMergedItemsButKey(recList);
// return const_cast<Record *>(recList.getKey()); //want key to be non-const
//}
Record *FileRecordMergeMgr::getNextRecord(RecordKeyVector *recList)
{
//clear the recList if there is one, and if it has records
// in it.
if (recList != NULL && !recList->allClear()) {
deleteMergedRecord(*recList);
}
_mustBeForward = _desiredStrand == SAME_STRAND_FORWARD;
_mustBeReverse = _desiredStrand == SAME_STRAND_REVERSE;
Record *startRecord = tryToTakeFromStorage();
// if we couldn't use a previously stored record for starters,
//then begin with a new one that matches strand criteria.
while (startRecord == NULL) {
startRecord = FileRecordMgr::getNextRecord();
if (startRecord == NULL) { //hit EOF!!
return NULL;
}
if ((_mustBeForward && (startRecord->getStrandVal() != Record::FORWARD)) || (_mustBeReverse && (startRecord->getStrandVal() != Record::REVERSE))) {
//record is reverse, only want forward, OR record is forward, wanted reverse
deleteRecord(startRecord);
startRecord = NULL;
continue;
}
if (startRecord->getStrandVal() == Record::UNKNOWN && _desiredStrand != ANY_STRAND) {
//there is an unknown strand, but the user specified strandedness.
deleteRecord(startRecord);
startRecord = NULL;
}
}
// OK!! We have a start record! Re-evaluate strand requirements for next recored.
_mustBeForward = _desiredStrand == SAME_STRAND_FORWARD || (_desiredStrand == SAME_STRAND_EITHER && (startRecord->getStrandVal() == Record::FORWARD));
_mustBeReverse = _desiredStrand == SAME_STRAND_REVERSE || (_desiredStrand == SAME_STRAND_EITHER && (startRecord->getStrandVal() == Record::REVERSE));
bool mustKeepOpposite = (_desiredStrand == SAME_STRAND_EITHER);
const string &currChrom = startRecord->getChrName();
_foundChroms.insert(currChrom);
bool madeComposite = false;
if (recList != NULL) {
recList->push_back(startRecord);
recList->setKey(startRecord); //key of recList will just be the startRecord unless we're able to merge more.
}
Record::strandType currStrand = startRecord->getStrandVal();
bool mustMatchStrand = _desiredStrand != ANY_STRAND;
CHRPOS currEnd = startRecord->getEndPos();
//now look for more records to merge with this one.
//stop when they're out of range, not on the same chromosome, or we hit EOF.
//ignore if they don't comply with strand.
Record *nextRecord = NULL;
while (nextRecord == NULL) {
bool takenFromStorage = false;
nextRecord = mustMatchStrand ? tryToTakeFromStorage(currStrand) : tryToTakeFromStorage();
if (nextRecord == NULL) {
nextRecord = FileRecordMgr::getNextRecord();
} else {
takenFromStorage = true;
}
if (nextRecord == NULL) { // EOF hit
break;
}
//delete any record from file with an unknown strand if we are doing stranded merge, but first check
//that it's chrom was the same and it's not out of range. If either is true, stop scanning.
bool mustDelete = (mustMatchStrand && nextRecord->getStrandVal() == Record::UNKNOWN);
//check that we are still on the same chromosome.
const string &newChrom = nextRecord->getChrName();
if (newChrom != currChrom) { //hit a different chromosome.
//haven't seen this chromosome before, sort order is already enforced in the base class method.
if (!mustDelete) {
addToStorage(nextRecord);
} else {
deleteRecord(nextRecord);
}
nextRecord = NULL;
break;
}
//check whether it's in range
CHRPOS nextStart = nextRecord->getStartPos();
if (nextStart > currEnd + _maxDistance) {
//no, it's out of range.
if (!mustDelete) {
addToStorage(nextRecord);
} else {
deleteRecord(nextRecord);
}
nextRecord = NULL;
break;
}
// NOW, going back, we can delete any unknown strand records. But don't stop scanning.
if (mustDelete) {
deleteRecord(nextRecord);
nextRecord = NULL;
continue;
}
//if taken from file, and wrong strand, store or delete.
if (!takenFromStorage && ((_mustBeForward && (nextRecord->getStrandVal() != Record::FORWARD)) || (_mustBeReverse && (nextRecord->getStrandVal() != Record::REVERSE)))) {
if (mustKeepOpposite) {
addToStorage(nextRecord);
} else {
deleteRecord(nextRecord);
}
nextRecord = NULL;
continue; //get the next record
}
//ok, they're on the same chrom and in range, and the strand is good. Do a merge.
if (recList != NULL) recList->push_back(nextRecord);
madeComposite = true;
CHRPOS nextEnd = nextRecord->getEndPos();
if (nextEnd > currEnd) {
currEnd = nextEnd;
}
nextRecord = NULL;
}
if (madeComposite) {
Record *newKey = _recordMgr->allocateRecord();
(*newKey) = (*startRecord);
newKey->setEndPos(currEnd);
if (recList != NULL) recList->setKey(newKey);
_totalMergedRecordLength += currEnd - newKey->getStartPos();
return newKey;
} else {
_totalMergedRecordLength += currEnd - startRecord->getStartPos();
return startRecord;
}
// _totalMergedRecordLength += (unsigned long)(recList->getKey()->getEndPos() - recList->getKey()->getStartPos());
// return const_cast<Record *>(recList->getKey());
}
void FileRecordMergeMgr::addToStorage(Record *record) {
//if the strand requirements are strict, and the record doesn't match,
//store in the "round file".
if ((_desiredStrand == SAME_STRAND_FORWARD && record->getStrandVal() != Record::FORWARD) ||
(_desiredStrand == SAME_STRAND_REVERSE && record->getStrandVal() != Record::REVERSE) ||
(_desiredStrand != ANY_STRAND && record->getStrandVal() == Record::UNKNOWN)) {
deleteRecord(record);
return;
}
_storedRecords.push(record);
}
Record *FileRecordMergeMgr::tryToTakeFromStorage() {
Record *record = _storedRecords.top();
if (record != NULL) {
_storedRecords.pop();
}
return record;
}
Record *FileRecordMergeMgr::tryToTakeFromStorage(Record::strandType strand) {
Record *record = _storedRecords.top(strand);
if (record != NULL) {
_storedRecords.pop(strand);
}
return record;
}
void FileRecordMergeMgr::deleteMergedRecord(RecordKeyVector &recList)
{
deleteAllMergedItemsButKey(recList);
deleteRecord(recList.getKey());
recList.setKey(NULL);
}
bool FileRecordMergeMgr::eof(){
return (_fileReader->eof() && _storedRecords.empty());
}
void FileRecordMergeMgr::deleteAllMergedItemsButKey(RecordKeyVector &recList) {
//if the key is also in the list, this method won't delete it.
for (RecordKeyVector::iterator_type iter = recList.begin(); iter != recList.end(); iter = recList.next()) {
if (*iter == recList.getKey()) {
continue;
}
deleteRecord(*iter);
}
recList.clearVector();
}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "crypto_utils.h"
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/data/smart_buffer.h>
#include <vespa/vespalib/net/tls/authorization_mode.h>
#include <vespa/vespalib/net/tls/crypto_codec.h>
#include <vespa/vespalib/net/tls/statistics.h>
#include <vespa/vespalib/net/tls/tls_context.h>
#include <vespa/vespalib/net/tls/transport_security_options.h>
#include <vespa/vespalib/net/tls/impl/openssl_crypto_codec_impl.h>
#include <vespa/vespalib/net/tls/impl/openssl_tls_context_impl.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>
#include <vespa/vespalib/test/peer_policy_utils.h>
#include <iostream>
#include <stdexcept>
#include <stdlib.h>
using namespace vespalib;
using namespace vespalib::net::tls;
using namespace vespalib::net::tls::impl;
const char* decode_state_to_str(DecodeResult::State state) noexcept {
switch (state) {
case DecodeResult::State::Failed: return "Broken";
case DecodeResult::State::OK: return "OK";
case DecodeResult::State::NeedsMorePeerData: return "NeedsMorePeerData";
case DecodeResult::State::Closed: return "Closed";
}
abort();
}
const char* hs_state_to_str(HandshakeResult::State state) noexcept {
switch (state) {
case HandshakeResult::State::Failed: return "Broken";
case HandshakeResult::State::Done: return "Done";
case HandshakeResult::State::NeedsMorePeerData: return "NeedsMorePeerData";
}
abort();
}
void print_handshake_result(const char* mode, const HandshakeResult& res) {
fprintf(stderr, "(handshake) %s consumed %zu peer bytes, wrote %zu peer bytes. State: %s\n",
mode, res.bytes_consumed, res.bytes_produced,
hs_state_to_str(res.state));
}
void print_encode_result(const char* mode, const EncodeResult& res) {
fprintf(stderr, "(encode) %s read %zu plaintext, wrote %zu cipher. State: %s\n",
mode, res.bytes_consumed, res.bytes_produced,
res.failed ? "Broken! D:" : "OK");
}
void print_decode_result(const char* mode, const DecodeResult& res) {
fprintf(stderr, "(decode) %s read %zu cipher, wrote %zu plaintext. State: %s\n",
mode, res.bytes_consumed, res.bytes_produced,
decode_state_to_str(res.state));
}
struct Fixture {
TransportSecurityOptions tls_opts;
std::shared_ptr<TlsContext> tls_ctx;
std::unique_ptr<CryptoCodec> client;
std::unique_ptr<CryptoCodec> server;
SmartBuffer client_to_server;
SmartBuffer server_to_client;
Fixture()
: tls_opts(vespalib::test::make_tls_options_for_testing()),
tls_ctx(TlsContext::create_default_context(tls_opts, AuthorizationMode::Enforce)),
client(create_openssl_codec(tls_ctx, CryptoCodec::Mode::Client)),
server(create_openssl_codec(tls_ctx, CryptoCodec::Mode::Server)),
client_to_server(64 * 1024),
server_to_client(64 * 1024)
{}
~Fixture();
static TransportSecurityOptions create_options_without_own_peer_cert() {
auto source_opts = vespalib::test::make_tls_options_for_testing();
return TransportSecurityOptions(source_opts.ca_certs_pem(), "", "");
}
static std::unique_ptr<CryptoCodec> create_openssl_codec(
const TransportSecurityOptions& opts, CryptoCodec::Mode mode) {
auto ctx = TlsContext::create_default_context(opts, AuthorizationMode::Enforce);
return create_openssl_codec(ctx, mode);
}
static std::unique_ptr<CryptoCodec> create_openssl_codec(
const TransportSecurityOptions& opts,
std::shared_ptr<CertificateVerificationCallback> cert_verify_callback,
CryptoCodec::Mode mode) {
auto ctx = TlsContext::create_default_context(opts, std::move(cert_verify_callback), AuthorizationMode::Enforce);
return create_openssl_codec(ctx, mode);
}
static std::unique_ptr<CryptoCodec> create_openssl_codec(
const std::shared_ptr<TlsContext>& ctx, CryptoCodec::Mode mode) {
auto ctx_impl = std::dynamic_pointer_cast<impl::OpenSslTlsContextImpl>(ctx);
return std::make_unique<impl::OpenSslCryptoCodecImpl>(std::move(ctx_impl), mode);
}
EncodeResult do_encode(CryptoCodec& codec, Output& buffer, vespalib::stringref plaintext) {
auto out = buffer.reserve(codec.min_encode_buffer_size());
auto enc_res = codec.encode(plaintext.data(), plaintext.size(), out.data, out.size);
buffer.commit(enc_res.bytes_produced);
return enc_res;
}
DecodeResult do_decode(CryptoCodec& codec, Input& buffer, vespalib::string& out,
size_t max_bytes_produced, size_t max_bytes_consumed) {
auto in = buffer.obtain();
out.resize(max_bytes_produced);
auto to_consume = std::min(in.size, max_bytes_consumed);
auto enc_res = codec.decode(in.data, to_consume, &out[0], out.size());
buffer.evict(enc_res.bytes_consumed);
out.resize(enc_res.bytes_produced);
return enc_res;
}
EncodeResult client_encode(vespalib::stringref plaintext) {
auto res = do_encode(*client, client_to_server, plaintext);
print_encode_result("client", res);
return res;
}
EncodeResult server_encode(vespalib::stringref plaintext) {
auto res = do_encode(*server, server_to_client, plaintext);
print_encode_result("server", res);
return res;
}
DecodeResult client_decode(vespalib::string& out, size_t max_bytes_produced,
size_t max_bytes_consumed = UINT64_MAX) {
auto res = do_decode(*client, server_to_client, out, max_bytes_produced, max_bytes_consumed);
print_decode_result("client", res);
return res;
}
DecodeResult server_decode(vespalib::string& out, size_t max_bytes_produced,
size_t max_bytes_consumed = UINT64_MAX) {
auto res = do_decode(*server, client_to_server, out, max_bytes_produced, max_bytes_consumed);
print_decode_result("server", res);
return res;
}
DecodeResult client_decode_ignore_plaintext_output() {
vespalib::string dummy_decoded;
constexpr size_t dummy_max_decoded = 100;
return client_decode(dummy_decoded, dummy_max_decoded);
}
DecodeResult server_decode_ignore_plaintext_output() {
vespalib::string dummy_decoded;
constexpr size_t dummy_max_decoded = 100;
return server_decode(dummy_decoded, dummy_max_decoded);
}
EncodeResult do_half_close(CryptoCodec& codec, Output& buffer) {
auto out = buffer.reserve(codec.min_encode_buffer_size());
auto enc_res = codec.half_close(out.data, out.size);
buffer.commit(enc_res.bytes_produced);
return enc_res;
}
EncodeResult client_half_close() {
auto res = do_half_close(*client, client_to_server);
print_encode_result("client", res);
return res;
}
EncodeResult server_half_close() {
auto res = do_half_close(*server, server_to_client);
print_encode_result("server", res);
return res;
}
HandshakeResult do_handshake(CryptoCodec& codec, Input& input, Output& output) {
auto in = input.obtain();
auto out = output.reserve(codec.min_encode_buffer_size());
auto hs_result = codec.handshake(in.data, in.size, out.data, out.size);
input.evict(hs_result.bytes_consumed);
output.commit(hs_result.bytes_produced);
return hs_result;
}
bool handshake() {
HandshakeResult cli_res;
HandshakeResult serv_res;
while (!(cli_res.done() && serv_res.done())) {
cli_res = do_handshake(*client, server_to_client, client_to_server);
serv_res = do_handshake(*server, client_to_server, server_to_client);
print_handshake_result("client", cli_res);
print_handshake_result("server", serv_res);
if (cli_res.failed() || serv_res.failed()) {
return false;
}
}
return true;
}
};
Fixture::~Fixture() = default;
TEST_F("client and server can complete handshake", Fixture) {
fprintf(stderr, "Compiled with %s\n", OPENSSL_VERSION_TEXT);
EXPECT_TRUE(f.handshake());
}
TEST_F("clients and servers can send single data frame after handshake (not full duplex)", Fixture) {
ASSERT_TRUE(f.handshake());
vespalib::string client_plaintext = "Hellooo world! :D";
vespalib::string server_plaintext = "Goodbye moon~ :3";
ASSERT_FALSE(f.client_encode(client_plaintext).failed);
vespalib::string server_plaintext_out;
ASSERT_TRUE(f.server_decode(server_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(client_plaintext, server_plaintext_out);
ASSERT_FALSE(f.server_encode(server_plaintext).failed);
vespalib::string client_plaintext_out;
ASSERT_TRUE(f.client_decode(client_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(server_plaintext, client_plaintext_out);
}
TEST_F("clients and servers can send single data frame after handshake (full duplex)", Fixture) {
ASSERT_TRUE(f.handshake());
vespalib::string client_plaintext = "Greetings globe! :D";
vespalib::string server_plaintext = "Sayonara luna~ :3";
ASSERT_FALSE(f.client_encode(client_plaintext).failed);
ASSERT_FALSE(f.server_encode(server_plaintext).failed);
vespalib::string client_plaintext_out;
vespalib::string server_plaintext_out;
ASSERT_TRUE(f.server_decode(server_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(client_plaintext, server_plaintext_out);
ASSERT_TRUE(f.client_decode(client_plaintext_out, 256).frame_decoded_ok());
EXPECT_EQUAL(server_plaintext, client_plaintext_out);
}
TEST_F("short ciphertext read on decode() returns NeedsMorePeerData", Fixture) {
ASSERT_TRUE(f.handshake());
vespalib::string client_plaintext = "very secret foo";
ASSERT_FALSE(f.client_encode(client_plaintext).failed);
vespalib::string server_plaintext_out;
auto dec_res = f.server_decode(server_plaintext_out, 256, 10);
EXPECT_FALSE(dec_res.failed()); // Short read is not a failure mode
EXPECT_TRUE(dec_res.state == DecodeResult::State::NeedsMorePeerData);
}
TEST_F("Encodes larger than max frame size are split up", Fixture) {
ASSERT_TRUE(f.handshake());
constexpr auto frame_size = impl::OpenSslCryptoCodecImpl::MaximumFramePlaintextSize;
vespalib::string client_plaintext(frame_size + 50, 'X');
auto enc_res = f.client_encode(client_plaintext);
ASSERT_FALSE(enc_res.failed);
ASSERT_EQUAL(frame_size, enc_res.bytes_consumed);
auto remainder = client_plaintext.substr(frame_size);
enc_res = f.client_encode(remainder);
ASSERT_FALSE(enc_res.failed);
ASSERT_EQUAL(50u, enc_res.bytes_consumed);
// Over on the server side, we expect to decode 2 matching frames
vespalib::string server_plaintext_out;
auto dec_res = f.server_decode(server_plaintext_out, frame_size);
ASSERT_TRUE(dec_res.frame_decoded_ok());
EXPECT_EQUAL(frame_size, dec_res.bytes_produced);
vespalib::string remainder_out;
dec_res = f.server_decode(remainder_out, frame_size);
ASSERT_TRUE(dec_res.frame_decoded_ok());
EXPECT_EQUAL(50u, dec_res.bytes_produced);
EXPECT_EQUAL(client_plaintext, server_plaintext_out + remainder);
}
TEST_F("client without a certificate is rejected by server", Fixture) {
f.client = f.create_openssl_codec(f.create_options_without_own_peer_cert(), CryptoCodec::Mode::Client);
EXPECT_FALSE(f.handshake());
}
void check_half_close_encoded_ok(const EncodeResult& close_res) {
EXPECT_FALSE(close_res.failed);
EXPECT_GREATER(close_res.bytes_produced, 0u);
EXPECT_EQUAL(close_res.bytes_consumed, 0u);
}
void check_decode_peer_is_reported_closed(const DecodeResult& decoded) {
EXPECT_TRUE(decoded.closed());
EXPECT_GREATER(decoded.bytes_consumed, 0u);
EXPECT_EQUAL(decoded.bytes_produced, 0u);
}
TEST_F("Both peers can half-close their connections", Fixture) {
ASSERT_TRUE(f.handshake());
auto close_res = f.client_half_close();
check_half_close_encoded_ok(close_res);
auto decoded = f.server_decode_ignore_plaintext_output();
check_decode_peer_is_reported_closed(decoded);
close_res = f.server_half_close();
check_half_close_encoded_ok(close_res);
decoded = f.client_decode_ignore_plaintext_output();
check_decode_peer_is_reported_closed(decoded);
}
// Certificate note: public keys must be of the same type as those
// used by vespalib::test::make_tls_options_for_testing(). In this case,
// it's P-256 EC keys.
// Also note: the Subject of this CA is different from the baseline
// test CA to avoid validation errors. This also means the Issuer is
// different for the below host certificate.
constexpr const char* unknown_ca_pem = R"(-----BEGIN CERTIFICATE-----
MIIBvzCCAWYCCQDEtg8a8Y5bBzAKBggqhkjOPQQDAjBoMQswCQYDVQQGEwJVUzEU
MBIGA1UEBwwLTG9vbmV5VmlsbGUxDjAMBgNVBAoMBUFDTUUyMRcwFQYDVQQLDA5B
Q01FIHRlc3QgQ0EgMjEaMBgGA1UEAwwRYWNtZTIuZXhhbXBsZS5jb20wHhcNMTgw
OTI3MTM0NjA3WhcNNDYwMjEyMTM0NjA3WjBoMQswCQYDVQQGEwJVUzEUMBIGA1UE
BwwLTG9vbmV5VmlsbGUxDjAMBgNVBAoMBUFDTUUyMRcwFQYDVQQLDA5BQ01FIHRl
c3QgQ0EgMjEaMBgGA1UEAwwRYWNtZTIuZXhhbXBsZS5jb20wWTATBgcqhkjOPQIB
BggqhkjOPQMBBwNCAAT88ScwGmpJ4NycxZBaqgSpw+IXfeIFR1oCGpxlLaKyrdpw
Sl9SeuAyJfW4yNinzUeiuX+5hSrzly4yFrOIW/n6MAoGCCqGSM49BAMCA0cAMEQC
IGNCYvQyZm/7GgTCi55y3RWK0tEE73ivEut9V0qvlqarAiBj8IDxv+Dm0ZFlB/8E
EYn91JZORccsNSJkfIWqrGEjBA==
-----END CERTIFICATE-----)";
// Signed by unknown CA above
constexpr const char* untrusted_host_cert_pem = R"(-----BEGIN CERTIFICATE-----
MIIBrzCCAVYCCQDAZrFWZPw7djAKBggqhkjOPQQDAjBoMQswCQYDVQQGEwJVUzEU
MBIGA1UEBwwLTG9vbmV5VmlsbGUxDjAMBgNVBAoMBUFDTUUyMRcwFQYDVQQLDA5B
Q01FIHRlc3QgQ0EgMjEaMBgGA1UEAwwRYWNtZTIuZXhhbXBsZS5jb20wHhcNMTgw
OTI3MTM0NjA3WhcNNDYwMjEyMTM0NjA3WjBYMQswCQYDVQQGEwJVUzEUMBIGA1UE
BwwLTG9vbmV5VmlsbGUxGjAYBgNVBAoMEVJvYWQgUnVubmVyLCBJbmMuMRcwFQYD
VQQDDA5yci5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABMrp
YgaA3CbDCaHa5CC6Vr7TLHEPNMkLNGnr2692a57ExWk1FMzNlZfaS79b67o6zxAu
/HMiEHtseecH96UaGg4wCgYIKoZIzj0EAwIDRwAwRAIgOjiCql8VIe0/Ihyymr0a
IforjEAMmPffLdHnMJzbya8CIBKWeTzSnG7/0PE0K73vqr+OrE5V31FjvzvYpvdT
tSe+
-----END CERTIFICATE-----)";
constexpr const char* untrusted_host_key_pem = R"(-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIHwh0Is5sf4emYv0UBsHSCCMI0XCV2RzhafIQ3j1BTK0oAoGCCqGSM49
AwEHoUQDQgAEyuliBoDcJsMJodrkILpWvtMscQ80yQs0aevbr3ZrnsTFaTUUzM2V
l9pLv1vrujrPEC78cyIQe2x55wf3pRoaDg==
-----END EC PRIVATE KEY-----)";
TEST_F("client with certificate signed by untrusted CA is rejected by server", Fixture) {
TransportSecurityOptions client_opts(unknown_ca_pem, untrusted_host_cert_pem, untrusted_host_key_pem);
f.client = f.create_openssl_codec(client_opts, CryptoCodec::Mode::Client);
EXPECT_FALSE(f.handshake());
}
TEST_F("server with certificate signed by untrusted CA is rejected by client", Fixture) {
TransportSecurityOptions server_opts(unknown_ca_pem, untrusted_host_cert_pem, untrusted_host_key_pem);
f.server = f.create_openssl_codec(server_opts, CryptoCodec::Mode::Server);
EXPECT_FALSE(f.handshake());
}
TEST_F("Can specify multiple trusted CA certs in transport options", Fixture) {
auto& base_opts = f.tls_opts;
auto multi_ca_pem = base_opts.ca_certs_pem() + "\n" + unknown_ca_pem;
TransportSecurityOptions multi_ca_using_ca_1(multi_ca_pem, untrusted_host_cert_pem, untrusted_host_key_pem);
TransportSecurityOptions multi_ca_using_ca_2(multi_ca_pem, base_opts.cert_chain_pem(), base_opts.private_key_pem());
// Let client be signed by CA 1, server by CA 2. Both have the two CAs in their trust store
// so this should allow for a successful handshake.
f.client = f.create_openssl_codec(multi_ca_using_ca_1, CryptoCodec::Mode::Client);
f.server = f.create_openssl_codec(multi_ca_using_ca_2, CryptoCodec::Mode::Server);
EXPECT_TRUE(f.handshake());
}
struct CertFixture : Fixture {
CertKeyWrapper root_ca;
static CertKeyWrapper make_root_ca() {
auto dn = X509Certificate::DistinguishedName()
.country("US").state("CA").locality("Sunnyvale")
.organization("ACME, Inc.")
.organizational_unit("ACME Root CA")
.add_common_name("acme.example.com");
auto subject = X509Certificate::SubjectInfo(std::move(dn));
auto key = PrivateKey::generate_p256_ec_key();
auto params = X509Certificate::Params::self_signed(std::move(subject), key);
auto cert = X509Certificate::generate_from(std::move(params));
return {std::move(cert), std::move(key)};
}
CertFixture()
: Fixture(),
root_ca(make_root_ca())
{}
~CertFixture();
CertKeyWrapper create_ca_issued_peer_cert(const std::vector<vespalib::string>& common_names,
const std::vector<vespalib::string>& sans) {
auto dn = X509Certificate::DistinguishedName()
.country("US").state("CA").locality("Sunnyvale")
.organization("Wile E. Coyote, Ltd.")
.organizational_unit("Personal Rocketry Division");
for (auto& cn : common_names) {
dn.add_common_name(cn);
}
auto subject = X509Certificate::SubjectInfo(std::move(dn));
for (auto& san : sans) {
subject.add_subject_alt_name(san);
}
auto key = PrivateKey::generate_p256_ec_key();
auto params = X509Certificate::Params::issued_by(std::move(subject), key, root_ca.cert, root_ca.key);
auto cert = X509Certificate::generate_from(std::move(params));
return {std::move(cert), std::move(key)};
}
static std::unique_ptr<CryptoCodec> create_openssl_codec_with_authz_mode(
const TransportSecurityOptions& opts,
std::shared_ptr<CertificateVerificationCallback> cert_verify_callback,
CryptoCodec::Mode codec_mode,
AuthorizationMode authz_mode) {
auto ctx = TlsContext::create_default_context(opts, std::move(cert_verify_callback), authz_mode);
return create_openssl_codec(ctx, codec_mode);
}
void reset_client_with_cert_opts(const CertKeyWrapper& ck, AuthorizedPeers authorized) {
TransportSecurityOptions client_opts(root_ca.cert->to_pem(), ck.cert->to_pem(),
ck.key->private_to_pem(), std::move(authorized));
client = create_openssl_codec(client_opts, CryptoCodec::Mode::Client);
}
void reset_client_with_cert_opts(const CertKeyWrapper& ck, std::shared_ptr<CertificateVerificationCallback> cert_cb) {
TransportSecurityOptions client_opts(root_ca.cert->to_pem(), ck.cert->to_pem(), ck.key->private_to_pem());
client = create_openssl_codec(client_opts, std::move(cert_cb), CryptoCodec::Mode::Client);
}
void reset_server_with_cert_opts(const CertKeyWrapper& ck, AuthorizedPeers authorized) {
TransportSecurityOptions server_opts(root_ca.cert->to_pem(), ck.cert->to_pem(),
ck.key->private_to_pem(), std::move(authorized));
server = create_openssl_codec(server_opts, CryptoCodec::Mode::Server);
}
void reset_server_with_cert_opts(const CertKeyWrapper& ck, std::shared_ptr<CertificateVerificationCallback> cert_cb) {
TransportSecurityOptions server_opts(root_ca.cert->to_pem(), ck.cert->to_pem(), ck.key->private_to_pem());
server = create_openssl_codec(server_opts, std::move(cert_cb), CryptoCodec::Mode::Server);
}
void reset_server_with_cert_opts(const CertKeyWrapper& ck,
std::shared_ptr<CertificateVerificationCallback> cert_cb,
AuthorizationMode authz_mode) {
TransportSecurityOptions server_opts(root_ca.cert->to_pem(), ck.cert->to_pem(), ck.key->private_to_pem());
server = create_openssl_codec_with_authz_mode(server_opts, std::move(cert_cb), CryptoCodec::Mode::Server, authz_mode);
}
};
CertFixture::~CertFixture() = default;
struct PrintingCertificateCallback : CertificateVerificationCallback {
bool verify(const PeerCredentials& peer_creds) const override {
if (!peer_creds.common_name.empty()) {
fprintf(stderr, "Got a CN: %s\n", peer_creds.common_name.c_str());
}
for (auto& dns : peer_creds.dns_sans) {
fprintf(stderr, "Got a DNS SAN entry: %s\n", dns.c_str());
}
return true;
}
};
// Single-use mock verifier
struct MockCertificateCallback : CertificateVerificationCallback {
mutable PeerCredentials creds; // only used in single thread testing context
bool verify(const PeerCredentials& peer_creds) const override {
creds = peer_creds;
return true;
}
};
struct AlwaysFailVerifyCallback : CertificateVerificationCallback {
bool verify([[maybe_unused]] const PeerCredentials& peer_creds) const override {
fprintf(stderr, "Rejecting certificate, none shall pass!\n");
return false;
}
};
struct ExceptionThrowingCallback : CertificateVerificationCallback {
bool verify([[maybe_unused]] const PeerCredentials& peer_creds) const override {
throw std::runtime_error("oh no what is going on");
}
};
TEST_F("Certificate verification callback returning false breaks handshake", CertFixture) {
auto ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
f.reset_client_with_cert_opts(ck, std::make_shared<PrintingCertificateCallback>());
f.reset_server_with_cert_opts(ck, std::make_shared<AlwaysFailVerifyCallback>());
EXPECT_FALSE(f.handshake());
}
TEST_F("Exception during verification callback processing breaks handshake", CertFixture) {
auto ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
f.reset_client_with_cert_opts(ck, std::make_shared<PrintingCertificateCallback>());
f.reset_server_with_cert_opts(ck, std::make_shared<ExceptionThrowingCallback>());
EXPECT_FALSE(f.handshake());
}
TEST_F("certificate verification callback observes CN and DNS SANs", CertFixture) {
auto ck = f.create_ca_issued_peer_cert(
{{"rockets.wile.example.com"}},
{{"DNS:crash.wile.example.com"}, {"DNS:burn.wile.example.com"}});
fprintf(stderr, "certs:\n%s%s\n", f.root_ca.cert->to_pem().c_str(), ck.cert->to_pem().c_str());
f.reset_client_with_cert_opts(ck, std::make_shared<PrintingCertificateCallback>());
auto server_cb = std::make_shared<MockCertificateCallback>();
f.reset_server_with_cert_opts(ck, server_cb);
ASSERT_TRUE(f.handshake());
auto& creds = server_cb->creds;
EXPECT_EQUAL("rockets.wile.example.com", creds.common_name);
ASSERT_EQUAL(2u, creds.dns_sans.size());
EXPECT_EQUAL("crash.wile.example.com", creds.dns_sans[0]);
EXPECT_EQUAL("burn.wile.example.com", creds.dns_sans[1]);
}
TEST_F("last occurring CN is given to verification callback if multiple CNs are present", CertFixture) {
auto ck = f.create_ca_issued_peer_cert(
{{"foo.wile.example.com"}, {"bar.wile.example.com"}, {"baz.wile.example.com"}}, {});
f.reset_client_with_cert_opts(ck, std::make_shared<PrintingCertificateCallback>());
auto server_cb = std::make_shared<MockCertificateCallback>();
f.reset_server_with_cert_opts(ck, server_cb);
ASSERT_TRUE(f.handshake());
auto& creds = server_cb->creds;
EXPECT_EQUAL("baz.wile.example.com", creds.common_name);
}
// TODO we are likely to want IPADDR SANs at some point
TEST_F("Only DNS SANs are enumerated", CertFixture) {
auto ck = f.create_ca_issued_peer_cert({}, {"IP:127.0.0.1"});
f.reset_client_with_cert_opts(ck, std::make_shared<PrintingCertificateCallback>());
auto server_cb = std::make_shared<MockCertificateCallback>();
f.reset_server_with_cert_opts(ck, server_cb);
ASSERT_TRUE(f.handshake());
EXPECT_EQUAL(0u, server_cb->creds.dns_sans.size());
}
// We don't test too many combinations of peer policies here, only that
// the wiring is set up. Verification logic is tested elsewhere.
TEST_F("Client rejects server with certificate that DOES NOT match peer policy", CertFixture) {
auto client_ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
auto authorized = authorized_peers({policy_with({required_san_dns("crash.wile.example.com")})});
f.reset_client_with_cert_opts(client_ck, std::move(authorized));
// crash.wile.example.com not present in certificate
auto server_ck = f.create_ca_issued_peer_cert(
{}, {{"DNS:birdseed.wile.example.com"}, {"DNS:roadrunner.wile.example.com"}});
f.reset_server_with_cert_opts(server_ck, AuthorizedPeers::allow_all_authenticated());
EXPECT_FALSE(f.handshake());
}
TEST_F("Client allows server with certificate that DOES match peer policy", CertFixture) {
auto client_ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
auto authorized = authorized_peers({policy_with({required_san_dns("crash.wile.example.com")})});
f.reset_client_with_cert_opts(client_ck, std::move(authorized));
auto server_ck = f.create_ca_issued_peer_cert(
{}, {{"DNS:birdseed.wile.example.com"}, {"DNS:crash.wile.example.com"}});
f.reset_server_with_cert_opts(server_ck, AuthorizedPeers::allow_all_authenticated());
EXPECT_TRUE(f.handshake());
}
TEST_F("Server rejects client with certificate that DOES NOT match peer policy", CertFixture) {
auto server_ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
auto authorized = authorized_peers({policy_with({required_san_dns("crash.wile.example.com")})});
f.reset_server_with_cert_opts(server_ck, std::move(authorized));
// crash.wile.example.com not present in certificate
auto client_ck = f.create_ca_issued_peer_cert(
{}, {{"DNS:birdseed.wile.example.com"}, {"DNS:roadrunner.wile.example.com"}});
f.reset_client_with_cert_opts(client_ck, AuthorizedPeers::allow_all_authenticated());
EXPECT_FALSE(f.handshake());
}
TEST_F("Server allows client with certificate that DOES match peer policy", CertFixture) {
auto server_ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
auto authorized = authorized_peers({policy_with({required_san_dns("crash.wile.example.com")})});
f.reset_server_with_cert_opts(server_ck, std::move(authorized));
auto client_ck = f.create_ca_issued_peer_cert(
{}, {{"DNS:birdseed.wile.example.com"}, {"DNS:crash.wile.example.com"}});
f.reset_client_with_cert_opts(client_ck, AuthorizedPeers::allow_all_authenticated());
EXPECT_TRUE(f.handshake());
}
void reset_peers_with_server_authz_mode(CertFixture& f, AuthorizationMode authz_mode) {
auto ck = f.create_ca_issued_peer_cert({"hello.world.example.com"}, {});
f.reset_client_with_cert_opts(ck, std::make_shared<PrintingCertificateCallback>());
f.reset_server_with_cert_opts(ck, std::make_shared<AlwaysFailVerifyCallback>(), authz_mode);
}
TEST_F("Log-only insecure authorization mode ignores verification result", CertFixture) {
reset_peers_with_server_authz_mode(f, AuthorizationMode::LogOnly);
EXPECT_TRUE(f.handshake());
}
TEST_F("Disabled insecure authorization mode ignores verification result", CertFixture) {
reset_peers_with_server_authz_mode(f, AuthorizationMode::Disable);
EXPECT_TRUE(f.handshake());
}
TEST_F("Failure statistics are incremented on authorization failures", CertFixture) {
reset_peers_with_server_authz_mode(f, AuthorizationMode::Enforce);
auto server_before = ConnectionStatistics::get(true).snapshot();
auto client_before = ConnectionStatistics::get(false).snapshot();
EXPECT_FALSE(f.handshake());
auto server_stats = ConnectionStatistics::get(true).snapshot().subtract(server_before);
auto client_stats = ConnectionStatistics::get(false).snapshot().subtract(client_before);
EXPECT_EQUAL(1u, server_stats.invalid_peer_credentials);
EXPECT_EQUAL(0u, client_stats.invalid_peer_credentials);
EXPECT_EQUAL(1u, server_stats.failed_tls_handshakes);
EXPECT_EQUAL(0u, server_stats.tls_connections);
EXPECT_EQUAL(0u, client_stats.tls_connections);
}
TEST_F("Success statistics are incremented on OK authorization", CertFixture) {
reset_peers_with_server_authz_mode(f, AuthorizationMode::Disable);
auto server_before = ConnectionStatistics::get(true).snapshot();
auto client_before = ConnectionStatistics::get(false).snapshot();
EXPECT_TRUE(f.handshake());
auto server_stats = ConnectionStatistics::get(true).snapshot().subtract(server_before);
auto client_stats = ConnectionStatistics::get(false).snapshot().subtract(client_before);
EXPECT_EQUAL(0u, server_stats.invalid_peer_credentials);
EXPECT_EQUAL(0u, client_stats.invalid_peer_credentials);
EXPECT_EQUAL(0u, server_stats.failed_tls_handshakes);
EXPECT_EQUAL(0u, client_stats.failed_tls_handshakes);
EXPECT_EQUAL(1u, server_stats.tls_connections);
EXPECT_EQUAL(1u, client_stats.tls_connections);
}
// TODO we can't test embedded nulls since the OpenSSL v3 extension APIs
// take in null terminated strings as arguments... :I
/*
* TODO tests:
* - handshakes with multi frame writes
* - completed handshake with pipelined data frame
* - short plaintext writes on decode (.. if we even want to support this..)
* - short ciphertext write on encode (.. if we even want to support this..)
* - detection of peer shutdown session
*/
TEST_MAIN() { TEST_RUN_ALL(); }
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kernels/Unpack.h"
#include "kernels/TestUtils.h"
namespace luci_interpreter
{
namespace kernels
{
namespace
{
using namespace testing;
template <typename T>
void Check(int axis, Shape input_shape, std::initializer_list<T> input_data,
const std::vector<std::initializer_list<int32_t>> &exp_output_shape,
std::vector<std::initializer_list<T>> exp_output_data)
{
constexpr DataType element_type = getElementType<T>();
const int num_outputs = input_shape.dim(axis < 0 ? axis + input_shape.num_dims() : axis);
Tensor input_tensor = makeInputTensor<element_type>(input_shape, input_data);
std::vector<Tensor> output_tensors;
output_tensors.reserve(num_outputs);
for (int i = 0; i < num_outputs; ++i)
{
output_tensors.push_back(makeOutputTensor(element_type));
}
std::vector<Tensor *> output_tensor_ptrs(num_outputs);
for (int i = 0; i < num_outputs; ++i)
{
output_tensor_ptrs[i] = &output_tensors[i];
}
UnpackParams params{};
params.axis = axis;
Unpack kernel(&input_tensor, std::move(output_tensor_ptrs), params);
kernel.configure();
kernel.execute();
for (int i = 0; i < num_outputs; ++i)
{
EXPECT_THAT(extractTensorData<T>(output_tensors[i]),
::testing::ElementsAreArray(exp_output_data[i]));
}
}
template <typename T> class UnpackTest : public ::testing::Test
{
};
using DataTypes = ::testing::Types<float, uint8_t>;
TYPED_TEST_CASE(UnpackTest, DataTypes);
TYPED_TEST(UnpackTest, ThreeOutputs)
{
Check<TypeParam>(/*axis=*/0, /*input_shape=*/{3, 2},
/*input_data=*/{1, 2, 3, 4, 5, 6},
/*exp_output_shape=*/{{2}, {2}, {2}},
/*exp_output_data=*/{{1, 2}, {3, 4}, {5, 6}});
}
TYPED_TEST(UnpackTest, ThreeOutputsAxisOne)
{
Check<TypeParam>(/*axis=*/1, /*input_shape=*/{3, 2},
/*input_data=*/{1, 2, 3, 4, 5, 6},
/*exp_output_shape=*/{{3}, {3}},
/*exp_output_data=*/{{1, 3, 5}, {2, 4, 6}});
}
TYPED_TEST(UnpackTest, ThreeOutputsNegativeAxisOne)
{
Check<TypeParam>(/*axis=*/-1, /*input_shape=*/{3, 2},
/*input_data=*/{1, 2, 3, 4, 5, 6},
/*exp_output_shape=*/{{3}, {3}},
/*exp_output_data=*/{{1, 3, 5}, {2, 4, 6}});
}
TYPED_TEST(UnpackTest, ThreeOutputsNegativeAxisTwo)
{
Check<TypeParam>(/*axis=*/-2, /*input_shape=*/{3, 2},
/*input_data=*/{1, 2, 3, 4, 5, 6},
/*exp_output_shape=*/{{2}, {2}, {2}},
/*exp_output_data=*/{{1, 2}, {3, 4}, {5, 6}});
}
TYPED_TEST(UnpackTest, OneOutput)
{
Check<TypeParam>(/*axis=*/0, /*input_shape=*/{1, 6},
/*input_data=*/{1, 2, 3, 4, 5, 6},
/*exp_output_shape=*/{{6}},
/*exp_output_data=*/{{1, 2, 3, 4, 5, 6}});
}
TYPED_TEST(UnpackTest, ThreeDimensionsTwoOutputs)
{
Check<TypeParam>(/*axis=*/2, /*input_shape=*/{2, 2, 2},
/*input_data=*/{1, 2, 3, 4, 5, 6, 7, 8},
/*exp_output_shape=*/{{2, 2}, {2, 2}},
/*exp_output_data=*/{{1, 3, 5, 7}, {2, 4, 6, 8}});
}
TYPED_TEST(UnpackTest, FiveDimensionsTwoOutputs)
{
Check<TypeParam>(
/*axis=*/2, /*input_shape=*/{2, 2, 2, 2, 1},
/*input_data=*/{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
/*exp_output_shape=*/{{2, 2, 2, 1}, {2, 2, 2, 1}},
/*exp_output_data=*/
{{1, 2, 5, 6, 9, 10, 13, 14}, {3, 4, 7, 8, 11, 12, 15, 16}});
}
TYPED_TEST(UnpackTest, VectorToScalar)
{
Check<TypeParam>(/*axis=*/0, /*input_shape=*/{5},
/*input_data=*/{1, 2, 3, 4, 5},
/*exp_output_shape=*/{{}, {}, {}, {}, {}},
/*exp_output_data=*/{{1}, {2}, {3}, {4}, {5}});
}
} // namespace
} // namespace kernels
} // namespace luci_interpreter
|
/*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2008 Hartmut Kaiser. 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)
=============================================================================*/
#if !defined(BOOST_WAVE_CPP_THROW_HPP_INCLUDED)
#define BOOST_WAVE_CPP_THROW_HPP_INCLUDED
#include <string>
#include <boost/throw_exception.hpp>
///////////////////////////////////////////////////////////////////////////////
// helper macro for throwing exceptions
#if !defined(BOOST_WAVE_THROW)
#ifdef BOOST_NO_STRINGSTREAM
#include <strstream>
#define BOOST_WAVE_THROW(cls, code, msg, act_pos) \
{ \
using namespace boost::wave; \
std::strstream stream; \
stream << cls::severity_text(cls::code) << ": " \
<< cls::error_text(cls::code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
std::string throwmsg = stream.str(); stream.freeze(false); \
boost::throw_exception(cls(throwmsg.c_str(), cls::code, \
(act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str())); \
} \
/**/
#define BOOST_WAVE_THROW_CTX(ctx, cls, code, msg, act_pos) \
{ \
using namespace boost::wave; \
std::strstream stream; \
stream << cls::severity_text(cls::code) << ": " \
<< cls::error_text(cls::code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
std::string throwmsg = stream.str(); stream.freeze(false); \
ctx.get_hooks().throw_exception(ctx, cls(throwmsg.c_str(), cls::code, \
(act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str())); \
} \
/**/
#else
#include <sstream>
#define BOOST_WAVE_THROW(cls, code, msg, act_pos) \
{ \
using namespace boost::wave; \
std::stringstream stream; \
stream << cls::severity_text(cls::code) << ": " \
<< cls::error_text(cls::code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
boost::throw_exception(cls(stream.str().c_str(), cls::code, \
(act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str())); \
} \
/**/
#define BOOST_WAVE_THROW_CTX(ctx, cls, code, msg, act_pos) \
{ \
using namespace boost::wave; \
std::stringstream stream; \
stream << cls::severity_text(cls::code) << ": " \
<< cls::error_text(cls::code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
ctx.get_hooks().throw_exception(ctx, cls(stream.str().c_str(), \
cls::code, (act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str())); \
} \
/**/
#endif // BOOST_NO_STRINGSTREAM
#endif // BOOST_WAVE_THROW
///////////////////////////////////////////////////////////////////////////////
// helper macro for throwing exceptions with additional parameter
#if !defined(BOOST_WAVE_THROW_NAME)
#ifdef BOOST_NO_STRINGSTREAM
#include <strstream>
#define BOOST_WAVE_THROW_NAME_CTX(ctx, cls, code, msg, act_pos, name) \
{ \
using namespace boost::wave; \
std::strstream stream; \
stream << cls::severity_text(cls::code) << ": " \
<< cls::error_text(cls::code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
std::string throwmsg = stream.str(); stream.freeze(false); \
ctx.get_hooks().throw_exception(ctx, cls(throwmsg.c_str(), cls::code, \
(act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str(), (name))); \
} \
/**/
#else
#include <sstream>
#define BOOST_WAVE_THROW_NAME_CTX(ctx, cls, code, msg, act_pos, name) \
{ \
using namespace boost::wave; \
std::stringstream stream; \
stream << cls::severity_text(cls::code) << ": " \
<< cls::error_text(cls::code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
ctx.get_hooks().throw_exception(ctx, cls(stream.str().c_str(), \
cls::code, (act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str(), (name))); \
} \
/**/
#endif // BOOST_NO_STRINGSTREAM
#endif // BOOST_WAVE_THROW_NAME
///////////////////////////////////////////////////////////////////////////////
// helper macro for throwing exceptions with additional parameter
#if !defined(BOOST_WAVE_THROW_VAR)
#ifdef BOOST_NO_STRINGSTREAM
#include <strstream>
#define BOOST_WAVE_THROW_VAR_CTX(ctx, cls, code, msg, act_pos) \
{ \
using namespace boost::wave; \
std::strstream stream; \
stream << cls::severity_text(code) << ": " \
<< cls::error_text(code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
std::string throwmsg = stream.str(); stream.freeze(false); \
ctx.get_hooks().throw_exception(ctx, cls(throwmsg.c_str(), code, \
(act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str())); \
} \
/**/
#else
#include <sstream>
#define BOOST_WAVE_THROW_VAR_CTX(ctx, cls, code, msg, act_pos) \
{ \
using namespace boost::wave; \
std::stringstream stream; \
stream << cls::severity_text(code) << ": " \
<< cls::error_text(code); \
if ((msg)[0] != 0) stream << ": " << (msg); \
stream << std::ends; \
ctx.get_hooks().throw_exception(ctx, cls(stream.str().c_str(), code, \
(act_pos).get_line(), (act_pos).get_column(), \
(act_pos).get_file().c_str())); \
} \
/**/
#endif // BOOST_NO_STRINGSTREAM
#endif // BOOST_WAVE_THROW_VAR
#endif // !defined(BOOST_WAVE_CPP_THROW_HPP_INCLUDED)
|
/*
* Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#include "SpecificTeamDebugInfo.h"
SpecificTeamDebugInfo::~SpecificTeamDebugInfo()
{
}
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file SHA3.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* The FixedHash fixed-size "hash" container type.
*/
#pragma once
#include <string>
#include <graphene/utilities/FixedHash.hpp>
#include <graphene/utilities/vector_ref.hpp>
namespace graphene { namespace utilities {
// Keccak-256 convenience routines.
/// Calculate Keccak-256 hash of the given input and load it into the given output.
/// @returns false if o_output.size() != 32.
bool keccak256(bytesConstRef _input, bytesRef o_output);
/// Calculate Keccak-256 hash of the given input, returning as a 256-bit hash.
inline h256 keccak256(bytesConstRef _input) { h256 ret; keccak256(_input, ret.ref()); return ret; }
/// Calculate Keccak-256 hash of the given input, returning as a 256-bit hash.
inline h256 keccak256(bytes const& _input) { return keccak256(bytesConstRef(&_input)); }
/// Calculate Keccak-256 hash of the given input (presented as a binary-filled string), returning as a 256-bit hash.
inline h256 keccak256(std::string const& _input) { return keccak256(bytesConstRef(_input)); }
/// Calculate Keccak-256 hash of the given input (presented as a FixedHash), returns a 256-bit hash.
template<unsigned N> inline h256 keccak256(FixedHash<N> const& _input) { return keccak256(_input.ref()); }
} }
|
#include <bits/stdc++.h>
using namespace std;
//Problem Code/Link:
//Codechef profile: @saubhagya0111
//Codeforces profile: @saubhagya011
#define fio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
#define endl "\n"
#define incr_loop(i, n) for (i = 0; i < n; i++)
#define decr_loop(i, n) for (i = n; i > 0; i--)
#define nested_incr_loop(a, b) for (int j = a; j < b; j++)
#define nested_decr_loop(a, b) for (int j = b; j > a; --j)
typedef long long ll;
#define pb push_back
#define ppb pop_back
#define MP make_pair
#define sort_all(v) sort(all(v));
#define PI 3.141592653589793238462
#define space cout << ' ';
#define gcd(a, b) __gcd(a, b);
#define all(x) x.begin(), x.end()
#define in(x) cin >> x;
#define in2(x, y) cin >> x >> y;
#define in3(x, y, z) cin >> x >> y >> z;
#define out(x) cout << x;
#define out2(x, y) cout << x << ' ' << y;
#define out3(x, y, z) cout << x << ' ' << y << ' ' << z;
#define line cout << endl;
#define string_in(x) getline(cin, x)
#define f first
#define s second
typedef vector<int> vi;
typedef vector<char> vc;
typedef set<int> si;
typedef set<char> scr;
typedef set<string> sst;
typedef vector<ll> vll;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef pair<int, int> pii;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
const int mod = 1'000'000'007;
const int N = 3e5, M = N;
/************************************/
void solution()
{
int i = 0, j, n, m, n1 = 0, element, a, b, flag = 0;
in(n);
vi v;
while (v.size() != n)
{
i++;
if (i % 10 != 3 && i % 3 != 0)
{
v.pb(i);
}
}
out(v[n - 1]);
line;
}
/************************************/
int main()
{
fio;
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
int tt = 1;
in(tt);
while (tt--)
{
solution();
}
return 0;
}
|
// Copyright 2013, Ji Zhang, Carnegie Mellon University
// Further contributions copyright (c) 2016, Southwest Research Institute
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE 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.
//
// This is an implementation of the algorithm described in the following papers:
// J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time.
// Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014.
// T. Shan and B. Englot. LeGO-LOAM: Lightweight and Ground-Optimized Lidar Odometry and Mapping on Variable Terrain
// IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS). October 2018.
/*
总体流程:
(特征提取部分)订阅传感器数据->运动畸变去除->曲率计算->去除瑕点->提取边、平面特征->发布特征点云;
(特征关联部分)将IMU信息作为先验->根据线特征、面特征计算位姿变换->联合IMU数据进行位姿更新->发布里程计信息
由于已经获取前后两帧的角点和平面点特征点云,因此进行帧间点云匹配,则可获取相邻两帧平移旋转变换,由初始位姿进行累计,从而获得激光里程计信息。
lego-loam采用将两次即两种特征点分别匹配,平面匹配和2维位姿匹配。
其中LM优化的流程为构建约束方程 -> 约束方程求偏导构建Jaccobian矩阵 -> L-M求解。
*/
#include "utility.h"
class FeatureAssociation{
private:
ros::NodeHandle nh;
ros::Subscriber subLaserCloud;
ros::Subscriber subLaserCloudInfo;
ros::Subscriber subOutlierCloud;
ros::Subscriber subImu;
ros::Publisher pubCornerPointsSharp;
ros::Publisher pubCornerPointsLessSharp;
ros::Publisher pubSurfPointsFlat;
ros::Publisher pubSurfPointsLessFlat;
pcl::PointCloud<PointType>::Ptr segmentedCloud;
pcl::PointCloud<PointType>::Ptr outlierCloud;
pcl::PointCloud<PointType>::Ptr cornerPointsSharp;
pcl::PointCloud<PointType>::Ptr cornerPointsLessSharp;
pcl::PointCloud<PointType>::Ptr surfPointsFlat;
pcl::PointCloud<PointType>::Ptr surfPointsLessFlat;
pcl::PointCloud<PointType>::Ptr surfPointsLessFlatScan;
pcl::PointCloud<PointType>::Ptr surfPointsLessFlatScanDS;
pcl::VoxelGrid<PointType> downSizeFilter;
double timeScanCur;
double timeNewSegmentedCloud;
double timeNewSegmentedCloudInfo;
double timeNewOutlierCloud;
bool newSegmentedCloud;
bool newSegmentedCloudInfo;
bool newOutlierCloud;
cloud_msgs::cloud_info segInfo;
std_msgs::Header cloudHeader;
int systemInitCount;
bool systemInited;
std::vector<smoothness_t> cloudSmoothness;
float *cloudCurvature;
int *cloudNeighborPicked;
int *cloudLabel;
int imuPointerFront;
int imuPointerLast;
int imuPointerLastIteration;
float imuRollStart, imuPitchStart, imuYawStart;
float cosImuRollStart, cosImuPitchStart, cosImuYawStart, sinImuRollStart, sinImuPitchStart, sinImuYawStart;
float imuRollCur, imuPitchCur, imuYawCur;
float imuVeloXStart, imuVeloYStart, imuVeloZStart;
float imuShiftXStart, imuShiftYStart, imuShiftZStart;
float imuVeloXCur, imuVeloYCur, imuVeloZCur;
float imuShiftXCur, imuShiftYCur, imuShiftZCur;
float imuShiftFromStartXCur, imuShiftFromStartYCur, imuShiftFromStartZCur;
float imuVeloFromStartXCur, imuVeloFromStartYCur, imuVeloFromStartZCur;
float imuAngularRotationXCur, imuAngularRotationYCur, imuAngularRotationZCur;
float imuAngularRotationXLast, imuAngularRotationYLast, imuAngularRotationZLast;
float imuAngularFromStartX, imuAngularFromStartY, imuAngularFromStartZ;
double imuTime[imuQueLength];
float imuRoll[imuQueLength];
float imuPitch[imuQueLength];
float imuYaw[imuQueLength];
float imuAccX[imuQueLength];
float imuAccY[imuQueLength];
float imuAccZ[imuQueLength];
float imuVeloX[imuQueLength];
float imuVeloY[imuQueLength];
float imuVeloZ[imuQueLength];
float imuShiftX[imuQueLength];
float imuShiftY[imuQueLength];
float imuShiftZ[imuQueLength];
float imuAngularVeloX[imuQueLength];
float imuAngularVeloY[imuQueLength];
float imuAngularVeloZ[imuQueLength];
float imuAngularRotationX[imuQueLength];
float imuAngularRotationY[imuQueLength];
float imuAngularRotationZ[imuQueLength];
ros::Publisher pubLaserCloudCornerLast;
ros::Publisher pubLaserCloudSurfLast;
ros::Publisher pubLaserOdometry;
ros::Publisher pubOutlierCloudLast;
int skipFrameNum;
bool systemInitedLM;
int laserCloudCornerLastNum;
int laserCloudSurfLastNum;
int *pointSelCornerInd;
float *pointSearchCornerInd1;
float *pointSearchCornerInd2;
int *pointSelSurfInd;
float *pointSearchSurfInd1;
float *pointSearchSurfInd2;
float *pointSearchSurfInd3;
float transformCur[6];
float transformSum[6];
float imuRollLast, imuPitchLast, imuYawLast;
float imuShiftFromStartX, imuShiftFromStartY, imuShiftFromStartZ;
float imuVeloFromStartX, imuVeloFromStartY, imuVeloFromStartZ;
pcl::PointCloud<PointType>::Ptr laserCloudCornerLast;
pcl::PointCloud<PointType>::Ptr laserCloudSurfLast;
pcl::PointCloud<PointType>::Ptr laserCloudOri;
pcl::PointCloud<PointType>::Ptr coeffSel;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeCornerLast;
pcl::KdTreeFLANN<PointType>::Ptr kdtreeSurfLast;
std::vector<int> pointSearchInd;
std::vector<float> pointSearchSqDis;
PointType pointOri, pointSel, tripod1, tripod2, tripod3, pointProj, coeff;
nav_msgs::Odometry laserOdometry;
tf::TransformBroadcaster tfBroadcaster;
tf::StampedTransform laserOdometryTrans;
bool isDegenerate;
cv::Mat matP;
int frameCount;
public:
FeatureAssociation():
nh("~")
{
subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>("/segmented_cloud", 1, &FeatureAssociation::laserCloudHandler, this);
subLaserCloudInfo = nh.subscribe<cloud_msgs::cloud_info>("/segmented_cloud_info", 1, &FeatureAssociation::laserCloudInfoHandler, this);
subOutlierCloud = nh.subscribe<sensor_msgs::PointCloud2>("/outlier_cloud", 1, &FeatureAssociation::outlierCloudHandler, this);
subImu = nh.subscribe<sensor_msgs::Imu>(imuTopic, 50, &FeatureAssociation::imuHandler, this);
pubCornerPointsSharp = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_sharp", 1);
pubCornerPointsLessSharp = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_less_sharp", 1);
pubSurfPointsFlat = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_flat", 1);
pubSurfPointsLessFlat = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_less_flat", 1);
pubLaserCloudCornerLast = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_corner_last", 2);
pubLaserCloudSurfLast = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_surf_last", 2);
pubOutlierCloudLast = nh.advertise<sensor_msgs::PointCloud2>("/outlier_cloud_last", 2);
pubLaserOdometry = nh.advertise<nav_msgs::Odometry> ("/laser_odom_to_init", 5);
initializationValue();
}
void initializationValue()
{
cloudCurvature = new float[N_SCAN*Horizon_SCAN];
cloudNeighborPicked = new int[N_SCAN*Horizon_SCAN];
cloudLabel = new int[N_SCAN*Horizon_SCAN];
pointSelCornerInd = new int[N_SCAN*Horizon_SCAN];
pointSearchCornerInd1 = new float[N_SCAN*Horizon_SCAN];
pointSearchCornerInd2 = new float[N_SCAN*Horizon_SCAN];
pointSelSurfInd = new int[N_SCAN*Horizon_SCAN];
pointSearchSurfInd1 = new float[N_SCAN*Horizon_SCAN];
pointSearchSurfInd2 = new float[N_SCAN*Horizon_SCAN];
pointSearchSurfInd3 = new float[N_SCAN*Horizon_SCAN];
cloudSmoothness.resize(N_SCAN*Horizon_SCAN);
downSizeFilter.setLeafSize(0.2, 0.2, 0.2);
segmentedCloud.reset(new pcl::PointCloud<PointType>());
outlierCloud.reset(new pcl::PointCloud<PointType>());
cornerPointsSharp.reset(new pcl::PointCloud<PointType>());
cornerPointsLessSharp.reset(new pcl::PointCloud<PointType>());
surfPointsFlat.reset(new pcl::PointCloud<PointType>());
surfPointsLessFlat.reset(new pcl::PointCloud<PointType>());
surfPointsLessFlatScan.reset(new pcl::PointCloud<PointType>());
surfPointsLessFlatScanDS.reset(new pcl::PointCloud<PointType>());
timeScanCur = 0;
timeNewSegmentedCloud = 0;
timeNewSegmentedCloudInfo = 0;
timeNewOutlierCloud = 0;
newSegmentedCloud = false;
newSegmentedCloudInfo = false;
newOutlierCloud = false;
systemInitCount = 0;
systemInited = false;
imuPointerFront = 0;
imuPointerLast = -1;
imuPointerLastIteration = 0;
imuRollStart = 0; imuPitchStart = 0; imuYawStart = 0;
cosImuRollStart = 0; cosImuPitchStart = 0; cosImuYawStart = 0;
sinImuRollStart = 0; sinImuPitchStart = 0; sinImuYawStart = 0;
imuRollCur = 0; imuPitchCur = 0; imuYawCur = 0;
imuVeloXStart = 0; imuVeloYStart = 0; imuVeloZStart = 0;
imuShiftXStart = 0; imuShiftYStart = 0; imuShiftZStart = 0;
imuVeloXCur = 0; imuVeloYCur = 0; imuVeloZCur = 0;
imuShiftXCur = 0; imuShiftYCur = 0; imuShiftZCur = 0;
imuShiftFromStartXCur = 0; imuShiftFromStartYCur = 0; imuShiftFromStartZCur = 0;
imuVeloFromStartXCur = 0; imuVeloFromStartYCur = 0; imuVeloFromStartZCur = 0;
imuAngularRotationXCur = 0; imuAngularRotationYCur = 0; imuAngularRotationZCur = 0;
imuAngularRotationXLast = 0; imuAngularRotationYLast = 0; imuAngularRotationZLast = 0;
imuAngularFromStartX = 0; imuAngularFromStartY = 0; imuAngularFromStartZ = 0;
for (int i = 0; i < imuQueLength; ++i)
{
imuTime[i] = 0;
imuRoll[i] = 0; imuPitch[i] = 0; imuYaw[i] = 0;
imuAccX[i] = 0; imuAccY[i] = 0; imuAccZ[i] = 0;
imuVeloX[i] = 0; imuVeloY[i] = 0; imuVeloZ[i] = 0;
imuShiftX[i] = 0; imuShiftY[i] = 0; imuShiftZ[i] = 0;
imuAngularVeloX[i] = 0; imuAngularVeloY[i] = 0; imuAngularVeloZ[i] = 0;
imuAngularRotationX[i] = 0; imuAngularRotationY[i] = 0; imuAngularRotationZ[i] = 0;
}
skipFrameNum = 1;
for (int i = 0; i < 6; ++i){
transformCur[i] = 0;
transformSum[i] = 0;
}
systemInitedLM = false;
imuRollLast = 0; imuPitchLast = 0; imuYawLast = 0;
imuShiftFromStartX = 0; imuShiftFromStartY = 0; imuShiftFromStartZ = 0;
imuVeloFromStartX = 0; imuVeloFromStartY = 0; imuVeloFromStartZ = 0;
laserCloudCornerLast.reset(new pcl::PointCloud<PointType>());
laserCloudSurfLast.reset(new pcl::PointCloud<PointType>());
laserCloudOri.reset(new pcl::PointCloud<PointType>());
coeffSel.reset(new pcl::PointCloud<PointType>());
kdtreeCornerLast.reset(new pcl::KdTreeFLANN<PointType>());
kdtreeSurfLast.reset(new pcl::KdTreeFLANN<PointType>());
laserOdometry.header.frame_id = "/camera_init";
laserOdometry.child_frame_id = "/laser_odom";
laserOdometryTrans.frame_id_ = "/camera_init";
laserOdometryTrans.child_frame_id_ = "/laser_odom";
isDegenerate = false;
matP = cv::Mat(6, 6, CV_32F, cv::Scalar::all(0));
frameCount = skipFrameNum;
}
void updateImuRollPitchYawStartSinCos(){
cosImuRollStart = cos(imuRollStart);
cosImuPitchStart = cos(imuPitchStart);
cosImuYawStart = cos(imuYawStart);
sinImuRollStart = sin(imuRollStart);
sinImuPitchStart = sin(imuPitchStart);
sinImuYawStart = sin(imuYawStart);
}
void ShiftToStartIMU(float pointTime)
{
imuShiftFromStartXCur = imuShiftXCur - imuShiftXStart - imuVeloXStart * pointTime;
imuShiftFromStartYCur = imuShiftYCur - imuShiftYStart - imuVeloYStart * pointTime;
imuShiftFromStartZCur = imuShiftZCur - imuShiftZStart - imuVeloZStart * pointTime;
float x1 = cosImuYawStart * imuShiftFromStartXCur - sinImuYawStart * imuShiftFromStartZCur;
float y1 = imuShiftFromStartYCur;
float z1 = sinImuYawStart * imuShiftFromStartXCur + cosImuYawStart * imuShiftFromStartZCur;
float x2 = x1;
float y2 = cosImuPitchStart * y1 + sinImuPitchStart * z1;
float z2 = -sinImuPitchStart * y1 + cosImuPitchStart * z1;
imuShiftFromStartXCur = cosImuRollStart * x2 + sinImuRollStart * y2;
imuShiftFromStartYCur = -sinImuRollStart * x2 + cosImuRollStart * y2;
imuShiftFromStartZCur = z2;
}
void VeloToStartIMU()
{
imuVeloFromStartXCur = imuVeloXCur - imuVeloXStart;
imuVeloFromStartYCur = imuVeloYCur - imuVeloYStart;
imuVeloFromStartZCur = imuVeloZCur - imuVeloZStart;
float x1 = cosImuYawStart * imuVeloFromStartXCur - sinImuYawStart * imuVeloFromStartZCur;
float y1 = imuVeloFromStartYCur;
float z1 = sinImuYawStart * imuVeloFromStartXCur + cosImuYawStart * imuVeloFromStartZCur;
float x2 = x1;
float y2 = cosImuPitchStart * y1 + sinImuPitchStart * z1;
float z2 = -sinImuPitchStart * y1 + cosImuPitchStart * z1;
imuVeloFromStartXCur = cosImuRollStart * x2 + sinImuRollStart * y2;
imuVeloFromStartYCur = -sinImuRollStart * x2 + cosImuRollStart * y2;
imuVeloFromStartZCur = z2;
}
void TransformToStartIMU(PointType *p)
{
float x1 = cos(imuRollCur) * p->x - sin(imuRollCur) * p->y;
float y1 = sin(imuRollCur) * p->x + cos(imuRollCur) * p->y;
float z1 = p->z;
float x2 = x1;
float y2 = cos(imuPitchCur) * y1 - sin(imuPitchCur) * z1;
float z2 = sin(imuPitchCur) * y1 + cos(imuPitchCur) * z1;
float x3 = cos(imuYawCur) * x2 + sin(imuYawCur) * z2;
float y3 = y2;
float z3 = -sin(imuYawCur) * x2 + cos(imuYawCur) * z2;
float x4 = cosImuYawStart * x3 - sinImuYawStart * z3;
float y4 = y3;
float z4 = sinImuYawStart * x3 + cosImuYawStart * z3;
float x5 = x4;
float y5 = cosImuPitchStart * y4 + sinImuPitchStart * z4;
float z5 = -sinImuPitchStart * y4 + cosImuPitchStart * z4;
p->x = cosImuRollStart * x5 + sinImuRollStart * y5 + imuShiftFromStartXCur;
p->y = -sinImuRollStart * x5 + cosImuRollStart * y5 + imuShiftFromStartYCur;
p->z = z5 + imuShiftFromStartZCur;
}
// IMU数据处理
// 单帧IMU在全局坐标系下的位移、速度、角速度
void AccumulateIMUShiftAndRotation()
{
float roll = imuRoll[imuPointerLast];
float pitch = imuPitch[imuPointerLast];
float yaw = imuYaw[imuPointerLast];
float accX = imuAccX[imuPointerLast];
float accY = imuAccY[imuPointerLast];
float accZ = imuAccZ[imuPointerLast];
// IMU坐标系到世界坐标系
float x1 = cos(roll) * accX - sin(roll) * accY;
float y1 = sin(roll) * accX + cos(roll) * accY;
float z1 = accZ;
float x2 = x1;
float y2 = cos(pitch) * y1 - sin(pitch) * z1;
float z2 = sin(pitch) * y1 + cos(pitch) * z1;
accX = cos(yaw) * x2 + sin(yaw) * z2;
accY = y2;
accZ = -sin(yaw) * x2 + cos(yaw) * z2;
// IMU 测量周期
int imuPointerBack = (imuPointerLast + imuQueLength - 1) % imuQueLength;
double timeDiff = imuTime[imuPointerLast] - imuTime[imuPointerBack];
if (timeDiff < scanPeriod) {
imuShiftX[imuPointerLast] = imuShiftX[imuPointerBack] + imuVeloX[imuPointerBack] * timeDiff + accX * timeDiff * timeDiff / 2;
imuShiftY[imuPointerLast] = imuShiftY[imuPointerBack] + imuVeloY[imuPointerBack] * timeDiff + accY * timeDiff * timeDiff / 2;
imuShiftZ[imuPointerLast] = imuShiftZ[imuPointerBack] + imuVeloZ[imuPointerBack] * timeDiff + accZ * timeDiff * timeDiff / 2;
imuVeloX[imuPointerLast] = imuVeloX[imuPointerBack] + accX * timeDiff;
imuVeloY[imuPointerLast] = imuVeloY[imuPointerBack] + accY * timeDiff;
imuVeloZ[imuPointerLast] = imuVeloZ[imuPointerBack] + accZ * timeDiff;
imuAngularRotationX[imuPointerLast] = imuAngularRotationX[imuPointerBack] + imuAngularVeloX[imuPointerBack] * timeDiff;
imuAngularRotationY[imuPointerLast] = imuAngularRotationY[imuPointerBack] + imuAngularVeloY[imuPointerBack] * timeDiff;
imuAngularRotationZ[imuPointerLast] = imuAngularRotationZ[imuPointerBack] + imuAngularVeloZ[imuPointerBack] * timeDiff;
}
}
void imuHandler(const sensor_msgs::Imu::ConstPtr& imuIn)
{
double roll, pitch, yaw;
tf::Quaternion orientation;
tf::quaternionMsgToTF(imuIn->orientation, orientation);
tf::Matrix3x3(orientation).getRPY(roll, pitch, yaw);
// 去除IMU重力加速度影响、同时进行坐标轴变换
float accX = imuIn->linear_acceleration.y - sin(roll) * cos(pitch) * 9.81;
float accY = imuIn->linear_acceleration.z - cos(roll) * cos(pitch) * 9.81;
float accZ = imuIn->linear_acceleration.x + sin(pitch) * 9.81;
// 保存欧拉角、线加速度、角速度
imuPointerLast = (imuPointerLast + 1) % imuQueLength;
imuTime[imuPointerLast] = imuIn->header.stamp.toSec();
imuRoll[imuPointerLast] = roll;
imuPitch[imuPointerLast] = pitch;
imuYaw[imuPointerLast] = yaw;
imuAccX[imuPointerLast] = accX;
imuAccY[imuPointerLast] = accY;
imuAccZ[imuPointerLast] = accZ;
imuAngularVeloX[imuPointerLast] = imuIn->angular_velocity.x;
imuAngularVeloY[imuPointerLast] = imuIn->angular_velocity.y;
imuAngularVeloZ[imuPointerLast] = imuIn->angular_velocity.z;
AccumulateIMUShiftAndRotation();
}
void laserCloudHandler(const sensor_msgs::PointCloud2ConstPtr& laserCloudMsg){
cloudHeader = laserCloudMsg->header;
timeScanCur = cloudHeader.stamp.toSec();
timeNewSegmentedCloud = timeScanCur;
segmentedCloud->clear();
pcl::fromROSMsg(*laserCloudMsg, *segmentedCloud);
newSegmentedCloud = true;
}
void outlierCloudHandler(const sensor_msgs::PointCloud2ConstPtr& msgIn){
timeNewOutlierCloud = msgIn->header.stamp.toSec();
outlierCloud->clear();
pcl::fromROSMsg(*msgIn, *outlierCloud);
newOutlierCloud = true;
}
void laserCloudInfoHandler(const cloud_msgs::cloud_infoConstPtr& msgIn)
{
timeNewSegmentedCloudInfo = msgIn->header.stamp.toSec();
segInfo = *msgIn;
newSegmentedCloudInfo = true;
}
// 使用IMU数据插值,去除运动畸变
void adjustDistortion()
{
bool halfPassed = false;
int cloudSize = segmentedCloud->points.size();
PointType point;
for (int i = 0; i < cloudSize; i++) {
point.x = segmentedCloud->points[i].y;
point.y = segmentedCloud->points[i].z;
point.z = segmentedCloud->points[i].x;
// 调整点所在的位置
float ori = -atan2(point.x, point.z);
if (!halfPassed) {
if (ori < segInfo.startOrientation - M_PI / 2)
ori += 2 * M_PI;
else if (ori > segInfo.startOrientation + M_PI * 3 / 2)
ori -= 2 * M_PI;
if (ori - segInfo.startOrientation > M_PI)
halfPassed = true;
} else {
ori += 2 * M_PI;
if (ori < segInfo.endOrientation - M_PI * 3 / 2)
ori += 2 * M_PI;
else if (ori > segInfo.endOrientation + M_PI / 2)
ori -= 2 * M_PI;
}
// 保留各点的相对时间
float relTime = (ori - segInfo.startOrientation) / segInfo.orientationDiff;
point.intensity = int(segmentedCloud->points[i].intensity) + scanPeriod * relTime;
if (imuPointerLast >= 0) {
float pointTime = relTime * scanPeriod;
imuPointerFront = imuPointerLastIteration;
// 与IMU时间戳对齐
while (imuPointerFront != imuPointerLast) {
if (timeScanCur + pointTime < imuTime[imuPointerFront]) {
break;
}
imuPointerFront = (imuPointerFront + 1) % imuQueLength;
}
if (timeScanCur + pointTime > imuTime[imuPointerFront]) {
// IMU数据比激光早且无后边数据,无法插值
imuRollCur = imuRoll[imuPointerFront];
imuPitchCur = imuPitch[imuPointerFront];
imuYawCur = imuYaw[imuPointerFront];
imuVeloXCur = imuVeloX[imuPointerFront];
imuVeloYCur = imuVeloY[imuPointerFront];
imuVeloZCur = imuVeloZ[imuPointerFront];
imuShiftXCur = imuShiftX[imuPointerFront];
imuShiftYCur = imuShiftY[imuPointerFront];
imuShiftZCur = imuShiftZ[imuPointerFront];
} else { //IMU插值,角度、速度、位移
int imuPointerBack = (imuPointerFront + imuQueLength - 1) % imuQueLength;
float ratioFront = (timeScanCur + pointTime - imuTime[imuPointerBack])
/ (imuTime[imuPointerFront] - imuTime[imuPointerBack]);
float ratioBack = (imuTime[imuPointerFront] - timeScanCur - pointTime)
/ (imuTime[imuPointerFront] - imuTime[imuPointerBack]);
imuRollCur = imuRoll[imuPointerFront] * ratioFront + imuRoll[imuPointerBack] * ratioBack;
imuPitchCur = imuPitch[imuPointerFront] * ratioFront + imuPitch[imuPointerBack] * ratioBack;
if (imuYaw[imuPointerFront] - imuYaw[imuPointerBack] > M_PI) {
imuYawCur = imuYaw[imuPointerFront] * ratioFront + (imuYaw[imuPointerBack] + 2 * M_PI) * ratioBack;
} else if (imuYaw[imuPointerFront] - imuYaw[imuPointerBack] < -M_PI) {
imuYawCur = imuYaw[imuPointerFront] * ratioFront + (imuYaw[imuPointerBack] - 2 * M_PI) * ratioBack;
} else {
imuYawCur = imuYaw[imuPointerFront] * ratioFront + imuYaw[imuPointerBack] * ratioBack;
}
imuVeloXCur = imuVeloX[imuPointerFront] * ratioFront + imuVeloX[imuPointerBack] * ratioBack;
imuVeloYCur = imuVeloY[imuPointerFront] * ratioFront + imuVeloY[imuPointerBack] * ratioBack;
imuVeloZCur = imuVeloZ[imuPointerFront] * ratioFront + imuVeloZ[imuPointerBack] * ratioBack;
imuShiftXCur = imuShiftX[imuPointerFront] * ratioFront + imuShiftX[imuPointerBack] * ratioBack;
imuShiftYCur = imuShiftY[imuPointerFront] * ratioFront + imuShiftY[imuPointerBack] * ratioBack;
imuShiftZCur = imuShiftZ[imuPointerFront] * ratioFront + imuShiftZ[imuPointerBack] * ratioBack;
}
if (i == 0) {
imuRollStart = imuRollCur;
imuPitchStart = imuPitchCur;
imuYawStart = imuYawCur;
imuVeloXStart = imuVeloXCur;
imuVeloYStart = imuVeloYCur;
imuVeloZStart = imuVeloZCur;
imuShiftXStart = imuShiftXCur;
imuShiftYStart = imuShiftYCur;
imuShiftZStart = imuShiftZCur;
if (timeScanCur + pointTime > imuTime[imuPointerFront]) {
imuAngularRotationXCur = imuAngularRotationX[imuPointerFront];
imuAngularRotationYCur = imuAngularRotationY[imuPointerFront];
imuAngularRotationZCur = imuAngularRotationZ[imuPointerFront];
}else{
int imuPointerBack = (imuPointerFront + imuQueLength - 1) % imuQueLength;
float ratioFront = (timeScanCur + pointTime - imuTime[imuPointerBack])
/ (imuTime[imuPointerFront] - imuTime[imuPointerBack]);
float ratioBack = (imuTime[imuPointerFront] - timeScanCur - pointTime)
/ (imuTime[imuPointerFront] - imuTime[imuPointerBack]);
imuAngularRotationXCur = imuAngularRotationX[imuPointerFront] * ratioFront + imuAngularRotationX[imuPointerBack] * ratioBack;
imuAngularRotationYCur = imuAngularRotationY[imuPointerFront] * ratioFront + imuAngularRotationY[imuPointerBack] * ratioBack;
imuAngularRotationZCur = imuAngularRotationZ[imuPointerFront] * ratioFront + imuAngularRotationZ[imuPointerBack] * ratioBack;
}
imuAngularFromStartX = imuAngularRotationXCur - imuAngularRotationXLast;
imuAngularFromStartY = imuAngularRotationYCur - imuAngularRotationYLast;
imuAngularFromStartZ = imuAngularRotationZCur - imuAngularRotationZLast;
imuAngularRotationXLast = imuAngularRotationXCur;
imuAngularRotationYLast = imuAngularRotationYCur;
imuAngularRotationZLast = imuAngularRotationZCur;
updateImuRollPitchYawStartSinCos();
} else {
VeloToStartIMU(); //速度投影到初始时刻
TransformToStartIMU(&point); //点的坐标变换到初始时刻
}
}
segmentedCloud->points[i] = point;
}
imuPointerLastIteration = imuPointerLast;
}
// 计算点的曲率,并将特殊情况的点标记为瑕点,不参与后续特征提取。
void calculateSmoothness()
{
int cloudSize = segmentedCloud->points.size();
for (int i = 5; i < cloudSize - 5; i++) {
float diffRange = segInfo.segmentedCloudRange[i-5] + segInfo.segmentedCloudRange[i-4]
+ segInfo.segmentedCloudRange[i-3] + segInfo.segmentedCloudRange[i-2]
+ segInfo.segmentedCloudRange[i-1] - segInfo.segmentedCloudRange[i] * 10
+ segInfo.segmentedCloudRange[i+1] + segInfo.segmentedCloudRange[i+2]
+ segInfo.segmentedCloudRange[i+3] + segInfo.segmentedCloudRange[i+4]
+ segInfo.segmentedCloudRange[i+5];
cloudCurvature[i] = diffRange*diffRange;
cloudNeighborPicked[i] = 0;
cloudLabel[i] = 0;
cloudSmoothness[i].value = cloudCurvature[i];
cloudSmoothness[i].ind = i;
}
}
void markOccludedPoints()
{
int cloudSize = segmentedCloud->points.size();
for (int i = 5; i < cloudSize - 6; ++i){
float depth1 = segInfo.segmentedCloudRange[i];
float depth2 = segInfo.segmentedCloudRange[i+1];
int columnDiff = std::abs(int(segInfo.segmentedCloudColInd[i+1] - segInfo.segmentedCloudColInd[i]));
if (columnDiff < 10){
if (depth1 - depth2 > 0.3){
cloudNeighborPicked[i - 5] = 1;
cloudNeighborPicked[i - 4] = 1;
cloudNeighborPicked[i - 3] = 1;
cloudNeighborPicked[i - 2] = 1;
cloudNeighborPicked[i - 1] = 1;
cloudNeighborPicked[i] = 1;
}else if (depth2 - depth1 > 0.3){
cloudNeighborPicked[i + 1] = 1;
cloudNeighborPicked[i + 2] = 1;
cloudNeighborPicked[i + 3] = 1;
cloudNeighborPicked[i + 4] = 1;
cloudNeighborPicked[i + 5] = 1;
cloudNeighborPicked[i + 6] = 1;
}
}
float diff1 = std::abs(float(segInfo.segmentedCloudRange[i-1] - segInfo.segmentedCloudRange[i]));
float diff2 = std::abs(float(segInfo.segmentedCloudRange[i+1] - segInfo.segmentedCloudRange[i]));
if (diff1 > 0.02 * segInfo.segmentedCloudRange[i] && diff2 > 0.02 * segInfo.segmentedCloudRange[i])
cloudNeighborPicked[i] = 1;
}
}
// 根据曲率阈值,提取边特征点、平面特征点,降采样处理之后发布
void extractFeatures()
{
cornerPointsSharp->clear();
cornerPointsLessSharp->clear();
surfPointsFlat->clear();
surfPointsLessFlat->clear();
for (int i = 0; i < N_SCAN; i++) {
surfPointsLessFlatScan->clear();
// 将一帧点云range-image按照行平均分为6份
for (int j = 0; j < 6; j++) {
int sp = (segInfo.startRingIndex[i] * (6 - j) + segInfo.endRingIndex[i] * j) / 6;
int ep = (segInfo.startRingIndex[i] * (5 - j) + segInfo.endRingIndex[i] * (j + 1)) / 6 - 1;
if (sp >= ep)
continue;
std::sort(cloudSmoothness.begin()+sp, cloudSmoothness.begin()+ep, by_value());
int largestPickedNum = 0;
for (int k = ep; k >= sp; k--) {
int ind = cloudSmoothness[k].ind;
//边点2个,次边点18个
if (cloudNeighborPicked[ind] == 0 &&
cloudCurvature[ind] > edgeThreshold &&
segInfo.segmentedCloudGroundFlag[ind] == false) {
largestPickedNum++;
if (largestPickedNum <= 2) {
cloudLabel[ind] = 2;
cornerPointsSharp->push_back(segmentedCloud->points[ind]);
cornerPointsLessSharp->push_back(segmentedCloud->points[ind]);
} else if (largestPickedNum <= 20) {
cloudLabel[ind] = 1;
cornerPointsLessSharp->push_back(segmentedCloud->points[ind]);
} else {
break;
}
cloudNeighborPicked[ind] = 1;
//特征点前后5个若有距离大于阈值的可以不用标记,否则标记为非特征点
for (int l = 1; l <= 5; l++) {
int columnDiff = std::abs(int(segInfo.segmentedCloudColInd[ind + l] - segInfo.segmentedCloudColInd[ind + l - 1]));
if (columnDiff > 10)
break;
cloudNeighborPicked[ind + l] = 1;
}
for (int l = -1; l >= -5; l--) {
int columnDiff = std::abs(int(segInfo.segmentedCloudColInd[ind + l] - segInfo.segmentedCloudColInd[ind + l + 1]));
if (columnDiff > 10)
break;
cloudNeighborPicked[ind + l] = 1;
}
}
}
int smallestPickedNum = 0;
for (int k = sp; k <= ep; k++) {
int ind = cloudSmoothness[k].ind;
if (cloudNeighborPicked[ind] == 0 &&
cloudCurvature[ind] < surfThreshold &&
segInfo.segmentedCloudGroundFlag[ind] == true) {
cloudLabel[ind] = -1;
surfPointsFlat->push_back(segmentedCloud->points[ind]);
smallestPickedNum++;
if (smallestPickedNum >= 4) {
break;
}
cloudNeighborPicked[ind] = 1;
for (int l = 1; l <= 5; l++) {
int columnDiff = std::abs(int(segInfo.segmentedCloudColInd[ind + l] - segInfo.segmentedCloudColInd[ind + l - 1]));
if (columnDiff > 10)
break;
cloudNeighborPicked[ind + l] = 1;
}
for (int l = -1; l >= -5; l--) {
int columnDiff = std::abs(int(segInfo.segmentedCloudColInd[ind + l] - segInfo.segmentedCloudColInd[ind + l + 1]));
if (columnDiff > 10)
break;
cloudNeighborPicked[ind + l] = 1;
}
}
}
//未被标记的点以及上述平面点作为次平面点
for (int k = sp; k <= ep; k++) {
if (cloudLabel[k] <= 0) {
surfPointsLessFlatScan->push_back(segmentedCloud->points[k]);
}
}
}
surfPointsLessFlatScanDS->clear();
downSizeFilter.setInputCloud(surfPointsLessFlatScan);
downSizeFilter.filter(*surfPointsLessFlatScanDS);
*surfPointsLessFlat += *surfPointsLessFlatScanDS;
}
}
void publishCloud()
{
sensor_msgs::PointCloud2 laserCloudOutMsg;
if (pubCornerPointsSharp.getNumSubscribers() != 0){
pcl::toROSMsg(*cornerPointsSharp, laserCloudOutMsg);
laserCloudOutMsg.header.stamp = cloudHeader.stamp;
laserCloudOutMsg.header.frame_id = "/camera";
pubCornerPointsSharp.publish(laserCloudOutMsg);
}
if (pubCornerPointsLessSharp.getNumSubscribers() != 0){
pcl::toROSMsg(*cornerPointsLessSharp, laserCloudOutMsg);
laserCloudOutMsg.header.stamp = cloudHeader.stamp;
laserCloudOutMsg.header.frame_id = "/camera";
pubCornerPointsLessSharp.publish(laserCloudOutMsg);
}
if (pubSurfPointsFlat.getNumSubscribers() != 0){
pcl::toROSMsg(*surfPointsFlat, laserCloudOutMsg);
laserCloudOutMsg.header.stamp = cloudHeader.stamp;
laserCloudOutMsg.header.frame_id = "/camera";
pubSurfPointsFlat.publish(laserCloudOutMsg);
}
if (pubSurfPointsLessFlat.getNumSubscribers() != 0){
pcl::toROSMsg(*surfPointsLessFlat, laserCloudOutMsg);
laserCloudOutMsg.header.stamp = cloudHeader.stamp;
laserCloudOutMsg.header.frame_id = "/camera";
pubSurfPointsLessFlat.publish(laserCloudOutMsg);
}
}
/*****
特征关联程序
将当前时刻保存的IMU数据作为先验信息(角度、位移)
*/
void TransformToStart(PointType const * const pi, PointType * const po)
{
float s = 10 * (pi->intensity - int(pi->intensity));
float rx = s * transformCur[0];
float ry = s * transformCur[1];
float rz = s * transformCur[2];
float tx = s * transformCur[3];
float ty = s * transformCur[4];
float tz = s * transformCur[5];
float x1 = cos(rz) * (pi->x - tx) + sin(rz) * (pi->y - ty);
float y1 = -sin(rz) * (pi->x - tx) + cos(rz) * (pi->y - ty);
float z1 = (pi->z - tz);
float x2 = x1;
float y2 = cos(rx) * y1 + sin(rx) * z1;
float z2 = -sin(rx) * y1 + cos(rx) * z1;
po->x = cos(ry) * x2 - sin(ry) * z2;
po->y = y2;
po->z = sin(ry) * x2 + cos(ry) * z2;
po->intensity = pi->intensity;
}
void TransformToEnd(PointType const * const pi, PointType * const po)
{
float s = 10 * (pi->intensity - int(pi->intensity));
float rx = s * transformCur[0];
float ry = s * transformCur[1];
float rz = s * transformCur[2];
float tx = s * transformCur[3];
float ty = s * transformCur[4];
float tz = s * transformCur[5];
float x1 = cos(rz) * (pi->x - tx) + sin(rz) * (pi->y - ty);
float y1 = -sin(rz) * (pi->x - tx) + cos(rz) * (pi->y - ty);
float z1 = (pi->z - tz);
float x2 = x1;
float y2 = cos(rx) * y1 + sin(rx) * z1;
float z2 = -sin(rx) * y1 + cos(rx) * z1;
float x3 = cos(ry) * x2 - sin(ry) * z2;
float y3 = y2;
float z3 = sin(ry) * x2 + cos(ry) * z2;
rx = transformCur[0];
ry = transformCur[1];
rz = transformCur[2];
tx = transformCur[3];
ty = transformCur[4];
tz = transformCur[5];
float x4 = cos(ry) * x3 + sin(ry) * z3;
float y4 = y3;
float z4 = -sin(ry) * x3 + cos(ry) * z3;
float x5 = x4;
float y5 = cos(rx) * y4 - sin(rx) * z4;
float z5 = sin(rx) * y4 + cos(rx) * z4;
float x6 = cos(rz) * x5 - sin(rz) * y5 + tx;
float y6 = sin(rz) * x5 + cos(rz) * y5 + ty;
float z6 = z5 + tz;
float x7 = cosImuRollStart * (x6 - imuShiftFromStartX)
- sinImuRollStart * (y6 - imuShiftFromStartY);
float y7 = sinImuRollStart * (x6 - imuShiftFromStartX)
+ cosImuRollStart * (y6 - imuShiftFromStartY);
float z7 = z6 - imuShiftFromStartZ;
float x8 = x7;
float y8 = cosImuPitchStart * y7 - sinImuPitchStart * z7;
float z8 = sinImuPitchStart * y7 + cosImuPitchStart * z7;
float x9 = cosImuYawStart * x8 + sinImuYawStart * z8;
float y9 = y8;
float z9 = -sinImuYawStart * x8 + cosImuYawStart * z8;
float x10 = cos(imuYawLast) * x9 - sin(imuYawLast) * z9;
float y10 = y9;
float z10 = sin(imuYawLast) * x9 + cos(imuYawLast) * z9;
float x11 = x10;
float y11 = cos(imuPitchLast) * y10 + sin(imuPitchLast) * z10;
float z11 = -sin(imuPitchLast) * y10 + cos(imuPitchLast) * z10;
po->x = cos(imuRollLast) * x11 + sin(imuRollLast) * y11;
po->y = -sin(imuRollLast) * x11 + cos(imuRollLast) * y11;
po->z = z11;
po->intensity = int(pi->intensity);
}
void PluginIMURotation(float bcx, float bcy, float bcz, float blx, float bly, float blz,
float alx, float aly, float alz, float &acx, float &acy, float &acz)
{
float sbcx = sin(bcx);
float cbcx = cos(bcx);
float sbcy = sin(bcy);
float cbcy = cos(bcy);
float sbcz = sin(bcz);
float cbcz = cos(bcz);
float sblx = sin(blx);
float cblx = cos(blx);
float sbly = sin(bly);
float cbly = cos(bly);
float sblz = sin(blz);
float cblz = cos(blz);
float salx = sin(alx);
float calx = cos(alx);
float saly = sin(aly);
float caly = cos(aly);
float salz = sin(alz);
float calz = cos(alz);
float srx = -sbcx*(salx*sblx + calx*caly*cblx*cbly + calx*cblx*saly*sbly)
- cbcx*cbcz*(calx*saly*(cbly*sblz - cblz*sblx*sbly)
- calx*caly*(sbly*sblz + cbly*cblz*sblx) + cblx*cblz*salx)
- cbcx*sbcz*(calx*caly*(cblz*sbly - cbly*sblx*sblz)
- calx*saly*(cbly*cblz + sblx*sbly*sblz) + cblx*salx*sblz);
acx = -asin(srx);
float srycrx = (cbcy*sbcz - cbcz*sbcx*sbcy)*(calx*saly*(cbly*sblz - cblz*sblx*sbly)
- calx*caly*(sbly*sblz + cbly*cblz*sblx) + cblx*cblz*salx)
- (cbcy*cbcz + sbcx*sbcy*sbcz)*(calx*caly*(cblz*sbly - cbly*sblx*sblz)
- calx*saly*(cbly*cblz + sblx*sbly*sblz) + cblx*salx*sblz)
+ cbcx*sbcy*(salx*sblx + calx*caly*cblx*cbly + calx*cblx*saly*sbly);
float crycrx = (cbcz*sbcy - cbcy*sbcx*sbcz)*(calx*caly*(cblz*sbly - cbly*sblx*sblz)
- calx*saly*(cbly*cblz + sblx*sbly*sblz) + cblx*salx*sblz)
- (sbcy*sbcz + cbcy*cbcz*sbcx)*(calx*saly*(cbly*sblz - cblz*sblx*sbly)
- calx*caly*(sbly*sblz + cbly*cblz*sblx) + cblx*cblz*salx)
+ cbcx*cbcy*(salx*sblx + calx*caly*cblx*cbly + calx*cblx*saly*sbly);
acy = atan2(srycrx / cos(acx), crycrx / cos(acx));
float srzcrx = sbcx*(cblx*cbly*(calz*saly - caly*salx*salz)
- cblx*sbly*(caly*calz + salx*saly*salz) + calx*salz*sblx)
- cbcx*cbcz*((caly*calz + salx*saly*salz)*(cbly*sblz - cblz*sblx*sbly)
+ (calz*saly - caly*salx*salz)*(sbly*sblz + cbly*cblz*sblx)
- calx*cblx*cblz*salz) + cbcx*sbcz*((caly*calz + salx*saly*salz)*(cbly*cblz
+ sblx*sbly*sblz) + (calz*saly - caly*salx*salz)*(cblz*sbly - cbly*sblx*sblz)
+ calx*cblx*salz*sblz);
float crzcrx = sbcx*(cblx*sbly*(caly*salz - calz*salx*saly)
- cblx*cbly*(saly*salz + caly*calz*salx) + calx*calz*sblx)
+ cbcx*cbcz*((saly*salz + caly*calz*salx)*(sbly*sblz + cbly*cblz*sblx)
+ (caly*salz - calz*salx*saly)*(cbly*sblz - cblz*sblx*sbly)
+ calx*calz*cblx*cblz) - cbcx*sbcz*((saly*salz + caly*calz*salx)*(cblz*sbly
- cbly*sblx*sblz) + (caly*salz - calz*salx*saly)*(cbly*cblz + sblx*sbly*sblz)
- calx*calz*cblx*sblz);
acz = atan2(srzcrx / cos(acx), crzcrx / cos(acx));
}
void AccumulateRotation(float cx, float cy, float cz, float lx, float ly, float lz,
float &ox, float &oy, float &oz)
{
float srx = cos(lx)*cos(cx)*sin(ly)*sin(cz) - cos(cx)*cos(cz)*sin(lx) - cos(lx)*cos(ly)*sin(cx);
ox = -asin(srx);
float srycrx = sin(lx)*(cos(cy)*sin(cz) - cos(cz)*sin(cx)*sin(cy)) + cos(lx)*sin(ly)*(cos(cy)*cos(cz)
+ sin(cx)*sin(cy)*sin(cz)) + cos(lx)*cos(ly)*cos(cx)*sin(cy);
float crycrx = cos(lx)*cos(ly)*cos(cx)*cos(cy) - cos(lx)*sin(ly)*(cos(cz)*sin(cy)
- cos(cy)*sin(cx)*sin(cz)) - sin(lx)*(sin(cy)*sin(cz) + cos(cy)*cos(cz)*sin(cx));
oy = atan2(srycrx / cos(ox), crycrx / cos(ox));
float srzcrx = sin(cx)*(cos(lz)*sin(ly) - cos(ly)*sin(lx)*sin(lz)) + cos(cx)*sin(cz)*(cos(ly)*cos(lz)
+ sin(lx)*sin(ly)*sin(lz)) + cos(lx)*cos(cx)*cos(cz)*sin(lz);
float crzcrx = cos(lx)*cos(lz)*cos(cx)*cos(cz) - cos(cx)*sin(cz)*(cos(ly)*sin(lz)
- cos(lz)*sin(lx)*sin(ly)) - sin(cx)*(sin(ly)*sin(lz) + cos(ly)*cos(lz)*sin(lx));
oz = atan2(srzcrx / cos(ox), crzcrx / cos(ox));
}
double rad2deg(double radians)
{
return radians * 180.0 / M_PI;
}
double deg2rad(double degrees)
{
return degrees * M_PI / 180.0;
}
void findCorrespondingCornerFeatures(int iterCount){
int cornerPointsSharpNum = cornerPointsSharp->points.size();
for (int i = 0; i < cornerPointsSharpNum; i++) {
TransformToStart(&cornerPointsSharp->points[i], &pointSel);
if (iterCount % 5 == 0) {
kdtreeCornerLast->nearestKSearch(pointSel, 1, pointSearchInd, pointSearchSqDis);
int closestPointInd = -1, minPointInd2 = -1;
if (pointSearchSqDis[0] < nearestFeatureSearchSqDist) {
closestPointInd = pointSearchInd[0];
int closestPointScan = int(laserCloudCornerLast->points[closestPointInd].intensity);
float pointSqDis, minPointSqDis2 = nearestFeatureSearchSqDist;
for (int j = closestPointInd + 1; j < cornerPointsSharpNum; j++) {
if (int(laserCloudCornerLast->points[j].intensity) > closestPointScan + 2.5) {
break;
}
pointSqDis = (laserCloudCornerLast->points[j].x - pointSel.x) *
(laserCloudCornerLast->points[j].x - pointSel.x) +
(laserCloudCornerLast->points[j].y - pointSel.y) *
(laserCloudCornerLast->points[j].y - pointSel.y) +
(laserCloudCornerLast->points[j].z - pointSel.z) *
(laserCloudCornerLast->points[j].z - pointSel.z);
if (int(laserCloudCornerLast->points[j].intensity) > closestPointScan) {
if (pointSqDis < minPointSqDis2) {
minPointSqDis2 = pointSqDis;
minPointInd2 = j;
}
}
}
for (int j = closestPointInd - 1; j >= 0; j--) {
if (int(laserCloudCornerLast->points[j].intensity) < closestPointScan - 2.5) {
break;
}
pointSqDis = (laserCloudCornerLast->points[j].x - pointSel.x) *
(laserCloudCornerLast->points[j].x - pointSel.x) +
(laserCloudCornerLast->points[j].y - pointSel.y) *
(laserCloudCornerLast->points[j].y - pointSel.y) +
(laserCloudCornerLast->points[j].z - pointSel.z) *
(laserCloudCornerLast->points[j].z - pointSel.z);
if (int(laserCloudCornerLast->points[j].intensity) < closestPointScan) {
if (pointSqDis < minPointSqDis2) {
minPointSqDis2 = pointSqDis;
minPointInd2 = j;
}
}
}
}
pointSearchCornerInd1[i] = closestPointInd;
pointSearchCornerInd2[i] = minPointInd2;
}
if (pointSearchCornerInd2[i] >= 0) {
tripod1 = laserCloudCornerLast->points[pointSearchCornerInd1[i]];
tripod2 = laserCloudCornerLast->points[pointSearchCornerInd2[i]];
float x0 = pointSel.x;
float y0 = pointSel.y;
float z0 = pointSel.z;
float x1 = tripod1.x;
float y1 = tripod1.y;
float z1 = tripod1.z;
float x2 = tripod2.x;
float y2 = tripod2.y;
float z2 = tripod2.z;
float m11 = ((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1));
float m22 = ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1));
float m33 = ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1));
float a012 = sqrt(m11 * m11 + m22 * m22 + m33 * m33);
float l12 = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2));
float la = ((y1 - y2)*m11 + (z1 - z2)*m22) / a012 / l12;
float lb = -((x1 - x2)*m11 - (z1 - z2)*m33) / a012 / l12;
float lc = -((x1 - x2)*m22 + (y1 - y2)*m33) / a012 / l12;
float ld2 = a012 / l12;
float s = 1;
if (iterCount >= 5) {
s = 1 - 1.8 * fabs(ld2);
}
if (s > 0.1 && ld2 != 0) {
coeff.x = s * la;
coeff.y = s * lb;
coeff.z = s * lc;
coeff.intensity = s * ld2;
laserCloudOri->push_back(cornerPointsSharp->points[i]);
coeffSel->push_back(coeff);
}
}
}
}
void findCorrespondingSurfFeatures(int iterCount){
int surfPointsFlatNum = surfPointsFlat->points.size();
for (int i = 0; i < surfPointsFlatNum; i++) {
TransformToStart(&surfPointsFlat->points[i], &pointSel);
if (iterCount % 5 == 0) {
kdtreeSurfLast->nearestKSearch(pointSel, 1, pointSearchInd, pointSearchSqDis);
int closestPointInd = -1, minPointInd2 = -1, minPointInd3 = -1;
if (pointSearchSqDis[0] < nearestFeatureSearchSqDist) {
closestPointInd = pointSearchInd[0];
int closestPointScan = int(laserCloudSurfLast->points[closestPointInd].intensity);
float pointSqDis, minPointSqDis2 = nearestFeatureSearchSqDist, minPointSqDis3 = nearestFeatureSearchSqDist;
for (int j = closestPointInd + 1; j < surfPointsFlatNum; j++) {
if (int(laserCloudSurfLast->points[j].intensity) > closestPointScan + 2.5) {
break;
}
pointSqDis = (laserCloudSurfLast->points[j].x - pointSel.x) *
(laserCloudSurfLast->points[j].x - pointSel.x) +
(laserCloudSurfLast->points[j].y - pointSel.y) *
(laserCloudSurfLast->points[j].y - pointSel.y) +
(laserCloudSurfLast->points[j].z - pointSel.z) *
(laserCloudSurfLast->points[j].z - pointSel.z);
if (int(laserCloudSurfLast->points[j].intensity) <= closestPointScan) {
if (pointSqDis < minPointSqDis2) {
minPointSqDis2 = pointSqDis;
minPointInd2 = j;
}
} else {
if (pointSqDis < minPointSqDis3) {
minPointSqDis3 = pointSqDis;
minPointInd3 = j;
}
}
}
for (int j = closestPointInd - 1; j >= 0; j--) {
if (int(laserCloudSurfLast->points[j].intensity) < closestPointScan - 2.5) {
break;
}
pointSqDis = (laserCloudSurfLast->points[j].x - pointSel.x) *
(laserCloudSurfLast->points[j].x - pointSel.x) +
(laserCloudSurfLast->points[j].y - pointSel.y) *
(laserCloudSurfLast->points[j].y - pointSel.y) +
(laserCloudSurfLast->points[j].z - pointSel.z) *
(laserCloudSurfLast->points[j].z - pointSel.z);
if (int(laserCloudSurfLast->points[j].intensity) >= closestPointScan) {
if (pointSqDis < minPointSqDis2) {
minPointSqDis2 = pointSqDis;
minPointInd2 = j;
}
} else {
if (pointSqDis < minPointSqDis3) {
minPointSqDis3 = pointSqDis;
minPointInd3 = j;
}
}
}
}
pointSearchSurfInd1[i] = closestPointInd;
pointSearchSurfInd2[i] = minPointInd2;
pointSearchSurfInd3[i] = minPointInd3;
}
if (pointSearchSurfInd2[i] >= 0 && pointSearchSurfInd3[i] >= 0) {
tripod1 = laserCloudSurfLast->points[pointSearchSurfInd1[i]];
tripod2 = laserCloudSurfLast->points[pointSearchSurfInd2[i]];
tripod3 = laserCloudSurfLast->points[pointSearchSurfInd3[i]];
float pa = (tripod2.y - tripod1.y) * (tripod3.z - tripod1.z)
- (tripod3.y - tripod1.y) * (tripod2.z - tripod1.z);
float pb = (tripod2.z - tripod1.z) * (tripod3.x - tripod1.x)
- (tripod3.z - tripod1.z) * (tripod2.x - tripod1.x);
float pc = (tripod2.x - tripod1.x) * (tripod3.y - tripod1.y)
- (tripod3.x - tripod1.x) * (tripod2.y - tripod1.y);
float pd = -(pa * tripod1.x + pb * tripod1.y + pc * tripod1.z);
float ps = sqrt(pa * pa + pb * pb + pc * pc);
pa /= ps;
pb /= ps;
pc /= ps;
pd /= ps;
float pd2 = pa * pointSel.x + pb * pointSel.y + pc * pointSel.z + pd;
float s = 1;
if (iterCount >= 5) {
s = 1 - 1.8 * fabs(pd2) / sqrt(sqrt(pointSel.x * pointSel.x
+ pointSel.y * pointSel.y + pointSel.z * pointSel.z));
}
if (s > 0.1 && pd2 != 0) {
coeff.x = s * pa;
coeff.y = s * pb;
coeff.z = s * pc;
coeff.intensity = s * pd2;
laserCloudOri->push_back(surfPointsFlat->points[i]);
coeffSel->push_back(coeff);
}
}
}
}
bool calculateTransformationSurf(int iterCount){
int pointSelNum = laserCloudOri->points.size();
cv::Mat matA(pointSelNum, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matAt(3, pointSelNum, CV_32F, cv::Scalar::all(0));
cv::Mat matAtA(3, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matB(pointSelNum, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matAtB(3, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matX(3, 1, CV_32F, cv::Scalar::all(0));
float srx = sin(transformCur[0]);
float crx = cos(transformCur[0]);
float sry = sin(transformCur[1]);
float cry = cos(transformCur[1]);
float srz = sin(transformCur[2]);
float crz = cos(transformCur[2]);
float tx = transformCur[3];
float ty = transformCur[4];
float tz = transformCur[5];
float a1 = crx*sry*srz; float a2 = crx*crz*sry; float a3 = srx*sry; float a4 = tx*a1 - ty*a2 - tz*a3;
float a5 = srx*srz; float a6 = crz*srx; float a7 = ty*a6 - tz*crx - tx*a5;
float a8 = crx*cry*srz; float a9 = crx*cry*crz; float a10 = cry*srx; float a11 = tz*a10 + ty*a9 - tx*a8;
float b1 = -crz*sry - cry*srx*srz; float b2 = cry*crz*srx - sry*srz;
float b5 = cry*crz - srx*sry*srz; float b6 = cry*srz + crz*srx*sry;
float c1 = -b6; float c2 = b5; float c3 = tx*b6 - ty*b5; float c4 = -crx*crz; float c5 = crx*srz; float c6 = ty*c5 + tx*-c4;
float c7 = b2; float c8 = -b1; float c9 = tx*-b2 - ty*-b1;
for (int i = 0; i < pointSelNum; i++) {
pointOri = laserCloudOri->points[i];
coeff = coeffSel->points[i];
float arx = (-a1*pointOri.x + a2*pointOri.y + a3*pointOri.z + a4) * coeff.x
+ (a5*pointOri.x - a6*pointOri.y + crx*pointOri.z + a7) * coeff.y
+ (a8*pointOri.x - a9*pointOri.y - a10*pointOri.z + a11) * coeff.z;
float arz = (c1*pointOri.x + c2*pointOri.y + c3) * coeff.x
+ (c4*pointOri.x - c5*pointOri.y + c6) * coeff.y
+ (c7*pointOri.x + c8*pointOri.y + c9) * coeff.z;
float aty = -b6 * coeff.x + c4 * coeff.y + b2 * coeff.z;
float d2 = coeff.intensity;
matA.at<float>(i, 0) = arx;
matA.at<float>(i, 1) = arz;
matA.at<float>(i, 2) = aty;
matB.at<float>(i, 0) = -0.05 * d2;
}
cv::transpose(matA, matAt);
matAtA = matAt * matA;
matAtB = matAt * matB;
cv::solve(matAtA, matAtB, matX, cv::DECOMP_QR);
if (iterCount == 0) {
cv::Mat matE(1, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matV(3, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matV2(3, 3, CV_32F, cv::Scalar::all(0));
cv::eigen(matAtA, matE, matV);
matV.copyTo(matV2);
isDegenerate = false;
float eignThre[3] = {10, 10, 10};
for (int i = 2; i >= 0; i--) {
if (matE.at<float>(0, i) < eignThre[i]) {
for (int j = 0; j < 3; j++) {
matV2.at<float>(i, j) = 0;
}
isDegenerate = true;
} else {
break;
}
}
matP = matV.inv() * matV2;
}
if (isDegenerate) {
cv::Mat matX2(3, 1, CV_32F, cv::Scalar::all(0));
matX.copyTo(matX2);
matX = matP * matX2;
}
transformCur[0] += matX.at<float>(0, 0);
transformCur[2] += matX.at<float>(1, 0);
transformCur[4] += matX.at<float>(2, 0);
for(int i=0; i<6; i++){
if(isnan(transformCur[i]))
transformCur[i]=0;
}
float deltaR = sqrt(
pow(rad2deg(matX.at<float>(0, 0)), 2) +
pow(rad2deg(matX.at<float>(1, 0)), 2));
float deltaT = sqrt(
pow(matX.at<float>(2, 0) * 100, 2));
if (deltaR < 0.1 && deltaT < 0.1) {
return false;
}
return true;
}
bool calculateTransformationCorner(int iterCount){
int pointSelNum = laserCloudOri->points.size();
cv::Mat matA(pointSelNum, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matAt(3, pointSelNum, CV_32F, cv::Scalar::all(0));
cv::Mat matAtA(3, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matB(pointSelNum, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matAtB(3, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matX(3, 1, CV_32F, cv::Scalar::all(0));
float srx = sin(transformCur[0]);
float crx = cos(transformCur[0]);
float sry = sin(transformCur[1]);
float cry = cos(transformCur[1]);
float srz = sin(transformCur[2]);
float crz = cos(transformCur[2]);
float tx = transformCur[3];
float ty = transformCur[4];
float tz = transformCur[5];
float b1 = -crz*sry - cry*srx*srz; float b2 = cry*crz*srx - sry*srz; float b3 = crx*cry; float b4 = tx*-b1 + ty*-b2 + tz*b3;
float b5 = cry*crz - srx*sry*srz; float b6 = cry*srz + crz*srx*sry; float b7 = crx*sry; float b8 = tz*b7 - ty*b6 - tx*b5;
float c5 = crx*srz;
for (int i = 0; i < pointSelNum; i++) {
pointOri = laserCloudOri->points[i];
coeff = coeffSel->points[i];
float ary = (b1*pointOri.x + b2*pointOri.y - b3*pointOri.z + b4) * coeff.x
+ (b5*pointOri.x + b6*pointOri.y - b7*pointOri.z + b8) * coeff.z;
float atx = -b5 * coeff.x + c5 * coeff.y + b1 * coeff.z;
float atz = b7 * coeff.x - srx * coeff.y - b3 * coeff.z;
float d2 = coeff.intensity;
matA.at<float>(i, 0) = ary;
matA.at<float>(i, 1) = atx;
matA.at<float>(i, 2) = atz;
matB.at<float>(i, 0) = -0.05 * d2;
}
cv::transpose(matA, matAt);
matAtA = matAt * matA;
matAtB = matAt * matB;
cv::solve(matAtA, matAtB, matX, cv::DECOMP_QR);
if (iterCount == 0) {
cv::Mat matE(1, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matV(3, 3, CV_32F, cv::Scalar::all(0));
cv::Mat matV2(3, 3, CV_32F, cv::Scalar::all(0));
cv::eigen(matAtA, matE, matV);
matV.copyTo(matV2);
isDegenerate = false;
float eignThre[3] = {10, 10, 10};
for (int i = 2; i >= 0; i--) {
if (matE.at<float>(0, i) < eignThre[i]) {
for (int j = 0; j < 3; j++) {
matV2.at<float>(i, j) = 0;
}
isDegenerate = true;
} else {
break;
}
}
matP = matV.inv() * matV2;
}
if (isDegenerate) {
cv::Mat matX2(3, 1, CV_32F, cv::Scalar::all(0));
matX.copyTo(matX2);
matX = matP * matX2;
}
transformCur[1] += matX.at<float>(0, 0);
transformCur[3] += matX.at<float>(1, 0);
transformCur[5] += matX.at<float>(2, 0);
for(int i=0; i<6; i++){
if(isnan(transformCur[i]))
transformCur[i]=0;
}
float deltaR = sqrt(
pow(rad2deg(matX.at<float>(0, 0)), 2));
float deltaT = sqrt(
pow(matX.at<float>(1, 0) * 100, 2) +
pow(matX.at<float>(2, 0) * 100, 2));
if (deltaR < 0.1 && deltaT < 0.1) {
return false;
}
return true;
}
bool calculateTransformation(int iterCount){
int pointSelNum = laserCloudOri->points.size();
cv::Mat matA(pointSelNum, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matAt(6, pointSelNum, CV_32F, cv::Scalar::all(0));
cv::Mat matAtA(6, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matB(pointSelNum, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matAtB(6, 1, CV_32F, cv::Scalar::all(0));
cv::Mat matX(6, 1, CV_32F, cv::Scalar::all(0));
float srx = sin(transformCur[0]);
float crx = cos(transformCur[0]);
float sry = sin(transformCur[1]);
float cry = cos(transformCur[1]);
float srz = sin(transformCur[2]);
float crz = cos(transformCur[2]);
float tx = transformCur[3];
float ty = transformCur[4];
float tz = transformCur[5];
float a1 = crx*sry*srz; float a2 = crx*crz*sry; float a3 = srx*sry; float a4 = tx*a1 - ty*a2 - tz*a3;
float a5 = srx*srz; float a6 = crz*srx; float a7 = ty*a6 - tz*crx - tx*a5;
float a8 = crx*cry*srz; float a9 = crx*cry*crz; float a10 = cry*srx; float a11 = tz*a10 + ty*a9 - tx*a8;
float b1 = -crz*sry - cry*srx*srz; float b2 = cry*crz*srx - sry*srz; float b3 = crx*cry; float b4 = tx*-b1 + ty*-b2 + tz*b3;
float b5 = cry*crz - srx*sry*srz; float b6 = cry*srz + crz*srx*sry; float b7 = crx*sry; float b8 = tz*b7 - ty*b6 - tx*b5;
float c1 = -b6; float c2 = b5; float c3 = tx*b6 - ty*b5; float c4 = -crx*crz; float c5 = crx*srz; float c6 = ty*c5 + tx*-c4;
float c7 = b2; float c8 = -b1; float c9 = tx*-b2 - ty*-b1;
for (int i = 0; i < pointSelNum; i++) {
pointOri = laserCloudOri->points[i];
coeff = coeffSel->points[i];
float arx = (-a1*pointOri.x + a2*pointOri.y + a3*pointOri.z + a4) * coeff.x
+ (a5*pointOri.x - a6*pointOri.y + crx*pointOri.z + a7) * coeff.y
+ (a8*pointOri.x - a9*pointOri.y - a10*pointOri.z + a11) * coeff.z;
float ary = (b1*pointOri.x + b2*pointOri.y - b3*pointOri.z + b4) * coeff.x
+ (b5*pointOri.x + b6*pointOri.y - b7*pointOri.z + b8) * coeff.z;
float arz = (c1*pointOri.x + c2*pointOri.y + c3) * coeff.x
+ (c4*pointOri.x - c5*pointOri.y + c6) * coeff.y
+ (c7*pointOri.x + c8*pointOri.y + c9) * coeff.z;
float atx = -b5 * coeff.x + c5 * coeff.y + b1 * coeff.z;
float aty = -b6 * coeff.x + c4 * coeff.y + b2 * coeff.z;
float atz = b7 * coeff.x - srx * coeff.y - b3 * coeff.z;
float d2 = coeff.intensity;
matA.at<float>(i, 0) = arx;
matA.at<float>(i, 1) = ary;
matA.at<float>(i, 2) = arz;
matA.at<float>(i, 3) = atx;
matA.at<float>(i, 4) = aty;
matA.at<float>(i, 5) = atz;
matB.at<float>(i, 0) = -0.05 * d2;
}
cv::transpose(matA, matAt);
matAtA = matAt * matA;
matAtB = matAt * matB;
cv::solve(matAtA, matAtB, matX, cv::DECOMP_QR);
if (iterCount == 0) {
cv::Mat matE(1, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matV(6, 6, CV_32F, cv::Scalar::all(0));
cv::Mat matV2(6, 6, CV_32F, cv::Scalar::all(0));
cv::eigen(matAtA, matE, matV);
matV.copyTo(matV2);
isDegenerate = false;
float eignThre[6] = {10, 10, 10, 10, 10, 10};
for (int i = 5; i >= 0; i--) {
if (matE.at<float>(0, i) < eignThre[i]) {
for (int j = 0; j < 6; j++) {
matV2.at<float>(i, j) = 0;
}
isDegenerate = true;
} else {
break;
}
}
matP = matV.inv() * matV2;
}
if (isDegenerate) {
cv::Mat matX2(6, 1, CV_32F, cv::Scalar::all(0));
matX.copyTo(matX2);
matX = matP * matX2;
}
transformCur[0] += matX.at<float>(0, 0);
transformCur[1] += matX.at<float>(1, 0);
transformCur[2] += matX.at<float>(2, 0);
transformCur[3] += matX.at<float>(3, 0);
transformCur[4] += matX.at<float>(4, 0);
transformCur[5] += matX.at<float>(5, 0);
for(int i=0; i<6; i++){
if(isnan(transformCur[i]))
transformCur[i]=0;
}
float deltaR = sqrt(
pow(rad2deg(matX.at<float>(0, 0)), 2) +
pow(rad2deg(matX.at<float>(1, 0)), 2) +
pow(rad2deg(matX.at<float>(2, 0)), 2));
float deltaT = sqrt(
pow(matX.at<float>(3, 0) * 100, 2) +
pow(matX.at<float>(4, 0) * 100, 2) +
pow(matX.at<float>(5, 0) * 100, 2));
if (deltaR < 0.1 && deltaT < 0.1) {
return false;
}
return true;
}
// 匹配初始化
// 由于激光里程计相临两帧点云进行匹配获取,即当前帧与上一帧进行匹配,故开启slam收到的第一帧点云数据则需要对cloud_last进行赋值,即对上一帧进行记录和存储,不做匹配运算
void checkSystemInitialization(){
pcl::PointCloud<PointType>::Ptr laserCloudTemp = cornerPointsLessSharp; // 第一次last 和 curr 应一样, 即赋初始状态
cornerPointsLessSharp = laserCloudCornerLast;
laserCloudCornerLast = laserCloudTemp;
laserCloudTemp = surfPointsLessFlat;
surfPointsLessFlat = laserCloudSurfLast;
laserCloudSurfLast = laserCloudTemp;
kdtreeCornerLast->setInputCloud(laserCloudCornerLast); // 初始化KD TREE
kdtreeSurfLast->setInputCloud(laserCloudSurfLast);
laserCloudCornerLastNum = laserCloudCornerLast->points.size(); // 获取两种特征点云个数
laserCloudSurfLastNum = laserCloudSurfLast->points.size();
sensor_msgs::PointCloud2 laserCloudCornerLast2;
pcl::toROSMsg(*laserCloudCornerLast, laserCloudCornerLast2);
laserCloudCornerLast2.header.stamp = cloudHeader.stamp;
laserCloudCornerLast2.header.frame_id = "/camera";
pubLaserCloudCornerLast.publish(laserCloudCornerLast2);
sensor_msgs::PointCloud2 laserCloudSurfLast2;
pcl::toROSMsg(*laserCloudSurfLast, laserCloudSurfLast2);
laserCloudSurfLast2.header.stamp = cloudHeader.stamp;
laserCloudSurfLast2.header.frame_id = "/camera";
pubLaserCloudSurfLast.publish(laserCloudSurfLast2);
transformSum[0] += imuPitchStart;
transformSum[2] += imuRollStart;
systemInitedLM = true;
}
void updateInitialGuess(){
imuPitchLast = imuPitchCur;
imuYawLast = imuYawCur;
imuRollLast = imuRollCur;
imuShiftFromStartX = imuShiftFromStartXCur;
imuShiftFromStartY = imuShiftFromStartYCur;
imuShiftFromStartZ = imuShiftFromStartZCur;
imuVeloFromStartX = imuVeloFromStartXCur;
imuVeloFromStartY = imuVeloFromStartYCur;
imuVeloFromStartZ = imuVeloFromStartZCur;
if (imuAngularFromStartX != 0 || imuAngularFromStartY != 0 || imuAngularFromStartZ != 0){
transformCur[0] = - imuAngularFromStartY;
transformCur[1] = - imuAngularFromStartZ;
transformCur[2] = - imuAngularFromStartX;
}
if (imuVeloFromStartX != 0 || imuVeloFromStartY != 0 || imuVeloFromStartZ != 0){
transformCur[3] -= imuVeloFromStartX * scanPeriod;
transformCur[4] -= imuVeloFromStartY * scanPeriod;
transformCur[5] -= imuVeloFromStartZ * scanPeriod;
}
}
// 查找平面特征进行匹配,寻找最近邻三点构成平面,构建点面距离最小二乘求解位姿(高斯牛顿);
// 查找线特征进行匹配,寻找两点构成直线,构建点线距离最小二乘求解位姿(高斯牛顿)。
// 注:默认Lidar坐标系是右下前
void updateTransformation(){
if (laserCloudCornerLastNum < 10 || laserCloudSurfLastNum < 100)
return;
for (int iterCount1 = 0; iterCount1 < 25; iterCount1++) {
laserCloudOri->clear();
coeffSel->clear();
findCorrespondingSurfFeatures(iterCount1);
if (laserCloudOri->points.size() < 10)
continue;
// 通过面特征匹配计算变换矩阵(z,roll,pitch)
if (calculateTransformationSurf(iterCount1) == false)
break;
}
for (int iterCount2 = 0; iterCount2 < 25; iterCount2++) {
laserCloudOri->clear();
coeffSel->clear();
findCorrespondingCornerFeatures(iterCount2); // 找对应的特征线,计算协方差矩阵
if (laserCloudOri->points.size() < 10)
continue;
// 通过线特征匹配结合面特征得出的变换矩阵计算变换矩阵(x,y,yaw)
if (calculateTransformationCorner(iterCount2) == false)
break;
}
}
// 将前后两帧位姿累加,获得对第一帧的位姿,同时从局部坐标系转换到全局坐标系,加入IMU数据更新出位姿,发布里程计信息、tf变换、点云。
void integrateTransformation(){
float rx, ry, rz, tx, ty, tz;
AccumulateRotation(transformSum[0], transformSum[1], transformSum[2],
-transformCur[0], -transformCur[1], -transformCur[2], rx, ry, rz);
float x1 = cos(rz) * (transformCur[3] - imuShiftFromStartX)
- sin(rz) * (transformCur[4] - imuShiftFromStartY);
float y1 = sin(rz) * (transformCur[3] - imuShiftFromStartX)
+ cos(rz) * (transformCur[4] - imuShiftFromStartY);
float z1 = transformCur[5] - imuShiftFromStartZ;
float x2 = x1;
float y2 = cos(rx) * y1 - sin(rx) * z1;
float z2 = sin(rx) * y1 + cos(rx) * z1;
tx = transformSum[3] - (cos(ry) * x2 + sin(ry) * z2);
ty = transformSum[4] - y2;
tz = transformSum[5] - (-sin(ry) * x2 + cos(ry) * z2);
PluginIMURotation(rx, ry, rz, imuPitchStart, imuYawStart, imuRollStart,
imuPitchLast, imuYawLast, imuRollLast, rx, ry, rz);
transformSum[0] = rx;
transformSum[1] = ry;
transformSum[2] = rz;
transformSum[3] = tx;
transformSum[4] = ty;
transformSum[5] = tz;
}
void publishOdometry(){
geometry_msgs::Quaternion geoQuat = tf::createQuaternionMsgFromRollPitchYaw(transformSum[2], -transformSum[0], -transformSum[1]);
laserOdometry.header.stamp = cloudHeader.stamp;
laserOdometry.pose.pose.orientation.x = -geoQuat.y;
laserOdometry.pose.pose.orientation.y = -geoQuat.z;
laserOdometry.pose.pose.orientation.z = geoQuat.x;
laserOdometry.pose.pose.orientation.w = geoQuat.w;
laserOdometry.pose.pose.position.x = transformSum[3];
laserOdometry.pose.pose.position.y = transformSum[4];
laserOdometry.pose.pose.position.z = transformSum[5];
pubLaserOdometry.publish(laserOdometry);
laserOdometryTrans.stamp_ = cloudHeader.stamp;
laserOdometryTrans.setRotation(tf::Quaternion(-geoQuat.y, -geoQuat.z, geoQuat.x, geoQuat.w));
laserOdometryTrans.setOrigin(tf::Vector3(transformSum[3], transformSum[4], transformSum[5]));
tfBroadcaster.sendTransform(laserOdometryTrans);
}
void adjustOutlierCloud(){
PointType point;
int cloudSize = outlierCloud->points.size();
for (int i = 0; i < cloudSize; ++i)
{
point.x = outlierCloud->points[i].y;
point.y = outlierCloud->points[i].z;
point.z = outlierCloud->points[i].x;
point.intensity = outlierCloud->points[i].intensity;
outlierCloud->points[i] = point;
}
}
void publishCloudsLast(){
updateImuRollPitchYawStartSinCos();
int cornerPointsLessSharpNum = cornerPointsLessSharp->points.size();
for (int i = 0; i < cornerPointsLessSharpNum; i++) {
TransformToEnd(&cornerPointsLessSharp->points[i], &cornerPointsLessSharp->points[i]);
}
int surfPointsLessFlatNum = surfPointsLessFlat->points.size();
for (int i = 0; i < surfPointsLessFlatNum; i++) {
TransformToEnd(&surfPointsLessFlat->points[i], &surfPointsLessFlat->points[i]);
}
pcl::PointCloud<PointType>::Ptr laserCloudTemp = cornerPointsLessSharp;
cornerPointsLessSharp = laserCloudCornerLast;
laserCloudCornerLast = laserCloudTemp;
laserCloudTemp = surfPointsLessFlat;
surfPointsLessFlat = laserCloudSurfLast;
laserCloudSurfLast = laserCloudTemp;
laserCloudCornerLastNum = laserCloudCornerLast->points.size();
laserCloudSurfLastNum = laserCloudSurfLast->points.size();
if (laserCloudCornerLastNum > 10 && laserCloudSurfLastNum > 100) {
kdtreeCornerLast->setInputCloud(laserCloudCornerLast);
kdtreeSurfLast->setInputCloud(laserCloudSurfLast);
}
frameCount++;
if (frameCount >= skipFrameNum + 1) {
frameCount = 0;
adjustOutlierCloud();
sensor_msgs::PointCloud2 outlierCloudLast2;
pcl::toROSMsg(*outlierCloud, outlierCloudLast2);
outlierCloudLast2.header.stamp = cloudHeader.stamp;
outlierCloudLast2.header.frame_id = "/camera";
pubOutlierCloudLast.publish(outlierCloudLast2);
sensor_msgs::PointCloud2 laserCloudCornerLast2;
pcl::toROSMsg(*laserCloudCornerLast, laserCloudCornerLast2);
laserCloudCornerLast2.header.stamp = cloudHeader.stamp;
laserCloudCornerLast2.header.frame_id = "/camera";
pubLaserCloudCornerLast.publish(laserCloudCornerLast2);
sensor_msgs::PointCloud2 laserCloudSurfLast2;
pcl::toROSMsg(*laserCloudSurfLast, laserCloudSurfLast2);
laserCloudSurfLast2.header.stamp = cloudHeader.stamp;
laserCloudSurfLast2.header.frame_id = "/camera";
pubLaserCloudSurfLast.publish(laserCloudSurfLast2);
}
}
void runFeatureAssociation()
{
if (newSegmentedCloud && newSegmentedCloudInfo && newOutlierCloud &&
std::abs(timeNewSegmentedCloudInfo - timeNewSegmentedCloud) < 0.05 &&
std::abs(timeNewOutlierCloud - timeNewSegmentedCloud) < 0.05){
newSegmentedCloud = false;
newSegmentedCloudInfo = false;
newOutlierCloud = false;
}else{
return;
}
/**
1. Feature Extraction
*/
adjustDistortion(); // 去运动畸变
calculateSmoothness(); // 计算曲率,以相邻左右五个点计算
markOccludedPoints(); // 标记瑕点,相邻但距离较远的点(平行点被误判为平面点的情况),以及邻域距离变化较大的点(遮挡点被误判为边点的情况)
extractFeatures(); // 特征提取
publishCloud(); // cloud for visualization
/**
2. Feature Association
*/
if (!systemInitedLM) {
checkSystemInitialization();
return;
}
updateInitialGuess();
updateTransformation();
integrateTransformation();
publishOdometry();
publishCloudsLast(); // cloud to mapOptimization
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "lego_loam");
ROS_INFO("\033[1;32m---->\033[0m Feature Association Started.");
FeatureAssociation FA;
ros::Rate rate(200);
while (ros::ok())
{
ros::spinOnce();
FA.runFeatureAssociation();
rate.sleep();
}
ros::spin();
return 0;
}
|
/***************************************************************************
*
* $Id: StMcRichHit.hh,v 2.9 2011/10/17 00:24:00 fisyak Exp $
* $Log: StMcRichHit.hh,v $
* Revision 2.9 2011/10/17 00:24:00 fisyak
* Add time of flight for hits
*
* Revision 2.8 2005/09/28 21:30:15 fisyak
* Persistent StMcEvent
*
* Revision 2.7 2005/07/06 20:05:28 calderon
* Remove forward declaration of StThreeVectorF, use #include, and only in
* StMcHit base class. StThreeVectorF is not a class anymore, it is now
* only a typedef, only template version of StThreeVector exists now.
*
* Revision 2.6 2005/01/27 23:40:47 calderon
* Adding persistency to StMcEvent as a step for Virtual MonteCarlo.
*
* Revision 2.5 2000/06/06 02:58:41 calderon
* Introduction of Calorimeter classes. Modified several classes
* accordingly.
*
* Revision 2.4 2000/05/26 21:42:11 calderon
* Added volumeId() method.
*
* Revision 2.3 2000/05/05 15:25:44 calderon
* Reduced dependencies and made constructors more efficient
*
* Revision 2.2 2000/04/17 23:01:15 calderon
* Added local momentum to hits as per Lee's request
*
* Revision 2.1 2000/03/06 18:05:21 calderon
* 1) Modified SVT Hits storage scheme from layer-ladder-wafer to
* barrel-ladder-wafer.
* 2) Added Rich Hit class and collection, and links to them in other
* classes.
*
*
**************************************************************************/
#ifndef StMcRichHit_hh
#define StMcRichHit_hh
#include "StMcHit.hh"
#include "tables/St_g2t_rch_hit_Table.h"
class StMcRichHit : public StMcHit {
public:
StMcRichHit() {}
StMcRichHit(const StThreeVectorF& x,const StThreeVectorF& p,
Float_t de = 0, Float_t ds = 0, Float_t tof = 0, Long_t k = 0, Long_t volId = 0, StMcTrack* parent=0) :
StMcHit(x,p,de,ds,tof,k,volId,parent) {}
StMcRichHit(g2t_rch_hit_st* pt) :
StMcHit(StThreeVectorF(pt->x[0], pt->x[1], pt->x[2]),
StThreeVectorF(pt->p[0], pt->p[1], pt->p[2]),
pt->de, pt->ds, pt->tof, pt->id, pt->volume_id, 0) {}
~StMcRichHit() {}
UShort_t pad() const {return (mVolumeId & 0xff);} // first 8 bits
UShort_t row() const {return ( (mVolumeId>>8) & 0xff);} // second 8 bits
private:
ClassDef(StMcRichHit,1)
};
ostream& operator<<(ostream& os, const StMcRichHit&);
#endif
|
/*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "map_insdelfind.h"
#include "map_type_skip_list.h"
namespace map {
CDSSTRESS_SkipListMap_RCU( Map_InsDelFind, run_test, size_t, size_t )
} // namespace map
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Abcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "walletmodel.h"
#include "base58.h"
#include "init.h"
#include "validation.h" // For strMessageMagic
#include "wallet/wallet.h"
#include <string>
#include <vector>
#include <QClipboard>
SignVerifyMessageDialog::SignVerifyMessageDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
#endif
QString theme = GUIUtil::getThemeName();
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->signMessageButton_SM->setIcon(QIcon());
ui->clearButton_SM->setIcon(QIcon());
ui->verifyMessageButton_VM->setIcon(QIcon());
ui->clearButton_VM->setIcon(QIcon());
#else
ui->signMessageButton_SM->setIcon(QIcon(":/icons/" + theme + "/edit"));
ui->clearButton_SM->setIcon(QIcon(":/icons/" + theme + "/remove"));
ui->verifyMessageButton_VM->setIcon(QIcon(":/icons/" + theme + "/transaction_0"));
ui->clearButton_VM->setIcon(QIcon(":/icons/" + theme + "/remove"));
#endif
// These icons are needed on Mac also
ui->addressBookButton_SM->setIcon(QIcon(":/icons/" + theme + "/address-book"));
ui->pasteButton_SM->setIcon(QIcon(":/icons/" + theme + "/editpaste"));
ui->copySignatureButton_SM->setIcon(QIcon(":/icons/" + theme + "/editcopy"));
ui->addressBookButton_VM->setIcon(QIcon(":/icons/" + theme + "/address-book"));
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::fixedPitchFont());
ui->signatureIn_VM->setFont(GUIUtil::fixedPitchFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *_model)
{
this->model = _model;
}
void SignVerifyMessageDialog::setAddress_SM(const QString &address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(const QString &address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
if (!model)
return;
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!model->getPrivKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
GUIUtil::setClipboard(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBitcoinAddress(pubkey.GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
|
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog),
mapper(0),
mode(_mode),
model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *_model)
{
this->model = _model;
if(!_model)
return;
mapper->setModel(_model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid PACGlobal address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &_address)
{
this->address = _address;
ui->addressEdit->setText(_address);
}
|
/**
* @file unit-capi-rest-dense_array.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB Inc.
* @copyright Copyright (c) 2016 MIT and Intel Corporation
*
* 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.
*
* @section DESCRIPTION
*
* Tests of C API for dense array operations via a REST server.
*
* This currently is a subset of the normal dense array tests in
* `unit-capi-dense_array.cc` -- not everything is supported via the REST server
* yet. Additionally global order queries have been removed.
*/
#include "catch.hpp"
#include "test/src/helpers.h"
#include "test/src/vfs_helpers.h"
#ifdef _WIN32
#include "tiledb/sm/filesystem/win.h"
#else
#include "tiledb/sm/filesystem/posix.h"
#endif
#include "test/src/helpers.h"
#include "tiledb/sm/c_api/tiledb.h"
#include "tiledb/sm/enums/encryption_type.h"
#include "tiledb/sm/misc/utils.h"
#include "tiledb/sm/rest/rest_client.h"
#include <array>
#include <cassert>
#include <climits>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <sstream>
#include <thread>
using namespace tiledb::test;
struct DenseArrayRESTFx {
// Constant parameters
const char* ATTR_NAME = "a";
const tiledb_datatype_t ATTR_TYPE = TILEDB_INT32;
const char* DIM1_NAME = "x";
const char* DIM2_NAME = "y";
const tiledb_datatype_t DIM_TYPE = TILEDB_INT64;
const int ITER_NUM = 10;
tiledb_encryption_type_t encryption_type = TILEDB_NO_ENCRYPTION;
const char* encryption_key = nullptr;
// TileDB context and VFS
tiledb_ctx_t* ctx_;
tiledb_vfs_t* vfs_;
// Vector of supported filsystems
const std::vector<std::unique_ptr<SupportedFs>> fs_vec_;
const std::string rest_server_uri_ = "http://localhost:8080";
const std::string rest_server_username_ = "unit";
const std::string rest_server_password_ = "unittest";
const std::string TILEDB_URI_PREFIX =
"tiledb://" + rest_server_username_ + "/";
std::set<std::string> to_deregister_;
// Functions
DenseArrayRESTFx();
~DenseArrayRESTFx();
void create_temp_dir(const std::string& path);
void remove_temp_dir(const std::string& path);
void check_sorted_reads(const std::string& path);
void check_incomplete_reads(const std::string& path);
void check_sorted_writes(const std::string& path);
void check_simultaneous_writes(const std::string& path);
void create_dense_array(const std::string& array_name);
void create_dense_array_1_attribute(const std::string& array_name);
void write_dense_array(const std::string& array_name);
void write_dense_array_missing_attributes(const std::string& array_name);
static std::string random_name(const std::string& prefix);
/**
* Creates a 2D dense array.
*
* @param array_name The array name.
* @param tile_extent_0 The tile extent along the first dimension.
* @param tile_extent_1 The tile extent along the second dimension.
* @param domain_0_lo The smallest value of the first dimension domain.
* @param domain_0_hi The largest value of the first dimension domain.
* @param domain_1_lo The smallest value of the second dimension domain.
* @param domain_1_hi The largest value of the second dimension domain.
* @param capacity The tile capacity.
* @param cell_order The cell order.
* @param tile_order The tile order.
*/
void create_dense_array_2D(
const std::string& array_name,
const int64_t tile_extent_0,
const int64_t tile_extent_1,
const int64_t domain_0_lo,
const int64_t domain_0_hi,
const int64_t domain_1_lo,
const int64_t domain_1_hi,
const uint64_t capacity,
const tiledb_layout_t cell_order,
const tiledb_layout_t tile_order);
/**
* Generates a 2D buffer containing the cell values of a 2D array.
* Each cell value equals (row index * total number of columns + col index).
* @param domain_size_0 The domain size of the first dimension.
* @param domain_size_1 The domain size of the second dimension.
* @return The created 2D buffer. Note that the function creates the buffer
* with 'new'. Make sure to delete the returned buffer in the caller
* function.
*/
int** generate_2D_buffer(
const int64_t domain_size_0, const int64_t domain_size_1);
/**
* Reads a subarray oriented by the input boundaries and outputs the buffer
* containing the attribute values of the corresponding cells.
*
* @param array_name The array name.
* @param domain_0_lo The smallest value of the first dimension domain to
* be read.
* @param domain_0_hi The largest value of the first dimension domain to
* be read.
* @param domain_1_lo The smallest value of the second dimension domain to
* be read.
* @param domain_1_hi The largest value of the second dimension domain to
* be read.
* @param read_mode The read mode.
* @return The buffer with the read values. Note that this function is
* creating the buffer with 'new'. Therefore, make sure to properly delete
* it in the caller. On error, it returns NULL.
*/
int* read_dense_array_2D(
const std::string& array_name,
const int64_t domain_0_lo,
const int64_t domain_0_hi,
const int64_t domain_1_lo,
const int64_t domain_1_hi,
const tiledb_query_type_t query_type,
const tiledb_layout_t query_layout);
/**
* Write to a 2D dense array tile by tile. The buffer is initialized
* with row_id*domain_size_1+col_id values.
*
* @param array_name The array name.
* @param domain_size_0 The domain size of the first dimension.
* @param domain_size_1 The domain size of the second dimension.
* @param tile_extent_0 The tile extent along the first dimension.
* @param tile_extent_1 The tile extent along the second dimension.
*/
void write_dense_array_by_tiles(
const std::string& array_name,
const int64_t domain_size_0,
const int64_t domain_size_1,
const int64_t tile_extent_0,
const int64_t tile_extent_1);
/**
* Writes a 2D dense subarray.
*
* @param array_name The array name.
* @param subarray The subarray to focus on, given as a vector of low, high
* values.
* @param write_mode The write mode.
* @param buffer The attribute buffer to be populated and written.
* @param buffer_sizes The buffer sizes to be dispatched to the write command.
*/
void write_dense_subarray_2D(
const std::string& array_name,
int64_t* subarray,
tiledb_query_type_t query_type,
tiledb_layout_t query_layout,
int* buffer,
uint64_t* buffer_sizes);
};
DenseArrayRESTFx::DenseArrayRESTFx()
: fs_vec_(vfs_test_get_fs_vec()) {
// Initialize vfs test
REQUIRE(vfs_test_init(fs_vec_, &ctx_, &vfs_).ok());
std::srand(0);
}
DenseArrayRESTFx::~DenseArrayRESTFx() {
// Close vfs test
REQUIRE(vfs_test_close(fs_vec_, ctx_, vfs_).ok());
tiledb::sm::Config config;
config.set("rest.server_address", rest_server_uri_);
config.set("rest.username", rest_server_username_);
config.set("rest.password", rest_server_password_);
tiledb::sm::RestClient rest_client;
ThreadPool tp;
REQUIRE(tp.init(4).ok());
REQUIRE(rest_client.init(&config, &tp).ok());
for (const auto& uri : to_deregister_) {
CHECK(rest_client.deregister_array_from_rest(tiledb::sm::URI(uri)).ok());
}
tiledb_vfs_free(&vfs_);
CHECK(vfs_ == nullptr);
tiledb_ctx_free(&ctx_);
CHECK(ctx_ == nullptr);
}
void DenseArrayRESTFx::create_temp_dir(const std::string& path) {
remove_temp_dir(path);
REQUIRE(tiledb_vfs_create_dir(ctx_, vfs_, path.c_str()) == TILEDB_OK);
}
void DenseArrayRESTFx::remove_temp_dir(const std::string& path) {
int is_dir = 0;
REQUIRE(tiledb_vfs_is_dir(ctx_, vfs_, path.c_str(), &is_dir) == TILEDB_OK);
if (is_dir)
REQUIRE(tiledb_vfs_remove_dir(ctx_, vfs_, path.c_str()) == TILEDB_OK);
}
void DenseArrayRESTFx::create_dense_array_2D(
const std::string& array_name,
const int64_t tile_extent_0,
const int64_t tile_extent_1,
const int64_t domain_0_lo,
const int64_t domain_0_hi,
const int64_t domain_1_lo,
const int64_t domain_1_hi,
const uint64_t capacity,
const tiledb_layout_t cell_order,
const tiledb_layout_t tile_order) {
// Create attribute
tiledb_attribute_t* a;
int rc = tiledb_attribute_alloc(ctx_, ATTR_NAME, ATTR_TYPE, &a);
REQUIRE(rc == TILEDB_OK);
// Create dimensions
int64_t dim_domain[] = {domain_0_lo, domain_0_hi, domain_1_lo, domain_1_hi};
tiledb_dimension_t* d1;
rc = tiledb_dimension_alloc(
ctx_, DIM1_NAME, TILEDB_INT64, &dim_domain[0], &tile_extent_0, &d1);
REQUIRE(rc == TILEDB_OK);
tiledb_dimension_t* d2;
rc = tiledb_dimension_alloc(
ctx_, DIM2_NAME, TILEDB_INT64, &dim_domain[2], &tile_extent_1, &d2);
REQUIRE(rc == TILEDB_OK);
// Create domain
tiledb_domain_t* domain;
rc = tiledb_domain_alloc(ctx_, &domain);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d1);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d2);
REQUIRE(rc == TILEDB_OK);
// Create array schema
tiledb_array_schema_t* array_schema;
rc = tiledb_array_schema_alloc(ctx_, TILEDB_DENSE, &array_schema);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_capacity(ctx_, array_schema, capacity);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_cell_order(ctx_, array_schema, cell_order);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_tile_order(ctx_, array_schema, tile_order);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_array_schema_set_domain(ctx_, array_schema, domain);
REQUIRE(rc == TILEDB_OK);
// Create the array
if (encryption_type_ != TILEDB_NO_ENCRYPTION) {
tiledb_ctx_free(&ctx_);
tiledb_vfs_free(&vfs_);
tiledb_config_t* config;
tiledb_error_t* error = nullptr;
rc = tiledb_config_alloc(&config, &error);
REQUIRE(rc == TILEDB_OK);
REQUIRE(error == nullptr);
std::string encryption_type_string =
encryption_type_str((tiledb::sm::EncryptionType)encryption_type_);
rc = tiledb_config_set(
config, "sm.encryption_type", encryption_type_string.c_str(), &error);
REQUIRE(error == nullptr);
rc =
tiledb_config_set(config, "sm.encryption_key", encryption_key_, &error);
REQUIRE(rc == TILEDB_OK);
REQUIRE(error == nullptr);
REQUIRE(vfs_test_init(fs_vec_, &ctx_, &vfs_, config).ok());
tiledb_config_free(&config);
}
rc = tiledb_array_create(ctx_, array_name.c_str(), array_schema);
REQUIRE(rc == TILEDB_OK);
to_deregister_.insert(array_name);
// Clean up
tiledb_attribute_free(&a);
tiledb_dimension_free(&d1);
tiledb_dimension_free(&d2);
tiledb_domain_free(&domain);
tiledb_array_schema_free(&array_schema);
}
int** DenseArrayRESTFx::generate_2D_buffer(
const int64_t domain_size_0, const int64_t domain_size_1) {
// Create buffer
auto buffer = new int*[domain_size_0];
// Populate buffer
for (int64_t i = 0; i < domain_size_0; ++i) {
buffer[i] = new int[domain_size_1];
for (int64_t j = 0; j < domain_size_1; ++j) {
buffer[i][j] = (int)(i * domain_size_1 + j);
}
}
// Return
return buffer;
}
int* DenseArrayRESTFx::read_dense_array_2D(
const std::string& array_name,
const int64_t domain_0_lo,
const int64_t domain_0_hi,
const int64_t domain_1_lo,
const int64_t domain_1_hi,
const tiledb_query_type_t query_type,
const tiledb_layout_t query_layout) {
// Error code
int rc;
// Initialize a subarray
const int64_t subarray[] = {
domain_0_lo, domain_0_hi, domain_1_lo, domain_1_hi};
const char* attributes[] = {ATTR_NAME};
// Prepare the buffers that will store the result
int64_t domain_size_0 = domain_0_hi - domain_0_lo + 1;
int64_t domain_size_1 = domain_1_hi - domain_1_lo + 1;
int64_t cell_num = domain_size_0 * domain_size_1;
auto buffer_a1 = new int[cell_num];
REQUIRE(buffer_a1 != nullptr);
void* buffers[] = {buffer_a1};
uint64_t buffer_size_a1 = cell_num * sizeof(int);
uint64_t buffer_sizes[] = {buffer_size_a1};
// Open array
tiledb_array_t* array;
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
if (encryption_type != TILEDB_NO_ENCRYPTION) {
tiledb_config_t* cfg;
tiledb_error_t* err = nullptr;
rc = tiledb_config_alloc(&cfg, &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
std::string encryption_type_string =
encryption_type_str((tiledb::sm::EncryptionType)encryption_type);
rc = tiledb_config_set(
cfg, "sm.encryption_type", encryption_type_string.c_str(), &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
rc = tiledb_config_set(cfg, "sm.encryption_key", encryption_key, &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
rc = tiledb_array_set_config(ctx_, array, cfg);
REQUIRE(rc == TILEDB_OK);
tiledb_config_free(&cfg);
}
rc = tiledb_array_open(ctx_, array, query_type);
CHECK(rc == TILEDB_OK);
// Create query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, query_type, &query);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, query_layout);
REQUIRE(rc == TILEDB_OK);
// Check that the query has no results yet
int has_results;
rc = tiledb_query_has_results(ctx_, query, &has_results);
CHECK(rc == TILEDB_OK);
CHECK(!has_results);
// Read from array
rc = tiledb_query_submit(ctx_, query);
REQUIRE(rc == TILEDB_OK);
// Now the query must have results
rc = tiledb_query_has_results(ctx_, query, &has_results);
CHECK(rc == TILEDB_OK);
CHECK(has_results);
rc = tiledb_query_finalize(ctx_, query);
REQUIRE(rc == TILEDB_OK);
rc =
tiledb_query_finalize(ctx_, query); // Second time must create no problem
REQUIRE(rc == TILEDB_OK);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
CHECK(array == nullptr);
tiledb_query_free(&query);
CHECK(query == nullptr);
// Success - return the created buffer
return buffer_a1;
}
void DenseArrayRESTFx::write_dense_array_by_tiles(
const std::string& array_name,
const int64_t domain_size_0,
const int64_t domain_size_1,
const int64_t tile_extent_0,
const int64_t tile_extent_1) {
// Error code
int rc;
// Other initializations
auto buffer = generate_2D_buffer(domain_size_0, domain_size_1);
int64_t cell_num_in_tile = tile_extent_0 * tile_extent_1;
auto buffer_a1 = new int[cell_num_in_tile];
for (int64_t i = 0; i < cell_num_in_tile; ++i)
buffer_a1[i] = 0;
void* buffers[2];
buffers[0] = buffer_a1;
uint64_t buffer_sizes[2];
int64_t index = 0L;
uint64_t buffer_size = 0L;
const char* attributes[] = {ATTR_NAME};
// Open array
tiledb_array_t* array;
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
if (encryption_type != TILEDB_NO_ENCRYPTION) {
tiledb_config_t* cfg;
tiledb_error_t* err = nullptr;
rc = tiledb_config_alloc(&cfg, &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
std::string encryption_type_string =
encryption_type_str((tiledb::sm::EncryptionType)encryption_type);
rc = tiledb_config_set(
cfg, "sm.encryption_type", encryption_type_string.c_str(), &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
rc = tiledb_config_set(cfg, "sm.encryption_key", encryption_key, &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
rc = tiledb_array_set_config(ctx_, array, cfg);
REQUIRE(rc == TILEDB_OK);
tiledb_config_free(&cfg);
}
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
// Populate and write tile by tile
for (int64_t i = 0; i < domain_size_0; i += tile_extent_0) {
for (int64_t j = 0; j < domain_size_1; j += tile_extent_1) {
// Create query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]);
REQUIRE(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
REQUIRE(rc == TILEDB_OK);
int64_t tile_rows = ((i + tile_extent_0) < domain_size_0) ?
tile_extent_0 :
(domain_size_0 - i);
int64_t tile_cols = ((j + tile_extent_1) < domain_size_1) ?
tile_extent_1 :
(domain_size_1 - j);
int64_t subarray[4] = {i, i + tile_rows - 1, j, j + tile_cols - 1};
rc = tiledb_query_set_subarray(ctx_, query, subarray);
REQUIRE(rc == TILEDB_OK);
int64_t k = 0, l = 0;
for (k = 0; k < tile_rows; ++k) {
for (l = 0; l < tile_cols; ++l) {
index = uint64_t(k * tile_cols + l);
buffer_a1[index] = buffer[uint64_t(i + k)][uint64_t(j + l)];
}
}
buffer_size = k * l * sizeof(int);
buffer_sizes[0] = {buffer_size};
rc = tiledb_query_submit(ctx_, query);
REQUIRE(rc == TILEDB_OK);
tiledb_query_free(&query);
}
}
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
for (int64_t i = 0; i < domain_size_0; ++i)
delete[] buffer[i];
delete[] buffer;
delete[] buffer_a1;
}
void DenseArrayRESTFx::write_dense_subarray_2D(
const std::string& array_name,
int64_t* subarray,
tiledb_query_type_t query_type,
tiledb_layout_t query_layout,
int* buffer,
uint64_t* buffer_sizes) {
// Attribute to focus on and buffers
const char* attributes[] = {ATTR_NAME};
void* buffers[] = {buffer};
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK_SAFE(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, query_type);
CHECK_SAFE(rc == TILEDB_OK);
// Create query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, query_type, &query);
REQUIRE_SAFE(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]);
REQUIRE_SAFE(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
REQUIRE_SAFE(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, query_layout);
REQUIRE_SAFE(rc == TILEDB_OK);
// Submit query
rc = tiledb_query_submit(ctx_, query);
REQUIRE_SAFE(rc == TILEDB_OK);
rc = tiledb_query_finalize(ctx_, query);
REQUIRE_SAFE(rc == TILEDB_OK);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK_SAFE(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void DenseArrayRESTFx::check_sorted_reads(const std::string& path) {
// Parameters used in this test
int64_t domain_size_0 = 5000;
int64_t domain_size_1 = 10000;
int64_t tile_extent_0 = 1000;
int64_t tile_extent_1 = 1000;
int64_t domain_0_lo = 0;
int64_t domain_0_hi = domain_size_0 - 1;
int64_t domain_1_lo = 0;
int64_t domain_1_hi = domain_size_1 - 1;
uint64_t capacity = 1000000;
tiledb_layout_t cell_order = TILEDB_ROW_MAJOR;
tiledb_layout_t tile_order = TILEDB_ROW_MAJOR;
std::string array_name = TILEDB_URI_PREFIX + path + "sorted_reads_array";
// Create a dense integer array
create_dense_array_2D(
array_name,
tile_extent_0,
tile_extent_1,
domain_0_lo,
domain_0_hi,
domain_1_lo,
domain_1_hi,
capacity,
cell_order,
tile_order);
// Write array cells with value = row id * COLUMNS + col id
// to disk tile by tile
write_dense_array_by_tiles(
array_name, domain_size_0, domain_size_1, tile_extent_0, tile_extent_1);
// Test random subarrays and check with corresponding value set by
// row_id*dim1+col_id. Top left corner is always 4,4.
int64_t d0_lo = 4;
int64_t d0_hi = 0;
int64_t d1_lo = 4;
int64_t d1_hi = 0;
int64_t height = 0, width = 0;
for (int iter = 0; iter < ITER_NUM; ++iter) {
height = std::rand() % (domain_size_0 - d0_lo);
width = std::rand() % (domain_size_1 - d1_lo);
d0_hi = d0_lo + height;
d1_hi = d1_lo + width;
int64_t index = 0;
// Read subarray
int* buffer = read_dense_array_2D(
array_name, d0_lo, d0_hi, d1_lo, d1_hi, TILEDB_READ, TILEDB_ROW_MAJOR);
REQUIRE(buffer != NULL);
bool allok = true;
// Check
for (int64_t i = d0_lo; i <= d0_hi; ++i) {
for (int64_t j = d1_lo; j <= d1_hi; ++j) {
bool match = (buffer[index] == i * domain_size_1 + j);
if (!match) {
allok = false;
std::cout << "mismatch: " << i << "," << j << "=" << buffer[index]
<< "!=" << ((i * domain_size_1 + j)) << "\n";
break;
}
++index;
}
if (!allok)
break;
}
REQUIRE(allok);
// Clean up
delete[] buffer;
}
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
if (encryption_type != TILEDB_NO_ENCRYPTION) {
tiledb_config_t* cfg;
tiledb_error_t* err = nullptr;
rc = tiledb_config_alloc(&cfg, &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
std::string encryption_type_string =
encryption_type_str((tiledb::sm::EncryptionType)encryption_type);
rc = tiledb_config_set(
cfg, "sm.encryption_type", encryption_type_string.c_str(), &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
rc = tiledb_config_set(cfg, "sm.encryption_key", encryption_key, &err);
REQUIRE(rc == TILEDB_OK);
REQUIRE(err == nullptr);
rc = tiledb_array_set_config(ctx_, array, cfg);
REQUIRE(rc == TILEDB_OK);
tiledb_config_free(&cfg);
CHECK(rc == TILEDB_OK);
}
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
// Check out of bounds subarray
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
REQUIRE(rc == TILEDB_OK);
int64_t subarray_1[] = {-1, 5, 10, 10};
rc = tiledb_query_set_subarray(ctx_, query, subarray_1);
CHECK(rc == TILEDB_ERR);
int64_t subarray_2[] = {0, 5000000, 10, 10};
rc = tiledb_query_set_subarray(ctx_, query, subarray_2);
CHECK(rc == TILEDB_ERR);
int64_t subarray_3[] = {0, 5, -1, 10};
rc = tiledb_query_set_subarray(ctx_, query, subarray_3);
CHECK(rc == TILEDB_ERR);
int64_t subarray_4[] = {0, 5, 10, 100000000};
rc = tiledb_query_set_subarray(ctx_, query, subarray_4);
CHECK(rc == TILEDB_ERR);
int64_t subarray_5[] = {0, 5, 10, 10};
rc = tiledb_query_set_subarray(ctx_, query, subarray_5);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_finalize(ctx_, query);
REQUIRE(rc == TILEDB_OK);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void DenseArrayRESTFx::check_incomplete_reads(const std::string& path) {
// Parameters used in this test
int64_t domain_size_0 = 5000;
int64_t domain_size_1 = 10000;
int64_t tile_extent_0 = 1000;
int64_t tile_extent_1 = 1000;
int64_t domain_0_lo = 0;
int64_t domain_0_hi = domain_size_0 - 1;
int64_t domain_1_lo = 0;
int64_t domain_1_hi = domain_size_1 - 1;
uint64_t capacity = 1000000;
tiledb_layout_t cell_order = TILEDB_ROW_MAJOR;
tiledb_layout_t tile_order = TILEDB_ROW_MAJOR;
std::string array_name = TILEDB_URI_PREFIX + path + "incomplete_reads_array";
// Create a dense integer array
create_dense_array_2D(
array_name,
tile_extent_0,
tile_extent_1,
domain_0_lo,
domain_0_hi,
domain_1_lo,
domain_1_hi,
capacity,
cell_order,
tile_order);
// Write array cells with value = row id * COLUMNS + col id
// to disk tile by tile
write_dense_array_by_tiles(
array_name, domain_size_0, domain_size_1, tile_extent_0, tile_extent_1);
// Open array
tiledb_array_t* array;
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_READ) == TILEDB_OK);
// Create query
tiledb_query_t* query;
REQUIRE(tiledb_query_alloc(ctx_, array, TILEDB_READ, &query) == TILEDB_OK);
int64_t subarray[] = {0, 50, 0, 50};
int32_t attr_buffer[100];
uint64_t attr_buffer_size = sizeof(attr_buffer);
REQUIRE(tiledb_query_set_subarray(ctx_, query, subarray) == TILEDB_OK);
unsigned num_incompletes = 0;
std::vector<int32_t> all_attr_values;
while (true) {
// Reset buffers and resubmit
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, ATTR_NAME, attr_buffer, &attr_buffer_size) ==
TILEDB_OK);
REQUIRE(tiledb_query_submit(ctx_, query) == TILEDB_OK);
tiledb_query_status_t status;
REQUIRE(tiledb_query_get_status(ctx_, query, &status) == TILEDB_OK);
REQUIRE(attr_buffer_size > 0);
for (uint64_t i = 0; i < (attr_buffer_size / sizeof(int32_t)); i++)
all_attr_values.push_back(attr_buffer[i]);
if (status == TILEDB_INCOMPLETE)
num_incompletes++;
else
break;
}
// Check size of results
REQUIRE(num_incompletes > 1);
REQUIRE(
all_attr_values.size() ==
static_cast<size_t>(
(subarray[1] - subarray[0] + 1) * (subarray[3] - subarray[2] + 1)));
// Check all attribute values from all queries.
bool allok = true;
uint64_t index = 0;
for (int64_t i = subarray[0]; i <= subarray[1]; ++i) {
for (int64_t j = subarray[2]; j <= subarray[3]; ++j) {
bool match = (all_attr_values[index] == i * domain_size_1 + j);
if (!match) {
allok = false;
std::cout << "mismatch: " << i << "," << j << "="
<< all_attr_values[index] << "!=" << ((i * domain_size_1 + j))
<< "\n";
break;
}
++index;
}
if (!allok)
break;
}
REQUIRE(allok);
// Close array
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void DenseArrayRESTFx::check_sorted_writes(const std::string& path) {
// Parameters used in this test
int64_t domain_size_0 = 100;
int64_t domain_size_1 = 100;
int64_t tile_extent_0 = 10;
int64_t tile_extent_1 = 10;
int64_t domain_0_lo = 0;
int64_t domain_0_hi = domain_size_0 - 1;
int64_t domain_1_lo = 0;
int64_t domain_1_hi = domain_size_1 - 1;
uint64_t capacity = 1000;
tiledb_layout_t cell_order = TILEDB_ROW_MAJOR;
tiledb_layout_t tile_order = TILEDB_ROW_MAJOR;
std::string array_name = TILEDB_URI_PREFIX + path + "sorted_writes_array";
// Create a dense integer array
create_dense_array_2D(
array_name,
tile_extent_0,
tile_extent_1,
domain_0_lo,
domain_0_hi,
domain_1_lo,
domain_1_hi,
capacity,
cell_order,
tile_order);
// Write random subarray, then read it back and check
int64_t d0[2], d1[2];
for (int i = 0; i < ITER_NUM; ++i) {
// Create subarray
d0[0] = std::rand() % domain_size_0;
d1[0] = std::rand() % domain_size_1;
d0[1] = d0[0] + std::rand() % (domain_size_0 - d0[0]);
d1[1] = d1[0] + std::rand() % (domain_size_1 - d1[0]);
int64_t subarray[] = {d0[0], d0[1], d1[0], d1[1]};
// Prepare buffers
int64_t subarray_length[2] = {d0[1] - d0[0] + 1, d1[1] - d1[0] + 1};
int64_t cell_num_in_subarray = subarray_length[0] * subarray_length[1];
auto buffer = new int[cell_num_in_subarray];
int64_t index = 0;
uint64_t buffer_size = cell_num_in_subarray * sizeof(int);
uint64_t buffer_sizes[] = {buffer_size};
for (int64_t r = 0; r < subarray_length[0]; ++r)
for (int64_t c = 0; c < subarray_length[1]; ++c)
buffer[index++] = -(std::rand() % 999999);
// Write 2D subarray
write_dense_subarray_2D(
array_name,
subarray,
TILEDB_WRITE,
TILEDB_ROW_MAJOR,
buffer,
buffer_sizes);
// Read back the same subarray
int* read_buffer = read_dense_array_2D(
array_name,
subarray[0],
subarray[1],
subarray[2],
subarray[3],
TILEDB_READ,
TILEDB_ROW_MAJOR);
REQUIRE(read_buffer != NULL);
// Check the two buffers
bool allok = true;
for (index = 0; index < cell_num_in_subarray; ++index) {
if (buffer[index] != read_buffer[index]) {
allok = false;
break;
}
}
REQUIRE(allok);
// Clean up
delete[] buffer;
delete[] read_buffer;
}
}
void DenseArrayRESTFx::check_simultaneous_writes(const std::string& path) {
// Parameters used in this test
int64_t domain_size_0 = 100;
int64_t domain_size_1 = 100;
int64_t tile_extent_0 = 10;
int64_t tile_extent_1 = 10;
int64_t domain_0_lo = 0;
int64_t domain_0_hi = domain_size_0 - 1;
int64_t domain_1_lo = 0;
int64_t domain_1_hi = domain_size_1 - 1;
uint64_t capacity = 1000;
tiledb_layout_t cell_order = TILEDB_ROW_MAJOR;
tiledb_layout_t tile_order = TILEDB_ROW_MAJOR;
std::string array_name =
TILEDB_URI_PREFIX + path + "simultaneous_writes_array";
// Create a dense integer array
create_dense_array_2D(
array_name,
tile_extent_0,
tile_extent_1,
domain_0_lo,
domain_0_hi,
domain_1_lo,
domain_1_hi,
capacity,
cell_order,
tile_order);
int nthreads = std::thread::hardware_concurrency();
std::vector<int*> buffers;
std::vector<std::array<uint64_t, 1>> buffer_sizes;
std::vector<std::array<int64_t, 4>> subarrays;
std::vector<std::thread> threads;
// Pre-generate buffers to write
for (int i = 0; i < nthreads; i++) {
subarrays.push_back({{domain_0_lo,
domain_0_lo + tile_extent_0 - 1,
domain_1_lo,
domain_1_lo + tile_extent_1 - 1}});
buffer_sizes.push_back({{tile_extent_0 * tile_extent_1 * sizeof(int)}});
buffers.push_back(new int[buffer_sizes.back()[0] / sizeof(int)]);
}
// Write multiple subarrays in parallel with a shared context.
for (int i = 0; i < nthreads; i++) {
threads.emplace_back([&, i]() {
const int writes_per_thread = 5;
for (int j = 0; j < writes_per_thread; j++) {
write_dense_subarray_2D(
array_name,
subarrays[i].data(),
TILEDB_WRITE,
TILEDB_ROW_MAJOR,
buffers[i],
buffer_sizes[i].data());
}
});
}
for (auto& t : threads) {
t.join();
}
for (int* buffer : buffers) {
delete[] buffer;
}
}
void DenseArrayRESTFx::create_dense_array(const std::string& array_name) {
// Create dimensions
uint64_t dim_domain[] = {1, 4, 1, 4};
uint64_t tile_extents[] = {2, 2};
tiledb_dimension_t* d1;
int rc = tiledb_dimension_alloc(
ctx_, "d1", TILEDB_UINT64, &dim_domain[0], &tile_extents[0], &d1);
CHECK(rc == TILEDB_OK);
tiledb_dimension_t* d2;
rc = tiledb_dimension_alloc(
ctx_, "d2", TILEDB_UINT64, &dim_domain[2], &tile_extents[1], &d2);
CHECK(rc == TILEDB_OK);
// Create domain
tiledb_domain_t* domain;
rc = tiledb_domain_alloc(ctx_, &domain);
CHECK(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d1);
CHECK(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d2);
CHECK(rc == TILEDB_OK);
// Create attributes
tiledb_attribute_t* a1;
rc = tiledb_attribute_alloc(ctx_, "a1", TILEDB_INT32, &a1);
CHECK(rc == TILEDB_OK);
rc = set_attribute_compression_filter(ctx_, a1, TILEDB_FILTER_LZ4, -1);
CHECK(rc == TILEDB_OK);
rc = tiledb_attribute_set_cell_val_num(ctx_, a1, 1);
CHECK(rc == TILEDB_OK);
tiledb_attribute_t* a2;
CHECK(rc == TILEDB_OK);
rc = tiledb_attribute_alloc(ctx_, "a2", TILEDB_CHAR, &a2);
CHECK(rc == TILEDB_OK);
rc = set_attribute_compression_filter(ctx_, a2, TILEDB_FILTER_GZIP, -1);
CHECK(rc == TILEDB_OK);
rc = tiledb_attribute_set_cell_val_num(ctx_, a2, TILEDB_VAR_NUM);
CHECK(rc == TILEDB_OK);
tiledb_attribute_t* a3;
CHECK(rc == TILEDB_OK);
rc = tiledb_attribute_alloc(ctx_, "a3", TILEDB_FLOAT32, &a3);
CHECK(rc == TILEDB_OK);
rc = set_attribute_compression_filter(ctx_, a3, TILEDB_FILTER_ZSTD, -1);
CHECK(rc == TILEDB_OK);
rc = tiledb_attribute_set_cell_val_num(ctx_, a3, 2);
CHECK(rc == TILEDB_OK);
// Create array schema
tiledb_array_schema_t* array_schema;
rc = tiledb_array_schema_alloc(ctx_, TILEDB_DENSE, &array_schema);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_set_cell_order(ctx_, array_schema, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_set_tile_order(ctx_, array_schema, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_set_domain(ctx_, array_schema, domain);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a1);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a2);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a3);
CHECK(rc == TILEDB_OK);
// Check array schema
rc = tiledb_array_schema_check(ctx_, array_schema);
CHECK(rc == TILEDB_OK);
// Create array
rc = tiledb_array_create(ctx_, array_name.c_str(), array_schema);
CHECK(rc == TILEDB_OK);
to_deregister_.insert(array_name);
// Clean up
tiledb_attribute_free(&a1);
tiledb_attribute_free(&a2);
tiledb_attribute_free(&a3);
tiledb_dimension_free(&d1);
tiledb_dimension_free(&d2);
tiledb_domain_free(&domain);
tiledb_array_schema_free(&array_schema);
}
void DenseArrayRESTFx::create_dense_array_1_attribute(
const std::string& array_name) {
// Create dimensions
uint64_t dim_domain[] = {1, 4, 1, 4};
uint64_t tile_extents[] = {2, 2};
tiledb_dimension_t* d1;
int rc = tiledb_dimension_alloc(
ctx_, "d1", TILEDB_UINT64, &dim_domain[0], &tile_extents[0], &d1);
CHECK(rc == TILEDB_OK);
tiledb_dimension_t* d2;
rc = tiledb_dimension_alloc(
ctx_, "d2", TILEDB_UINT64, &dim_domain[2], &tile_extents[1], &d2);
CHECK(rc == TILEDB_OK);
// Create domain
tiledb_domain_t* domain;
rc = tiledb_domain_alloc(ctx_, &domain);
CHECK(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d1);
CHECK(rc == TILEDB_OK);
rc = tiledb_domain_add_dimension(ctx_, domain, d2);
CHECK(rc == TILEDB_OK);
// Create attributes
tiledb_attribute_t* a1;
rc = tiledb_attribute_alloc(ctx_, "a1", TILEDB_INT32, &a1);
CHECK(rc == TILEDB_OK);
// Create array schema
tiledb_array_schema_t* array_schema;
rc = tiledb_array_schema_alloc(ctx_, TILEDB_DENSE, &array_schema);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_set_cell_order(ctx_, array_schema, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_set_tile_order(ctx_, array_schema, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_set_domain(ctx_, array_schema, domain);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_add_attribute(ctx_, array_schema, a1);
CHECK(rc == TILEDB_OK);
// Check array schema
rc = tiledb_array_schema_check(ctx_, array_schema);
CHECK(rc == TILEDB_OK);
// Create array
rc = tiledb_array_create(ctx_, array_name.c_str(), array_schema);
CHECK(rc == TILEDB_OK);
to_deregister_.insert(array_name);
// Clean up
tiledb_attribute_free(&a1);
tiledb_dimension_free(&d1);
tiledb_dimension_free(&d2);
tiledb_domain_free(&domain);
tiledb_array_schema_free(&array_schema);
}
void DenseArrayRESTFx::write_dense_array(const std::string& array_name) {
// Set attributes
const char* attributes[] = {"a1", "a2", "a3"};
// Prepare cell buffers
// clang-format off
int buffer_a1[] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15
};
uint64_t buffer_a2[] = {
0, 1, 3, 6, 10, 11, 13, 16,
20, 21, 23, 26, 30, 31, 33, 36
};
char buffer_var_a2[] =
"abbcccdddd"
"effggghhhh"
"ijjkkkllll"
"mnnooopppp";
float buffer_a3[] = {
0.1f, 0.2f, 1.1f, 1.2f, 2.1f, 2.2f, 3.1f, 3.2f,
4.1f, 4.2f, 5.1f, 5.2f, 6.1f, 6.2f, 7.1f, 7.2f,
8.1f, 8.2f, 9.1f, 9.2f, 10.1f, 10.2f, 11.1f, 11.2f,
12.1f, 12.2f, 13.1f, 13.2f, 14.1f, 14.2f, 15.1f, 15.2f,
};
void* buffers[] = { buffer_a1, buffer_a2, buffer_var_a2, buffer_a3 };
uint64_t buffer_sizes[] =
{
sizeof(buffer_a1),
sizeof(buffer_a2),
sizeof(buffer_var_a2)-1, // No need to store the last '\0' character
sizeof(buffer_a3)
};
// clang-format on
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
// Create query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[1], buffers[2], &buffer_sizes[2]);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_offsets_buffer(
ctx_, query, attributes[1], (uint64_t*)buffers[1], &buffer_sizes[1]);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[2], buffers[3], &buffer_sizes[3]);
CHECK(rc == TILEDB_OK);
// Submit query
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
// Finalize query
rc = tiledb_query_finalize(ctx_, query);
CHECK(rc == TILEDB_OK);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
void DenseArrayRESTFx::write_dense_array_missing_attributes(
const std::string& array_name) {
// Set attributes
const char* attributes[] = {"a1", "a2", "a3"};
// Prepare cell buffers
// clang-format off
int buffer_a1[] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15
};
uint64_t buffer_a2[] = {
0, 1, 3, 6, 10, 11, 13, 16,
20, 21, 23, 26, 30, 31, 33, 36
};
char buffer_var_a2[] =
"abbcccdddd"
"effggghhhh"
"ijjkkkllll"
"mnnooopppp";
float buffer_a3[] = {
0.1f, 0.2f, 1.1f, 1.2f, 2.1f, 2.2f, 3.1f, 3.2f,
4.1f, 4.2f, 5.1f, 5.2f, 6.1f, 6.2f, 7.1f, 7.2f,
8.1f, 8.2f, 9.1f, 9.2f, 10.1f, 10.2f, 11.1f, 11.2f,
12.1f, 12.2f, 13.1f, 13.2f, 14.1f, 14.2f, 15.1f, 15.2f,
};
void* buffers[] = { buffer_a1, buffer_a2, buffer_var_a2, buffer_a3 };
uint64_t buffer_sizes[] =
{
sizeof(buffer_a1),
sizeof(buffer_a2),
sizeof(buffer_var_a2)-1, // No need to store the last '\0' character
sizeof(buffer_a3)
};
// clang-format on
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
// Create query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_GLOBAL_ORDER);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[1], buffers[2], &buffer_sizes[2]);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_offsets_buffer(
ctx_, query, attributes[1], (uint64_t*)buffers[1], &buffer_sizes[1]);
CHECK(rc == TILEDB_OK);
// Observe we omit setting buffer for one of the attributes (a3)
// Submit query - this should fail
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_ERR);
// Close array
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
}
std::string DenseArrayRESTFx::random_name(const std::string& prefix) {
std::stringstream ss;
ss << prefix << "-" << std::this_thread::get_id() << "-"
<< TILEDB_TIMESTAMP_NOW_MS;
return ss.str();
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, sorted reads",
"[capi][dense][rest]") {
// TODO: refactor for each supported FS.
std::string temp_dir = fs_vec_[0]->temp_dir();
create_temp_dir(temp_dir);
check_sorted_reads(temp_dir);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, sorted writes",
"[capi][dense][rest]") {
// TODO: refactor for each supported FS.
std::string temp_dir = fs_vec_[0]->temp_dir();
create_temp_dir(temp_dir);
check_sorted_writes(temp_dir);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, simultaneous writes",
"[capi][dense][rest][dense-simultaneous-writes]") {
// TODO: refactor for each supported FS.
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
create_temp_dir(temp_dir);
check_simultaneous_writes(temp_dir);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, global order reads",
"[capi][dense][rest]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = TILEDB_URI_PREFIX + temp_dir + "global_order_reads/";
create_temp_dir(temp_dir);
create_dense_array(array_name);
write_dense_array(array_name);
tiledb_array_t* array;
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_READ) == TILEDB_OK);
uint64_t subarray[] = {1, 4, 1, 4};
uint64_t buffer_a1_size = 1024;
uint64_t buffer_a2_off_size = 1024;
uint64_t buffer_a2_val_size = 1024;
uint64_t buffer_a3_size = 1024;
uint64_t buffer_coords_size = 1024;
auto buffer_a1 = (int*)malloc(buffer_a1_size);
auto buffer_a2_off = (uint64_t*)malloc(buffer_a2_off_size);
auto buffer_a2_val = (char*)malloc(buffer_a2_val_size);
auto buffer_a3 = (float*)malloc(buffer_a3_size);
auto buffer_coords = (uint64_t*)malloc(buffer_coords_size);
tiledb_query_t* query;
REQUIRE(tiledb_query_alloc(ctx_, array, TILEDB_READ, &query) == TILEDB_OK);
REQUIRE(
tiledb_query_set_layout(ctx_, query, TILEDB_GLOBAL_ORDER) == TILEDB_OK);
REQUIRE(tiledb_query_set_subarray(ctx_, query, subarray) == TILEDB_OK);
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, "a1", buffer_a1, &buffer_a1_size) == TILEDB_OK);
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, "a2", buffer_a2_val, &buffer_a2_val_size) == TILEDB_OK);
REQUIRE(
tiledb_query_set_offsets_buffer(
ctx_, query, "a2", buffer_a2_off, &buffer_a2_off_size) == TILEDB_OK);
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, "a3", buffer_a3, &buffer_a3_size) == TILEDB_OK);
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, "d1", buffer_coords, &buffer_coords_size) == TILEDB_OK);
REQUIRE(tiledb_query_submit(ctx_, query) == TILEDB_OK);
tiledb_query_status_t status;
REQUIRE(tiledb_query_get_status(ctx_, query, &status) == TILEDB_OK);
REQUIRE(status == TILEDB_COMPLETED);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
// Clean up
tiledb_array_free(&array);
tiledb_query_free(&query);
free(buffer_a1);
free(buffer_a2_off);
free(buffer_a2_val);
free(buffer_a3);
free(buffer_coords);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, missing attributes in writes",
"[capi][dense]][rest][dense-write-missing-attributes]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name =
TILEDB_URI_PREFIX + temp_dir + "dense_write_missing_attributes/";
create_temp_dir(temp_dir);
create_dense_array(array_name);
write_dense_array_missing_attributes(array_name);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, read subarrays with empty cells",
"[capi][dense][rest][dense-read-empty]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = TILEDB_URI_PREFIX + temp_dir + "dense_read_empty/";
create_temp_dir(temp_dir);
create_dense_array_1_attribute(array_name);
// Write a slice
const char* attributes[] = {"a1"};
int write_a1[] = {1, 2, 3, 4};
uint64_t write_a1_size = sizeof(write_a1);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], write_a1, &write_a1_size);
CHECK(rc == TILEDB_OK);
uint64_t subarray[] = {2, 3, 1, 2};
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
// Read whole array
uint64_t subarray_read[] = {1, 4, 1, 4};
int c_a1[] = {INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
1,
2,
INT_MIN,
INT_MIN,
3,
4,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN};
int read_a1[16];
uint64_t read_a1_size = sizeof(read_a1);
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray_read);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], read_a1, &read_a1_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
CHECK(!memcmp(c_a1, read_a1, sizeof(c_a1)));
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, read subarrays with empty areas, merging "
"adjacent cell ranges",
"[capi][dense][rest][dense-read-empty][dense-read-empty-merge]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name =
TILEDB_URI_PREFIX + temp_dir + "dense_read_empty_merge/";
create_temp_dir(temp_dir);
create_dense_array_1_attribute(array_name);
// Write a slice
const char* attributes[] = {"a1"};
int write_a1[] = {1, 2, 3, 4};
uint64_t write_a1_size = sizeof(write_a1);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], write_a1, &write_a1_size);
CHECK(rc == TILEDB_OK);
uint64_t subarray[] = {2, 3, 2, 3};
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
// Read whole array
uint64_t subarray_read[] = {1, 4, 1, 4};
int c_a1[] = {INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
1,
2,
INT_MIN,
INT_MIN,
3,
4,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN};
int read_a1[16];
uint64_t read_a1_size = sizeof(read_a1);
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray_read);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(
ctx_, query, attributes[0], read_a1, &read_a1_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
CHECK(!memcmp(c_a1, read_a1, sizeof(c_a1)));
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, multi-fragment reads",
"[capi][dense][rest][dense-multi-fragment]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name =
TILEDB_URI_PREFIX + temp_dir + "dense_multi_fragment/";
create_temp_dir(temp_dir);
create_dense_array_1_attribute(array_name);
// Write slice [1,2], [3,4]
int write_a1[] = {1, 2, 3, 4, 5, 6, 7, 8};
uint64_t write_a1_size = sizeof(write_a1);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc =
tiledb_query_set_data_buffer(ctx_, query, "a1", write_a1, &write_a1_size);
CHECK(rc == TILEDB_OK);
uint64_t subarray_1[] = {1, 2, 1, 4};
rc = tiledb_query_set_subarray(ctx_, query, subarray_1);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
// Write slice [2,3], [2,3]
int write_a2[] = {101, 102, 103, 104};
uint64_t write_a2_size = sizeof(write_a2);
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc =
tiledb_query_set_data_buffer(ctx_, query, "a1", write_a2, &write_a2_size);
CHECK(rc == TILEDB_OK);
uint64_t subarray_2[] = {2, 3, 2, 3};
rc = tiledb_query_set_subarray(ctx_, query, subarray_2);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
// Read whole array
uint64_t subarray[] = {1, 4, 1, 4};
int c_a[] = {1,
2,
3,
4,
5,
101,
102,
8,
INT_MIN,
103,
104,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN,
INT_MIN};
int read_a[16];
uint64_t read_a_size = sizeof(read_a);
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_alloc(ctx_, array, TILEDB_READ, &query);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_data_buffer(ctx_, query, "a1", read_a, &read_a_size);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_submit(ctx_, query);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
CHECK(!memcmp(c_a, read_a, sizeof(c_a)));
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, check if open",
"[capi][dense][rest][dense-is-open]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = TILEDB_URI_PREFIX + temp_dir + "dense_is_open/";
create_temp_dir(temp_dir);
create_dense_array(array_name);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
int is_open;
rc = tiledb_array_is_open(ctx_, array, &is_open);
CHECK(rc == TILEDB_OK);
CHECK(is_open == 0);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_is_open(ctx_, array, &is_open);
CHECK(rc == TILEDB_OK);
CHECK(is_open == 1);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_is_open(ctx_, array, &is_open);
CHECK(rc == TILEDB_OK);
CHECK(is_open == 0);
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, get schema from opened array",
"[capi][dense][rest][dense-get-schema]") {
SupportedFsLocal local_fs;
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
std::string array_name = TILEDB_URI_PREFIX + temp_dir + "dense_get_schema/";
create_temp_dir(temp_dir);
create_dense_array(array_name);
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
// Get schema
tiledb_array_schema_t* schema;
rc = tiledb_array_get_schema(ctx_, array, &schema);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_schema_check(ctx_, schema);
CHECK(rc == TILEDB_OK);
// Clean up
rc = tiledb_array_close(ctx_, array);
CHECK(rc == TILEDB_OK);
tiledb_array_free(&array);
tiledb_array_schema_free(&schema);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, set subarray in sparse writes should error",
"[capi][dense][rest][dense-set-subarray-sparse]") {
SupportedFsLocal local_fs;
std::string array_name = TILEDB_URI_PREFIX + local_fs.file_prefix() +
local_fs.temp_dir() + "dense_set_subarray_sparse";
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
create_temp_dir(temp_dir);
create_dense_array(array_name);
// Open array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_WRITE);
CHECK(rc == TILEDB_OK);
// Create WRITE query
tiledb_query_t* query;
rc = tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query);
CHECK(rc == TILEDB_OK);
uint64_t subarray[] = {1, 1, 1, 1};
// Set some subarray BEFORE setting the layout to UNORDERED
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_OK);
// Set some subarray AFTER setting the layout to UNORDERED
rc = tiledb_query_set_layout(ctx_, query, TILEDB_UNORDERED);
CHECK(rc == TILEDB_OK);
rc = tiledb_query_set_subarray(ctx_, query, subarray);
CHECK(rc == TILEDB_ERR);
// Close array
CHECK(tiledb_array_close(ctx_, array) == TILEDB_OK);
// Clean up
tiledb_query_free(&query);
tiledb_array_free(&array);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, incomplete reads",
"[capi][dense][rest][incomplete]") {
// Disable incomplete resubmission
tiledb_ctx_free(&ctx_);
tiledb_error_t* error;
tiledb_config_t* config;
tiledb_config_alloc(&config, &error);
REQUIRE(
tiledb_config_set(config, "rest.resubmit_incomplete", "false", &error) ==
TILEDB_OK);
// Keep other REST server parameters the same
REQUIRE(
tiledb_config_set(
config, "rest.server_address", rest_server_uri_.c_str(), &error) ==
TILEDB_OK);
REQUIRE(
tiledb_config_set(
config, "rest.server_serialization_format", "CAPNP", &error) ==
TILEDB_OK);
REQUIRE(
tiledb_config_set(
config, "rest.username", rest_server_username_.c_str(), &error) ==
TILEDB_OK);
REQUIRE(
tiledb_config_set(
config, "rest.password", rest_server_password_.c_str(), &error) ==
TILEDB_OK);
REQUIRE(tiledb_ctx_alloc(config, &ctx_) == TILEDB_OK);
tiledb_config_free(&config);
// TODO: refactor for each supported FS.
std::string temp_dir = fs_vec_[0]->temp_dir();
create_temp_dir(temp_dir);
check_incomplete_reads(temp_dir);
remove_temp_dir(temp_dir);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, get nonempty domain",
"[capi][dense][rest]") {
// Parameters used in this test
int64_t domain_size_0 = 100;
int64_t domain_size_1 = 100;
int64_t tile_extent_0 = 10;
int64_t tile_extent_1 = 10;
int64_t domain_0_lo = 0;
int64_t domain_0_hi = domain_size_0 - 1;
int64_t domain_1_lo = 0;
int64_t domain_1_hi = domain_size_1 - 1;
uint64_t capacity = 1000;
tiledb_layout_t cell_order = TILEDB_ROW_MAJOR;
tiledb_layout_t tile_order = TILEDB_ROW_MAJOR;
SupportedFsLocal local_fs;
std::string array_name = TILEDB_URI_PREFIX + local_fs.file_prefix() +
local_fs.temp_dir() + "nonempty_domain_array";
create_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
// Create a dense integer array
create_dense_array_2D(
array_name,
tile_extent_0,
tile_extent_1,
domain_0_lo,
domain_0_hi,
domain_1_lo,
domain_1_hi,
capacity,
cell_order,
tile_order);
// Check nonempty domain before writing
tiledb_array_t* array;
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_READ) == TILEDB_OK);
int64_t nonempty_domain[4];
int32_t is_empty;
REQUIRE(
tiledb_array_get_non_empty_domain(
ctx_, array, &nonempty_domain, &is_empty) == TILEDB_OK);
REQUIRE(is_empty == 1);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
// Create a subarray of data
int64_t subarray[] = {10, 50, 20, 60};
int64_t subarray_length[2] = {subarray[1] - subarray[0] + 1,
subarray[3] - subarray[2] + 1};
int64_t cell_num_in_subarray = subarray_length[0] * subarray_length[1];
auto buffer = new int[cell_num_in_subarray];
int64_t index = 0;
uint64_t buffer_size = cell_num_in_subarray * sizeof(int);
uint64_t buffer_sizes[] = {buffer_size};
for (int64_t r = 0; r < subarray_length[0]; ++r)
for (int64_t c = 0; c < subarray_length[1]; ++c)
buffer[index++] = -(std::rand() % 999999);
// Write 2D subarray
write_dense_subarray_2D(
array_name,
subarray,
TILEDB_WRITE,
TILEDB_ROW_MAJOR,
buffer,
buffer_sizes);
// Clean up
delete[] buffer;
// Open array
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
// Check nonempty domain after writing
REQUIRE(
tiledb_array_get_non_empty_domain(
ctx_, array, &nonempty_domain, &is_empty) == TILEDB_OK);
REQUIRE(is_empty == 0);
for (unsigned i = 0; i < 4; i++)
REQUIRE(nonempty_domain[i] == subarray[i]);
// Clean up
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
remove_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, get max buffer sizes",
"[capi][dense][rest]") {
SupportedFsLocal local_fs;
std::string array_name = TILEDB_URI_PREFIX + local_fs.file_prefix() +
local_fs.temp_dir() + "max_buffer_sizes_array";
create_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
create_dense_array(array_name);
// Check max buffer sizes with empty array
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
// Write array
write_dense_array(array_name);
// Check max buffer sizes for whole domain
rc = tiledb_array_alloc(ctx_, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx_, array, TILEDB_READ);
CHECK(rc == TILEDB_OK);
// Clean up
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
remove_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, error without rest server configured",
"[capi][dense][rest][dense-set-subarray-sparse]") {
SupportedFsLocal local_fs;
std::string array_name = TILEDB_URI_PREFIX + local_fs.file_prefix() +
local_fs.temp_dir() + "dense_set_subarray_sparse";
std::string temp_dir = local_fs.file_prefix() + local_fs.temp_dir();
create_temp_dir(temp_dir);
create_dense_array(array_name);
// Create context without a REST config
tiledb_ctx_t* ctx;
REQUIRE(tiledb_ctx_alloc(nullptr, &ctx) == TILEDB_OK);
tiledb_array_t* array;
int rc = tiledb_array_alloc(ctx, array_name.c_str(), &array);
CHECK(rc == TILEDB_OK);
rc = tiledb_array_open(ctx, array, TILEDB_WRITE);
CHECK(rc == TILEDB_ERR);
// Clean up
CHECK(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
tiledb_ctx_free(&ctx);
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, datetimes",
"[capi][dense][rest][datetime]") {
SupportedFsLocal local_fs;
std::string array_name = TILEDB_URI_PREFIX + local_fs.file_prefix() +
local_fs.temp_dir() + "datetime_array";
create_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
int64_t dim_domain[] = {1, 10};
int64_t tile_extents[] = {2};
tiledb_dimension_t* d1;
REQUIRE(
tiledb_dimension_alloc(
ctx_,
"d1",
TILEDB_DATETIME_DAY,
&dim_domain[0],
&tile_extents[0],
&d1) == TILEDB_OK);
tiledb_domain_t* domain;
REQUIRE(tiledb_domain_alloc(ctx_, &domain) == TILEDB_OK);
REQUIRE(tiledb_domain_add_dimension(ctx_, domain, d1) == TILEDB_OK);
tiledb_attribute_t* a1;
REQUIRE(
tiledb_attribute_alloc(ctx_, "a1", TILEDB_DATETIME_HR, &a1) == TILEDB_OK);
tiledb_array_schema_t* array_schema;
REQUIRE(
tiledb_array_schema_alloc(ctx_, TILEDB_DENSE, &array_schema) ==
TILEDB_OK);
REQUIRE(
tiledb_array_schema_set_domain(ctx_, array_schema, domain) == TILEDB_OK);
REQUIRE(
tiledb_array_schema_add_attribute(ctx_, array_schema, a1) == TILEDB_OK);
REQUIRE(tiledb_array_schema_check(ctx_, array_schema) == TILEDB_OK);
// Create array
REQUIRE(
tiledb_array_create(ctx_, array_name.c_str(), array_schema) == TILEDB_OK);
to_deregister_.insert(array_name);
// Clean up
tiledb_attribute_free(&a1);
tiledb_dimension_free(&d1);
tiledb_domain_free(&domain);
tiledb_array_schema_free(&array_schema);
// Write some values
const char* attributes[] = {"a1"};
int64_t buffer_a1[] = {-3, -2, -1, 0, 1, 2, 3, 4, 5, 6};
void* buffers[] = {buffer_a1};
uint64_t buffer_sizes[] = {sizeof(buffer_a1)};
tiledb_array_t* array;
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_WRITE) == TILEDB_OK);
tiledb_query_t* query;
REQUIRE(tiledb_query_alloc(ctx_, array, TILEDB_WRITE, &query) == TILEDB_OK);
REQUIRE(tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR) == TILEDB_OK);
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]) ==
TILEDB_OK);
REQUIRE(tiledb_query_submit(ctx_, query) == TILEDB_OK);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
tiledb_query_free(&query);
// Read a section back
for (int i = 0; i < 10; i++)
buffer_a1[i] = 0;
int64_t subarray[] = {2, 5};
buffer_sizes[0] = sizeof(buffer_a1);
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_READ) == TILEDB_OK);
REQUIRE(tiledb_query_alloc(ctx_, array, TILEDB_READ, &query) == TILEDB_OK);
REQUIRE(tiledb_query_set_layout(ctx_, query, TILEDB_ROW_MAJOR) == TILEDB_OK);
REQUIRE(
tiledb_query_set_data_buffer(
ctx_, query, attributes[0], buffers[0], &buffer_sizes[0]) ==
TILEDB_OK);
REQUIRE(tiledb_query_set_subarray(ctx_, query, &subarray[0]) == TILEDB_OK);
REQUIRE(tiledb_query_submit(ctx_, query) == TILEDB_OK);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
REQUIRE(buffer_a1[0] == -2);
REQUIRE(buffer_a1[1] == -1);
REQUIRE(buffer_a1[2] == 0);
REQUIRE(buffer_a1[3] == 1);
tiledb_array_free(&array);
tiledb_query_free(&query);
remove_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
}
TEST_CASE_METHOD(
DenseArrayRESTFx,
"C API: REST Test dense array, array metadata",
"[capi][dense][rest][metadata]") {
SupportedFsLocal local_fs;
std::string array_name = TILEDB_URI_PREFIX + local_fs.file_prefix() +
local_fs.temp_dir() + "metadata_array";
create_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
int64_t dim_domain[] = {1, 10};
int64_t tile_extents[] = {2};
tiledb_dimension_t* d1;
REQUIRE(
tiledb_dimension_alloc(
ctx_, "d1", TILEDB_INT64, &dim_domain[0], &tile_extents[0], &d1) ==
TILEDB_OK);
tiledb_domain_t* domain;
REQUIRE(tiledb_domain_alloc(ctx_, &domain) == TILEDB_OK);
REQUIRE(tiledb_domain_add_dimension(ctx_, domain, d1) == TILEDB_OK);
tiledb_attribute_t* a1;
REQUIRE(tiledb_attribute_alloc(ctx_, "a1", TILEDB_INT64, &a1) == TILEDB_OK);
tiledb_array_schema_t* array_schema;
REQUIRE(
tiledb_array_schema_alloc(ctx_, TILEDB_DENSE, &array_schema) ==
TILEDB_OK);
REQUIRE(
tiledb_array_schema_set_domain(ctx_, array_schema, domain) == TILEDB_OK);
REQUIRE(
tiledb_array_schema_add_attribute(ctx_, array_schema, a1) == TILEDB_OK);
REQUIRE(tiledb_array_schema_check(ctx_, array_schema) == TILEDB_OK);
// Create array
REQUIRE(
tiledb_array_create(ctx_, array_name.c_str(), array_schema) == TILEDB_OK);
to_deregister_.insert(array_name);
// Clean up
tiledb_attribute_free(&a1);
tiledb_dimension_free(&d1);
tiledb_domain_free(&domain);
tiledb_array_schema_free(&array_schema);
// Write some metadata values
tiledb_array_t* array;
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_WRITE) == TILEDB_OK);
int32_t v = 5;
float f[] = {1.1f, 1.2f};
REQUIRE(
tiledb_array_put_metadata(ctx_, array, "aaa", TILEDB_INT32, 1, &v) ==
TILEDB_OK);
REQUIRE(
tiledb_array_put_metadata(ctx_, array, "bb", TILEDB_FLOAT32, 2, f) ==
TILEDB_OK);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
// Read metadata and check values.
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_READ) == TILEDB_OK);
uint64_t num_metadata = 0;
REQUIRE(
tiledb_array_get_metadata_num(ctx_, array, &num_metadata) == TILEDB_OK);
REQUIRE(num_metadata == 2);
tiledb_datatype_t datatype = TILEDB_UINT8;
uint32_t value_num = 0;
const void* value = nullptr;
REQUIRE(
tiledb_array_get_metadata(
ctx_, array, "aaa", &datatype, &value_num, &value) == TILEDB_OK);
REQUIRE(datatype == TILEDB_INT32);
REQUIRE(value_num == 1);
REQUIRE(*static_cast<const int32_t*>(value) == 5);
REQUIRE(
tiledb_array_get_metadata(
ctx_, array, "bb", &datatype, &value_num, &value) == TILEDB_OK);
REQUIRE(datatype == TILEDB_FLOAT32);
REQUIRE(value_num == 2);
REQUIRE(static_cast<const float*>(value)[0] == 1.1f);
REQUIRE(static_cast<const float*>(value)[1] == 1.2f);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
// Prevent array metadata filename/timestamp conflicts
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// Open for writing and delete a key.
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_WRITE) == TILEDB_OK);
REQUIRE(tiledb_array_delete_metadata(ctx_, array, "aaa") == TILEDB_OK);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
// Read metadata and check values again.
REQUIRE(tiledb_array_alloc(ctx_, array_name.c_str(), &array) == TILEDB_OK);
REQUIRE(tiledb_array_open(ctx_, array, TILEDB_READ) == TILEDB_OK);
REQUIRE(
tiledb_array_get_metadata_num(ctx_, array, &num_metadata) == TILEDB_OK);
REQUIRE(num_metadata == 1);
REQUIRE(
tiledb_array_get_metadata(
ctx_, array, "aaa", &datatype, &value_num, &value) == TILEDB_OK);
REQUIRE(value == nullptr);
REQUIRE(
tiledb_array_get_metadata(
ctx_, array, "bb", &datatype, &value_num, &value) == TILEDB_OK);
REQUIRE(datatype == TILEDB_FLOAT32);
REQUIRE(value_num == 2);
REQUIRE(static_cast<const float*>(value)[0] == 1.1f);
REQUIRE(static_cast<const float*>(value)[1] == 1.2f);
REQUIRE(tiledb_array_close(ctx_, array) == TILEDB_OK);
tiledb_array_free(&array);
remove_temp_dir(local_fs.file_prefix() + local_fs.temp_dir());
}
|
/*=============================================================================
Copyright (c) 2003 Joel de Guzman
Copyright (c) 2004 Peder Holt
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_JOINT_VIEW_HPP)
#define FUSION_SEQUENCE_JOINT_VIEW_HPP
#include <boost/spirit/fusion/detail/access.hpp>
#include <boost/spirit/fusion/sequence/begin.hpp>
#include <boost/spirit/fusion/sequence/end.hpp>
#include <boost/spirit/fusion/iterator/joint_view_iterator.hpp>
#include <boost/spirit/fusion/sequence/detail/joint_view_begin_end_traits.hpp>
#include <boost/spirit/fusion/sequence/detail/sequence_base.hpp>
#include <boost/spirit/fusion/sequence/as_fusion_sequence.hpp>
#include <boost/mpl/if.hpp>
namespace boost { namespace fusion
{
struct joint_view_tag;
template<typename View1, typename View2, bool copy1, bool copy2>
struct joint_view;
template <typename View1, typename View2, bool copy1 = false, bool copy2 = false>
struct joint_view : sequence_base<joint_view<View1, View2, copy1, copy2> >
{
typedef as_fusion_sequence<View1> view1_converter;
typedef typename view1_converter::type view1;
typedef as_fusion_sequence<View2> view2_converter;
typedef typename view2_converter::type view2;
typedef joint_view_tag tag;
typedef typename meta::begin<view1>::type first_type;
typedef typename meta::end<view1>::type last_type;
typedef typename meta::begin<view2>::type concat_type;
typedef typename meta::end<view2>::type concat_last_type;
joint_view(View1& view1, View2& view2);
first_type first() const { return boost::fusion::begin(view1_); }
concat_type concat() const { return boost::fusion::begin(view2_); }
concat_last_type concat_last() const { return boost::fusion::end(view2_); }
private:
typename boost::mpl::if_c<copy1, View1, View1&>::type view1_;
typename boost::mpl::if_c<copy2, View2, View2&>::type view2_;
};
template <typename View1, typename View2, bool copy1, bool copy2>
joint_view<View1,View2,copy1,copy2>::joint_view(View1& view1, View2& view2)
: view1_(view1), view2_(view2)
{}
}}
#endif
|
// $Id: test.cpp 80826 2008-03-04 14:51:23Z wotte $
// A simple test for performance of the ACEXML_escape_string() function
#include "ACEXML/common/XML_Util.h"
#include "ace/OS_main.h"
#include "ace/Time_Value.h"
#include "ace/OS_NS_sys_time.h"
#include "ace/Log_Msg.h"
const int MAX_ITERATIONS = 100 * 1000;
const int NUM_TEST_STRS = 6;
static bool is_escaped(const ACEXML_String& s)
{
if (s[0] != ACE_TEXT('&'))
return false;
if (s[s.length() - 1] != ACE_TEXT(';'))
return false;
return true;
}
static int run_tests(ACEXML_String test_strings[NUM_TEST_STRS], int iterations)
{
// Test 1 - Escape the strings using a new temporary string each iteration.
ACE_Time_Value start = ACE_OS::gettimeofday();
int i = 0;
for (i = 0; i < iterations; ++i)
{
ACEXML_String tmp = ACEXML_escape_string(test_strings[i % NUM_TEST_STRS]);
if (! is_escaped(tmp))
{
ACE_ERROR((LM_ERROR, "Error: Failed to escape string\n"));
return 1;
}
}
ACE_DEBUG((LM_DEBUG, "Test1 took %dms\n", (ACE_OS::gettimeofday() - start).msec()));
// Test 2 - Escape the strings using a shared temporary string. This shouldn't
// be any faster than Test 1 as long as the compiler has return value optimization.
ACEXML_String tmp;
start = ACE_OS::gettimeofday();
for (i = 0; i < iterations; ++i)
{
tmp = ACEXML_escape_string(test_strings[i % NUM_TEST_STRS]);
if (! is_escaped(tmp))
{
ACE_ERROR((LM_ERROR, "Error: Failed to escape string\n"));
return 1;
}
}
ACE_DEBUG((LM_DEBUG, "Test2 took %dms\n", (ACE_OS::gettimeofday() - start).msec()));
// Test 3 - Escape the strings using a shared temporary string. This time, we use
// the alternate form of ACEXML_escape_string() so that our temporary buffer is reused.
tmp.clear(1);
start = ACE_OS::gettimeofday();
for (i = 0; i < iterations; ++i)
{
ACEXML_escape_string(test_strings[i % NUM_TEST_STRS], tmp);
if (! is_escaped(tmp))
{
ACE_ERROR((LM_ERROR, "Error: Failed to escape string\n"));
return 1;
}
}
ACE_DEBUG((LM_DEBUG, "Test3 took %dms\n", (ACE_OS::gettimeofday() - start).msec()));
// Test 4 - Same as Test 3, except that the tmp buffer shouldn't have to resize.
start = ACE_OS::gettimeofday();
for (i = 0; i < iterations; ++i)
{
ACEXML_escape_string(test_strings[i % NUM_TEST_STRS], tmp);
if (! is_escaped(tmp))
{
ACE_ERROR((LM_ERROR, "Error: Failed to escape string\n"));
return 1;
}
}
ACE_DEBUG((LM_DEBUG, "Test4 took %dms\n", (ACE_OS::gettimeofday() - start).msec()));
return 0;
}
int ACE_TMAIN (int, ACE_TCHAR *[])
{
ACEXML_String test_strings[NUM_TEST_STRS] = {
ACE_TEXT("\"xxxxx\"xxxxxxxx xx\"xxxxxx xxxxxx\"xxxxxxxxxx xxxxxxxx\"xxxxxx\""),
ACE_TEXT("'xxxxx\'xxxxxxxx' xxxxxxxx xx'xxxxxxxx'xxxxxx xxxxxxx'xxxxxxx'"),
ACE_TEXT("&xxxx&xxxxxxxxx &xxxxxxxx xxxxx&xxxxxxxxxxx xxxx&xxxxxxxxxx&"),
ACE_TEXT(">xx>xxxxxxxxxxx >xxxxxxxx xxxxx>xxxxxxxxxxx xxxxx>xxxxxxxxx>"),
ACE_TEXT("<xxxxx<xxxxxxxx xxxxxxxx <xxxxxxxxxxxxxxx<x xxxxxxxxxxxxxx<"),
ACE_TEXT("&xxxx\"xxxxxxx&xx xxx'xxxxx xx<xxxxxxx>xxxxxxx xx\"xxxxxxxxxxxx>"),
};
if (run_tests(test_strings, MAX_ITERATIONS) != 0)
return 1;
ACE_DEBUG((LM_DEBUG, "Rerun tests with larger strings\n"));
for (int i = 0; i < NUM_TEST_STRS; ++i)
{
for (int j = 0; j < 5; ++j)
{
test_strings[i] += test_strings[i];
}
}
if (run_tests(test_strings, MAX_ITERATIONS / 10) != 0)
return 1;
return 0;
}
|
/*
Original code: Copyright (C) 2001-2003 Andrea Mazzoleni
openMSX adaptation by Maarten ter Huurne
This file is based on code from the Scale2x project.
This modified version is licensed under GPL; the original code is dual-licensed
under GPL and under a custom license.
Visit the Scale2x site for info:
http://scale2x.sourceforge.net/
*/
#include "Scale3xScaler.hh"
#include "FrameSource.hh"
#include "ScalerOutput.hh"
#include "vla.hh"
#include "build-info.hh"
#include <cstdint>
namespace openmsx {
template <class Pixel>
Scale3xScaler<Pixel>::Scale3xScaler(const PixelOperations<Pixel>& pixelOps_)
: Scaler3<Pixel>(pixelOps_)
{
}
template <class Pixel>
void Scale3xScaler<Pixel>::scaleLine1on3Half(
Pixel* __restrict dst, const Pixel* __restrict src0,
const Pixel* __restrict src1, const Pixel* __restrict src2,
unsigned srcWidth) __restrict
{
/* A B C
* D E F
* G H I
*
* E0 = D == B && B != F && D != H ? D : E;
* E1 = (D == B && B != F && D != H && E != C) ||
* (B == F && B != D && F != H && E != A) ? B : E;
* E2 = B == F && B != D && F != H ? F : E;
*/
// First pixel.
Pixel top = src0[0];
Pixel mid = src1[0];
Pixel right = src1[1];
Pixel bot = src2[0];
dst[0] = mid;
dst[1] = (mid != right) && (top != bot) &&
(((top == mid ) && (mid != src0[1])) ||
((top == right) && (mid != top)))
? top : mid;
dst[2] = (mid != right) && (top != bot) && (top == right)
? top : mid;
// Central pixels.
for (unsigned x = 1; x < srcWidth - 1; ++x) {
Pixel left = mid;
mid = right;
right = src1[x + 1];
top = src0[x];
bot = src2[x];
dst[3 * x + 0] = (left != right) && (top != bot) &&
(top == left)
? top : mid;
dst[3 * x + 1] = (left != right) && (top != bot) &&
(((top == left ) && (mid != src0[x + 1])) ||
((top == right) && (mid != src0[x - 1])))
? top : mid;
dst[3 * x + 2] = (left != right) && (top != bot) &&
(top == right)
? top : mid;
}
// Last pixel.
Pixel left = mid;
mid = right;
top = src0[srcWidth - 1];
bot = src2[srcWidth - 1];
dst[3 * srcWidth - 3] = (left != mid) && (top != bot) && (top ==left)
? top : mid;
dst[3 * srcWidth - 2] = (left != mid) && (top != bot) &&
(((top == left) && (mid != top)) ||
((top == mid ) && (mid != src0[srcWidth - 2])))
? top : mid;
dst[3 * srcWidth - 1] = mid;
}
template <class Pixel>
void Scale3xScaler<Pixel>::scaleLine1on3Mid(
Pixel* __restrict dst, const Pixel* __restrict src0,
const Pixel* __restrict src1, const Pixel* __restrict src2,
unsigned srcWidth) __restrict
{
/*
* A B C
* D E F
* G H I
*
* E3 = (D == B && B != F && D != H && E != G) ||
* (D == H && D != B && H != F && E != A) ? D : E;
* E4 = E
* E5 = (B == F && B != D && F != H && E != I) ||
* (H == F && D != H && B != F && E != C) ? F : E;
*/
// First pixel.
Pixel mid = src1[0];
Pixel right = src1[1];
Pixel top = src0[0];
Pixel bot = src2[0];
dst[0] = mid;
dst[1] = mid;
dst[2] = (mid != right) && (top != bot) &&
(((right == top) && (mid != src2[1])) ||
((right == bot) && (mid != src0[1])))
? right : mid;
// Central pixels.
for (unsigned x = 1; x < srcWidth - 1; ++x) {
Pixel left = mid;
mid = right;
right = src1[x + 1];
top = src0[x];
bot = src2[x];
dst[3 * x + 0] = (left != right) && (top != bot) &&
(((left == top) && (mid != src2[x - 1])) ||
((left == bot) && (mid != src0[x - 1])))
? left : mid;
dst[3 * x + 1] = mid;
dst[3 * x + 2] = (left != right) && (top != bot) &&
(((right == top) && (mid != src2[x + 1])) ||
((right == bot) && (mid != src0[x + 1])))
? right : mid;
}
// Last pixel.
Pixel left = mid;
mid = right;
top = src0[srcWidth - 1];
bot = src2[srcWidth - 1];
dst[3 * srcWidth - 3] = (left != mid) && (top != bot) &&
(((left == top) && (mid != src2[srcWidth - 2])) ||
((left == bot) && (mid != src0[srcWidth - 2])))
? left : mid;
dst[3 * srcWidth - 2] = mid;
dst[3 * srcWidth - 1] = mid;
}
template <class Pixel>
void Scale3xScaler<Pixel>::scale1x1to3x3(FrameSource& src,
unsigned srcStartY, unsigned /*srcEndY*/, unsigned srcWidth,
ScalerOutput<Pixel>& dst, unsigned dstStartY, unsigned dstEndY)
{
VLA_SSE_ALIGNED(Pixel, buf0_, srcWidth); auto* buf0 = buf0_;
VLA_SSE_ALIGNED(Pixel, buf1_, srcWidth); auto* buf1 = buf1_;
VLA_SSE_ALIGNED(Pixel, buf2_, srcWidth); auto* buf2 = buf2_;
int srcY = srcStartY;
auto* srcPrev = src.getLinePtr(srcY - 1, srcWidth, buf0);
auto* srcCurr = src.getLinePtr(srcY + 0, srcWidth, buf1);
for (unsigned dstY = dstStartY; dstY < dstEndY; srcY += 1, dstY += 3) {
auto* srcNext = src.getLinePtr(srcY + 1, srcWidth, buf2);
auto* dstUpper = dst.acquireLine(dstY + 0);
scaleLine1on3Half(dstUpper, srcPrev, srcCurr, srcNext, srcWidth);
dst.releaseLine(dstY + 0, dstUpper);
auto* dstMiddle = dst.acquireLine(dstY + 1);
scaleLine1on3Mid(dstMiddle, srcPrev, srcCurr, srcNext, srcWidth);
dst.releaseLine(dstY + 1, dstMiddle);
auto* dstLower = dst.acquireLine(dstY + 2);
scaleLine1on3Half(dstLower, srcNext, srcCurr, srcPrev, srcWidth);
dst.releaseLine(dstY + 2, dstLower);
srcPrev = srcCurr;
srcCurr = srcNext;
std::swap(buf0, buf1);
std::swap(buf1, buf2);
}
}
// Force template instantiation.
#if HAVE_16BPP
template class Scale3xScaler<uint16_t>;
#endif
#if HAVE_32BPP
template class Scale3xScaler<uint32_t>;
#endif
} // namespace openmsx
|
// Copyright (c) 2020-2021 The Wflscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <pow.h>
#include <primitives/block.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
void initialize_pow()
{
SelectParams(CBaseChainParams::MAIN);
}
FUZZ_TARGET_INIT(pow, initialize_pow)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const Consensus::Params& consensus_params = Params().GetConsensus();
std::vector<CBlockIndex> blocks;
const uint32_t fixed_time = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
const uint32_t fixed_bits = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
while (fuzzed_data_provider.remaining_bytes() > 0) {
const std::optional<CBlockHeader> block_header = ConsumeDeserializable<CBlockHeader>(fuzzed_data_provider);
if (!block_header) {
continue;
}
CBlockIndex current_block{*block_header};
{
CBlockIndex* previous_block = blocks.empty() ? nullptr : &PickValue(fuzzed_data_provider, blocks);
const int current_height = (previous_block != nullptr && previous_block->nHeight != std::numeric_limits<int>::max()) ? previous_block->nHeight + 1 : 0;
if (fuzzed_data_provider.ConsumeBool()) {
current_block.pprev = previous_block;
}
if (fuzzed_data_provider.ConsumeBool()) {
current_block.nHeight = current_height;
}
if (fuzzed_data_provider.ConsumeBool()) {
const uint32_t seconds = current_height * consensus_params.nPowTargetSpacing;
if (!AdditionOverflow(fixed_time, seconds)) {
current_block.nTime = fixed_time + seconds;
}
}
if (fuzzed_data_provider.ConsumeBool()) {
current_block.nBits = fixed_bits;
}
if (fuzzed_data_provider.ConsumeBool()) {
current_block.nChainWork = previous_block != nullptr ? previous_block->nChainWork + GetBlockProof(*previous_block) : arith_uint256{0};
} else {
current_block.nChainWork = ConsumeArithUInt256(fuzzed_data_provider);
}
blocks.push_back(current_block);
}
{
(void)GetBlockProof(current_block);
(void)CalculateNextWorkRequired(¤t_block, fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(0, std::numeric_limits<int64_t>::max()), consensus_params);
if (current_block.nHeight != std::numeric_limits<int>::max() && current_block.nHeight - (consensus_params.DifficultyAdjustmentInterval() - 1) >= 0) {
(void)GetNextWorkRequired(¤t_block, &(*block_header), consensus_params);
}
}
{
const CBlockIndex* to = &PickValue(fuzzed_data_provider, blocks);
const CBlockIndex* from = &PickValue(fuzzed_data_provider, blocks);
const CBlockIndex* tip = &PickValue(fuzzed_data_provider, blocks);
try {
(void)GetBlockProofEquivalentTime(*to, *from, *tip, consensus_params);
} catch (const uint_error&) {
}
}
{
const std::optional<uint256> hash = ConsumeDeserializable<uint256>(fuzzed_data_provider);
if (hash) {
(void)CheckProofOfWork(*hash, fuzzed_data_provider.ConsumeIntegral<unsigned int>(), consensus_params);
}
}
}
}
|
// Copyright 2018 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 "chrome/browser/vr/ui_support.h"
namespace vr {
UScriptCode UScriptGetScript(UChar32 codepoint, UErrorCode* err) {
return uscript_getScript(codepoint, err);
}
base::string16 FormatUrlForVr(const GURL& gurl, url::Parsed* new_parsed) {
return url_formatter::FormatUrl(
gurl,
url_formatter::kFormatUrlOmitDefaults |
url_formatter::kFormatUrlOmitHTTPS |
url_formatter::kFormatUrlOmitTrivialSubdomains,
net::UnescapeRule::NORMAL, new_parsed, nullptr, nullptr);
}
} // namespace vr
|
/*
functions that can not be optimazed by vertorization in python.
1. rasterization.(need process each triangle)
2. normal of each vertex.(use one-ring, need process each vertex)
3. write obj(seems that it can be verctorized? anyway, writing it in c++ is simple, so also add function here. --> however, why writting in c++ is still slow?)
Author: Yao Feng
Mail: yaofeng1995@gmail.com
*/
#include "mesh_core.h"
/* Judge whether the point is in the triangle
Method:
http://blackpawn.com/texts/pointinpoly/
Args:
point: [x, y]
tri_points: three vertices(2d points) of a triangle. 2 coords x 3 vertices
Returns:
bool: true for in triangle
*/
bool isPointInTri(point p, point p0, point p1, point p2)
{
// vectors
point v0, v1, v2;
v0 = p2 - p0;
v1 = p1 - p0;
v2 = p - p0;
// dot products
float dot00 = v0.dot(v0); //v0.x * v0.x + v0.y * v0.y //np.dot(v0.T, v0)
float dot01 = v0.dot(v1); //v0.x * v1.x + v0.y * v1.y //np.dot(v0.T, v1)
float dot02 = v0.dot(v2); //v0.x * v2.x + v0.y * v2.y //np.dot(v0.T, v2)
float dot11 = v1.dot(v1); //v1.x * v1.x + v1.y * v1.y //np.dot(v1.T, v1)
float dot12 = v1.dot(v2); //v1.x * v2.x + v1.y * v2.y//np.dot(v1.T, v2)
// barycentric coordinates
float inverDeno;
if(dot00*dot11 - dot01*dot01 == 0)
inverDeno = 0;
else
inverDeno = 1/(dot00*dot11 - dot01*dot01);
float u = (dot11*dot02 - dot01*dot12)*inverDeno;
float v = (dot00*dot12 - dot01*dot02)*inverDeno;
// check if point in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
}
void get_point_weight(float* weight, point p, point p0, point p1, point p2)
{
// vectors
point v0, v1, v2;
v0 = p2 - p0;
v1 = p1 - p0;
v2 = p - p0;
// dot products
float dot00 = v0.dot(v0); //v0.x * v0.x + v0.y * v0.y //np.dot(v0.T, v0)
float dot01 = v0.dot(v1); //v0.x * v1.x + v0.y * v1.y //np.dot(v0.T, v1)
float dot02 = v0.dot(v2); //v0.x * v2.x + v0.y * v2.y //np.dot(v0.T, v2)
float dot11 = v1.dot(v1); //v1.x * v1.x + v1.y * v1.y //np.dot(v1.T, v1)
float dot12 = v1.dot(v2); //v1.x * v2.x + v1.y * v2.y//np.dot(v1.T, v2)
// barycentric coordinates
float inverDeno;
if(dot00*dot11 - dot01*dot01 == 0)
inverDeno = 0;
else
inverDeno = 1/(dot00*dot11 - dot01*dot01);
float u = (dot11*dot02 - dot01*dot12)*inverDeno;
float v = (dot00*dot12 - dot01*dot02)*inverDeno;
// weight
weight[0] = 1 - u - v;
weight[1] = v;
weight[2] = u;
}
void _get_normal_core(
float* normal, float* tri_normal, int* triangles,
int ntri)
{
int i, j;
int tri_p0_ind, tri_p1_ind, tri_p2_ind;
for(i = 0; i < ntri; i++)
{
tri_p0_ind = triangles[3*i];
tri_p1_ind = triangles[3*i + 1];
tri_p2_ind = triangles[3*i + 2];
for(j = 0; j < 3; j++)
{
normal[3*tri_p0_ind + j] = normal[3*tri_p0_ind + j] + tri_normal[3*i + j];
normal[3*tri_p1_ind + j] = normal[3*tri_p1_ind + j] + tri_normal[3*i + j];
normal[3*tri_p2_ind + j] = normal[3*tri_p2_ind + j] + tri_normal[3*i + j];
}
}
}
void _rasterize_triangles_core(
float* vertices, int* triangles,
float* depth_buffer, int* triangle_buffer, float* barycentric_weight,
int nver, int ntri,
int h, int w)
{
int i;
int x, y, k;
int tri_p0_ind, tri_p1_ind, tri_p2_ind;
point p0, p1, p2, p;
int x_min, x_max, y_min, y_max;
float p_depth, p0_depth, p1_depth, p2_depth;
float weight[3];
for(i = 0; i < ntri; i++)
{
tri_p0_ind = triangles[3*i];
tri_p1_ind = triangles[3*i + 1];
tri_p2_ind = triangles[3*i + 2];
p0.x = vertices[3*tri_p0_ind]; p0.y = vertices[3*tri_p0_ind + 1]; p0_depth = vertices[3*tri_p0_ind + 2];
p1.x = vertices[3*tri_p1_ind]; p1.y = vertices[3*tri_p1_ind + 1]; p1_depth = vertices[3*tri_p1_ind + 2];
p2.x = vertices[3*tri_p2_ind]; p2.y = vertices[3*tri_p2_ind + 1]; p2_depth = vertices[3*tri_p2_ind + 2];
x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0);
x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1);
y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0);
y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1);
if(x_max < x_min || y_max < y_min)
{
continue;
}
for(y = y_min; y <= y_max; y++) //h
{
for(x = x_min; x <= x_max; x++) //w
{
p.x = x; p.y = y;
if(p.x < 2 || p.x > w - 3 || p.y < 2 || p.y > h - 3 || isPointInTri(p, p0, p1, p2))
{
get_point_weight(weight, p, p0, p1, p2);
p_depth = weight[0]*p0_depth + weight[1]*p1_depth + weight[2]*p2_depth;
if((p_depth > depth_buffer[y*w + x]))
{
depth_buffer[y*w + x] = p_depth;
triangle_buffer[y*w + x] = i;
for(k = 0; k < 3; k++)
{
barycentric_weight[y*w*3 + x*3 + k] = weight[k];
}
}
}
}
}
}
}
void _render_colors_core(
float* image, float* vertices, int* triangles,
float* colors,
float* depth_buffer,
int nver, int ntri,
int h, int w, int c)
{
int i;
int x, y, k;
int tri_p0_ind, tri_p1_ind, tri_p2_ind;
point p0, p1, p2, p;
int x_min, x_max, y_min, y_max;
float p_depth, p0_depth, p1_depth, p2_depth;
float p_color, p0_color, p1_color, p2_color;
float weight[3];
for(i = 0; i < ntri; i++)
{
tri_p0_ind = triangles[3*i];
tri_p1_ind = triangles[3*i + 1];
tri_p2_ind = triangles[3*i + 2];
p0.x = vertices[3*tri_p0_ind]; p0.y = vertices[3*tri_p0_ind + 1]; p0_depth = vertices[3*tri_p0_ind + 2];
p1.x = vertices[3*tri_p1_ind]; p1.y = vertices[3*tri_p1_ind + 1]; p1_depth = vertices[3*tri_p1_ind + 2];
p2.x = vertices[3*tri_p2_ind]; p2.y = vertices[3*tri_p2_ind + 1]; p2_depth = vertices[3*tri_p2_ind + 2];
x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0);
x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1);
y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0);
y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1);
if(x_max < x_min || y_max < y_min)
{
continue;
}
for(y = y_min; y <= y_max; y++) //h
{
for(x = x_min; x <= x_max; x++) //w
{
p.x = x; p.y = y;
if(p.x < 2 || p.x > w - 3 || p.y < 2 || p.y > h - 3 || isPointInTri(p, p0, p1, p2))
{
get_point_weight(weight, p, p0, p1, p2);
p_depth = weight[0]*p0_depth + weight[1]*p1_depth + weight[2]*p2_depth;
if((p_depth > depth_buffer[y*w + x]))
{
for(k = 0; k < c; k++) // c
{
p0_color = colors[c*tri_p0_ind + k];
p1_color = colors[c*tri_p1_ind + k];
p2_color = colors[c*tri_p2_ind + k];
p_color = weight[0]*p0_color + weight[1]*p1_color + weight[2]*p2_color;
image[y*w*c + x*c + k] = p_color;
}
depth_buffer[y*w + x] = p_depth;
}
}
}
}
}
}
void _render_texture_core(
float* image, float* vertices, int* triangles,
float* texture, float* tex_coords, int* tex_triangles,
float* depth_buffer,
int nver, int tex_nver, int ntri,
int h, int w, int c,
int tex_h, int tex_w, int tex_c,
int mapping_type)
{
int i;
int x, y, k;
int tri_p0_ind, tri_p1_ind, tri_p2_ind;
int tex_tri_p0_ind, tex_tri_p1_ind, tex_tri_p2_ind;
point p0, p1, p2, p;
point tex_p0, tex_p1, tex_p2, tex_p;
int x_min, x_max, y_min, y_max;
float weight[3];
float p_depth, p0_depth, p1_depth, p2_depth;
float xd, yd;
float ul, ur, dl, dr;
for(i = 0; i < ntri; i++)
{
// mesh
tri_p0_ind = triangles[3*i];
tri_p1_ind = triangles[3*i + 1];
tri_p2_ind = triangles[3*i + 2];
p0.x = vertices[3*tri_p0_ind]; p0.y = vertices[3*tri_p0_ind + 1]; p0_depth = vertices[3*tri_p0_ind + 2];
p1.x = vertices[3*tri_p1_ind]; p1.y = vertices[3*tri_p1_ind + 1]; p1_depth = vertices[3*tri_p1_ind + 2];
p2.x = vertices[3*tri_p2_ind]; p2.y = vertices[3*tri_p2_ind + 1]; p2_depth = vertices[3*tri_p2_ind + 2];
// texture
tex_tri_p0_ind = tex_triangles[3*i];
tex_tri_p1_ind = tex_triangles[3*i + 1];
tex_tri_p2_ind = tex_triangles[3*i + 2];
tex_p0.x = tex_coords[3*tex_tri_p0_ind]; tex_p0.y = tex_coords[3*tri_p0_ind + 1];
tex_p1.x = tex_coords[3*tex_tri_p1_ind]; tex_p1.y = tex_coords[3*tri_p1_ind + 1];
tex_p2.x = tex_coords[3*tex_tri_p2_ind]; tex_p2.y = tex_coords[3*tri_p2_ind + 1];
x_min = max((int)ceil(min(p0.x, min(p1.x, p2.x))), 0);
x_max = min((int)floor(max(p0.x, max(p1.x, p2.x))), w - 1);
y_min = max((int)ceil(min(p0.y, min(p1.y, p2.y))), 0);
y_max = min((int)floor(max(p0.y, max(p1.y, p2.y))), h - 1);
if(x_max < x_min || y_max < y_min)
{
continue;
}
for(y = y_min; y <= y_max; y++) //h
{
for(x = x_min; x <= x_max; x++) //w
{
p.x = x; p.y = y;
if(p.x < 2 || p.x > w - 3 || p.y < 2 || p.y > h - 3 || isPointInTri(p, p0, p1, p2))
{
get_point_weight(weight, p, p0, p1, p2);
p_depth = weight[0]*p0_depth + weight[1]*p1_depth + weight[2]*p2_depth;
if((p_depth > depth_buffer[y*w + x]))
{
// -- color from texture
// cal weight in mesh tri
get_point_weight(weight, p, p0, p1, p2);
// cal coord in texture
tex_p = tex_p0*weight[0] + tex_p1*weight[1] + tex_p2*weight[2];
tex_p.x = max(min(tex_p.x, float(tex_w - 1)), float(0));
tex_p.y = max(min(tex_p.y, float(tex_h - 1)), float(0));
yd = tex_p.y - floor(tex_p.y);
xd = tex_p.x - floor(tex_p.x);
for(k = 0; k < c; k++)
{
if(mapping_type==0)// nearest
{
image[y*w*c + x*c + k] = texture[int(round(tex_p.y))*tex_w*tex_c + int(round(tex_p.x))*tex_c + k];
}
else//bilinear interp
{
ul = texture[(int)floor(tex_p.y)*tex_w*tex_c + (int)floor(tex_p.x)*tex_c + k];
ur = texture[(int)floor(tex_p.y)*tex_w*tex_c + (int)ceil(tex_p.x)*tex_c + k];
dl = texture[(int)ceil(tex_p.y)*tex_w*tex_c + (int)floor(tex_p.x)*tex_c + k];
dr = texture[(int)ceil(tex_p.y)*tex_w*tex_c + (int)ceil(tex_p.x)*tex_c + k];
image[y*w*c + x*c + k] = ul*(1-xd)*(1-yd) + ur*xd*(1-yd) + dl*(1-xd)*yd + dr*xd*yd;
}
}
depth_buffer[y*w + x] = p_depth;
}
}
}
}
}
}
// ------------------------------------------------- write
// obj write
// Ref: https://github.com/patrikhuber/eos/blob/master/include/eos/core/Mesh.hpp
void _write_obj_with_colors_texture(string filename, string mtl_name,
float* vertices, int* triangles, float* colors, float* uv_coords,
int nver, int ntri, int ntexver)
{
int i;
//ofstream obj_file(filename);
ofstream obj_file(filename.c_str());
// first line of the obj file: the mtl name
obj_file << "mtllib " << mtl_name << endl;
// write vertices
for (i = 0; i < nver; ++i)
{
obj_file << "v " << vertices[3*i] << " " << vertices[3*i + 1] << " " << vertices[3*i + 2] << colors[3*i] << " " << colors[3*i + 1] << " " << colors[3*i + 2] << endl;
}
// write uv coordinates
for (i = 0; i < ntexver; ++i)
{
//obj_file << "vt " << uv_coords[2*i] << " " << (1 - uv_coords[2*i + 1]) << endl;
obj_file << "vt " << uv_coords[2*i] << " " << uv_coords[2*i + 1] << endl;
}
obj_file << "usemtl FaceTexture" << endl;
// write triangles
for (i = 0; i < ntri; ++i)
{
// obj_file << "f " << triangles[3*i] << "/" << triangles[3*i] << " " << triangles[3*i + 1] << "/" << triangles[3*i + 1] << " " << triangles[3*i + 2] << "/" << triangles[3*i + 2] << endl;
obj_file << "f " << triangles[3*i + 2] << "/" << triangles[3*i + 2] << " " << triangles[3*i + 1] << "/" << triangles[3*i + 1] << " " << triangles[3*i] << "/" << triangles[3*i] << endl;
}
}
|
/*
SYCL Academy (c)
SYCL Academy is licensed under a Creative Commons
Attribution-ShareAlike 4.0 International License.
You should have received a copy of the license along with this
work. If not, see <http://creativecommons.org/licenses/by-sa/4.0/>.
*/
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#if __has_include(<SYCL/sycl.hpp>)
#include <SYCL/sycl.hpp>
#else
#include <CL/sycl.hpp>
#endif
class usm_selector : public sycl::device_selector {
public:
int operator()(const sycl::device& dev) const {
if (dev.has(sycl::aspect::usm_device_allocations)) {
return 1;
}
return -1;
}
};
TEST_CASE("usm_selector", "usm_selector_solution") {
try {
auto asyncHandler = [&](sycl::exception_list exceptionList) {
for (auto& e : exceptionList) {
std::rethrow_exception(e);
}
};
auto usmQueue = sycl::queue{usm_selector{}, asyncHandler};
usmQueue.throw_asynchronous();
} catch (const sycl::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
REQUIRE(true);
}
|
#include <kungfu/tensorflow/ops.h>
namespace tensorflow
{
REGISTER_OP("KungfuResizeCluster")
.Input("checkpoint: string")
.Input("new_cluster_size: int32")
// indicats if self is still in the new cluster
.Output("keep: bool");
class KungfuResizeCluster : public AsyncOpKernel
{
using AsyncOpKernel::AsyncOpKernel;
public:
void ComputeAsync(OpKernelContext *context, DoneCallback done) override
{
const std::string &chpt = context->input(0).scalar<std::string>()();
const int32_t new_size = context->input(1).scalar<int32_t>()();
Tensor *keep = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, MakeTensorShape(), &keep));
_kungfu_world->ResizeCluster(chpt.c_str(), new_size,
keep->scalar<bool>().data());
done();
}
};
REGISTER_KERNEL_BUILDER(Name("KungfuResizeCluster").Device(DEVICE_CPU),
KungfuResizeCluster);
} // namespace tensorflow
|
/* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "common/base/Base.h"
#include "kvstore/raftex/RaftexService.h"
#include <folly/ScopeGuard.h>
#include "kvstore/raftex/RaftPart.h"
namespace nebula {
namespace raftex {
/*******************************************************
*
* Implementation of RaftexService
*
******************************************************/
std::shared_ptr<RaftexService> RaftexService::createService(
std::shared_ptr<folly::IOThreadPoolExecutor> pool,
std::shared_ptr<folly::Executor> workers,
uint16_t port) {
auto svc = std::shared_ptr<RaftexService>(new RaftexService());
CHECK(svc != nullptr) << "Failed to create a raft service";
svc->server_ = std::make_unique<apache::thrift::ThriftServer>();
CHECK(svc->server_ != nullptr) << "Failed to create a thrift server";
svc->server_->setInterface(svc);
svc->initThriftServer(pool, workers, port);
return svc;
}
RaftexService::~RaftexService() {
}
bool RaftexService::start() {
serverThread_.reset(new std::thread([&] {serve();}));
waitUntilReady();
// start failed, reclaim resource
if (status_.load() != STATUS_RUNNING) {
waitUntilStop();
return false;
}
return true;
}
void RaftexService::waitUntilReady() {
while (status_.load() == STATUS_NOT_RUNNING) {
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
}
void RaftexService::initThriftServer(std::shared_ptr<folly::IOThreadPoolExecutor> pool,
std::shared_ptr<folly::Executor> workers,
uint16_t port) {
LOG(INFO) << "Init thrift server for raft service.";
server_->setPort(port);
server_->setIdleTimeout(std::chrono::seconds(0));
server_->setReusePort(true);
if (pool != nullptr) {
server_->setIOThreadPool(pool);
}
if (workers != nullptr) {
server_->setThreadManager(
std::dynamic_pointer_cast<
apache::thrift::concurrency::ThreadManager>(workers));
}
server_->setStopWorkersOnStopListening(false);
}
bool RaftexService::setup() {
try {
server_->setup();
serverPort_ = server_->getAddress().getPort();
LOG(INFO) << "Starting the Raftex Service on " << serverPort_;
}
catch (const std::exception &e) {
LOG(ERROR) << "Setup the Raftex Service failed, error: " << e.what();
return false;
}
return true;
}
void RaftexService::serve() {
LOG(INFO) << "Starting the Raftex Service";
if (!setup()) {
status_.store(STATUS_SETUP_FAILED);
return;
}
SCOPE_EXIT {
server_->cleanUp();
};
status_.store(STATUS_RUNNING);
LOG(INFO) << "Start the Raftex Service successfully";
server_->getEventBaseManager()->getEventBase()->loopForever();
status_.store(STATUS_NOT_RUNNING);
LOG(INFO) << "The Raftex Service stopped";
}
std::shared_ptr<folly::IOThreadPoolExecutor>
RaftexService::getIOThreadPool() const {
return server_->getIOThreadPool();
}
std::shared_ptr<folly::Executor> RaftexService::getThreadManager() {
return server_->getThreadManager();
}
void RaftexService::stop() {
if (status_.load() != STATUS_RUNNING) {
return;
}
// stop service
LOG(INFO) << "Stopping the raftex service on port " << serverPort_;
{
folly::RWSpinLock::WriteHolder wh(partsLock_);
for (auto& p : parts_) {
p.second->stop();
}
parts_.clear();
LOG(INFO) << "All partitions have stopped";
}
server_->stop();
}
void RaftexService::waitUntilStop() {
if (serverThread_) {
serverThread_->join();
serverThread_.reset();
server_.reset();
LOG(INFO) << "Server thread has stopped. Service on port "
<< serverPort_ << " is ready to be destroyed";
}
}
void RaftexService::addPartition(std::shared_ptr<RaftPart> part) {
// todo(doodle): If we need to start both listener and normal replica on same hosts,
// this class need to be aware of type.
folly::RWSpinLock::WriteHolder wh(partsLock_);
parts_.emplace(std::make_pair(part->spaceId(), part->partitionId()),
part);
}
void RaftexService::removePartition(std::shared_ptr<RaftPart> part) {
folly::RWSpinLock::WriteHolder wh(partsLock_);
parts_.erase(std::make_pair(part->spaceId(), part->partitionId()));
// Stop the partition
part->stop();
}
std::shared_ptr<RaftPart> RaftexService::findPart(
GraphSpaceID spaceId,
PartitionID partId) {
folly::RWSpinLock::ReadHolder rh(partsLock_);
auto it = parts_.find(std::make_pair(spaceId, partId));
if (it == parts_.end()) {
// Part not found
LOG(WARNING) << "Cannot find the part " << partId
<< " in the graph space " << spaceId;
return std::shared_ptr<RaftPart>();
}
// Otherwise, return the part pointer
return it->second;
}
void RaftexService::askForVote(
cpp2::AskForVoteResponse& resp,
const cpp2::AskForVoteRequest& req) {
auto part = findPart(req.get_space(), req.get_part());
if (!part) {
// Not found
resp.set_error_code(cpp2::ErrorCode::E_UNKNOWN_PART);
return;
}
part->processAskForVoteRequest(req, resp);
}
void RaftexService::appendLog(
cpp2::AppendLogResponse& resp,
const cpp2::AppendLogRequest& req) {
auto part = findPart(req.get_space(), req.get_part());
if (!part) {
// Not found
resp.set_error_code(cpp2::ErrorCode::E_UNKNOWN_PART);
return;
}
part->processAppendLogRequest(req, resp);
}
void RaftexService::sendSnapshot(
cpp2::SendSnapshotResponse& resp,
const cpp2::SendSnapshotRequest& req) {
auto part = findPart(req.get_space(), req.get_part());
if (!part) {
// Not found
resp.set_error_code(cpp2::ErrorCode::E_UNKNOWN_PART);
return;
}
part->processSendSnapshotRequest(req, resp);
}
} // namespace raftex
} // namespace nebula
|
/*
The MIT License (MIT)
Copyright (c) 2013-2018 menonon
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 "marchingcubes_tf.hpp"
#include "error.hpp"
Shader* MarchingCubesTF::mMCShaderTransformFeedback = NULL;
Shader* MarchingCubesTF::mMCShaderRender = NULL;
bool MarchingCubesTF::isInitialized = false;
GLint* MarchingCubesTF::mEdgeConnection = NULL;
GLint* MarchingCubesTF::mEdgeFlags = NULL;
Texture<GLint>* MarchingCubesTF::mTexEdgeConnection = NULL;
MarchingCubesTF::~MarchingCubesTF() {
}
MarchingCubesTF::MarchingCubesTF() {
mModel = glm::mat4(1.0);
mIsThresholdChanged = true;
staticInit();
}
void MarchingCubesTF::staticInit() {
if (isInitialized) {
// do nothing
}
else {
isInitialized = true;
initTables();
initBuffers();
initShader();
}
}
void MarchingCubesTF::setData(Texture<GLfloat>* aData) {
mData = aData;
mData->createSampler(GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE);
mData->setTextureUnit(0);
}
void MarchingCubesTF::setThreshold(GLfloat aPercentage) {
GLfloat min = mData->getDataRange().x;
GLfloat max = mData->getDataRange().y;
GLfloat base = max - min;
GLfloat per = aPercentage * 0.01;
GLfloat tmpThreshold = (per * base) + min;
if (mThreshold != tmpThreshold) {
mIsThresholdChanged = true;
mThreshold = tmpThreshold;
//std::cout << "min,value,per,max: " << min << "," << mThreshold << "," << aPercentage << "," << max << std::endl;
GLfloat r, g, b;
r = per + 0.0;
if (per < 0.5) {
g = 2.0* per;
}
else {
g = -2.0* per + 2.0;
}
b = -per + 1.0;
mColor = glm::vec3(r, g, b);
}
else {
mIsThresholdChanged = false;
}
}
void MarchingCubesTF::bind() {
mTexEdgeConnection->bind();
mData->bind();
mCells->bind();
}
void MarchingCubesTF::unbind() {
mTexEdgeConnection->unbind();
mData->unbind();
mCells->unbind();
}
void MarchingCubesTF::render(glm::mat4 aProjection, glm::mat4 aView) {
if (mIsThresholdChanged) {
mMCShaderTransformFeedback->use();
bind();
//uniforms update
mMCShaderTransformFeedback->setUniform("uSlice", mSlices);
mMCShaderTransformFeedback->setUniform("uThreshold", mThreshold);
mMCShaderTransformFeedback->setUniform("uData", mData->getTextureUnit());
mMCShaderTransformFeedback->setUniform("uEdgeConnection", mTexEdgeConnection->getTextureUnit());
glEnable(GL_RASTERIZER_DISCARD);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, mTransformFeedbackObjectID);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, mTransformFeedbackVBOID);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 1, mTransformFeedbackVBONormalID);
glBeginTransformFeedback(GL_TRIANGLES);
mCells->draw();
glEndTransformFeedback();
glDisable(GL_RASTERIZER_DISCARD);
unbind();
mMCShaderTransformFeedback->unuse();
mIsThresholdChanged = false;
}
mMCShaderRender->use();
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, mTransformFeedbackObjectID);
glBindBuffer(GL_ARRAY_BUFFER, mTransformFeedbackVBOID);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, mTransformFeedbackVBONormalID);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
mMCShaderRender->setUniform("uProjection", aProjection);
mMCShaderRender->setUniform("uModelView", aView * mModel);
mMCShaderRender->setUniform("diffuse_albedo", mColor);
glDrawTransformFeedback(GL_TRIANGLES, mTransformFeedbackObjectID);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
mMCShaderRender->unuse();
}
void MarchingCubesTF::generateGeometry() {
mSlices = mData->getSize();
mCells = new Geometry(Geometry::POINTS);
std::vector<glm::vec3> points;
points.reserve((mSlices.x - 1) * (mSlices.y - 1) * (mSlices.z - 1));
std::cout << "reserve: " << (mSlices.x - 1) * (mSlices.y - 1) * (mSlices.z - 1) << std::endl;
for (float i = 0.5; i < mSlices.x - 1; i += 1.0) {
for (float j = 0.5; j < mSlices.y - 1; j += 1.0) {
for (float k = 0.5; k < mSlices.z - 1; k += 1.0) {
points.push_back(glm::vec3(i, j, k));
}
}
}
mCells->setVertices(&points);
// scale model matrix
glm::vec3 scaleVect = glm::vec3(2.0 / static_cast<GLfloat>(mSlices.x - 1), 2.0 / static_cast<GLfloat>(mSlices.y - 1), 2.0 / static_cast<GLfloat>(mSlices.z - 1));
glm::mat4 tra = glm::translate(glm::mat4(1.0), glm::vec3(-1.0, -1.0, -1.0));
glm::mat4 sca = glm::scale(tra, scaleVect);
mModel = sca;
}
void MarchingCubesTF::initTransformFeedback() {
glGenTransformFeedbacks(1, &mTransformFeedbackObjectID);
glGenBuffers(1, &mTransformFeedbackVBOID);
glGenBuffers(1, &mTransformFeedbackVBONormalID);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, mTransformFeedbackObjectID);
std::cout << "isTransfromFeedback: " << glIsTransformFeedback(mTransformFeedbackObjectID) << std::endl;
GLsizeiptr arrSize = (mSlices.x - 1) * (mSlices.y - 1) * (mSlices.z - 1) * 3 * 12 * sizeof(GLfloat);
//std::cout << "arrSize: " << arrSize << "mSlices.z - 1: " << (mSlices.z - 1) << std::endl;
glBindBuffer(GL_ARRAY_BUFFER, mTransformFeedbackVBOID);
glBufferData(GL_ARRAY_BUFFER, arrSize, nullptr, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, mTransformFeedbackVBOID);
glBindBuffer(GL_ARRAY_BUFFER, mTransformFeedbackVBONormalID);
glBufferData(GL_ARRAY_BUFFER, arrSize, nullptr, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, mTransformFeedbackVBONormalID);
}
void MarchingCubesTF::initShader() {
// Transform Feedback shader (no fragment shader)
mMCShaderTransformFeedback = new Shader();
mMCShaderTransformFeedback->compileShader(GL_VERTEX_SHADER, "../../shader/simple.vert");
mMCShaderTransformFeedback->compileShader(GL_GEOMETRY_SHADER, "../../shader/marchingcubes_tf.geom");
const char* varyings[] = { "iVertexPosition", "iNormal" };
mMCShaderTransformFeedback->setTransformFeedbackVaryings(varyings);
mMCShaderTransformFeedback->linkProgram();
// Render shader
mMCShaderRender = new Shader();
mMCShaderRender->compileShader(GL_VERTEX_SHADER, "../../shader/marchingcubes_tf_render_basic.vert");
mMCShaderRender->compileShader(GL_FRAGMENT_SHADER, "../../shader/marchingcubes_tf_render_phong.frag");
mMCShaderRender->linkProgram();
}
void MarchingCubesTF::initBuffers() {
mTexEdgeConnection = new Texture<GLint>(Texture<GLint>::T_BUFF, GL_R32I);
mTexEdgeConnection->setTextureUnit(1);
mTexEdgeConnection->setImageData(mEdgeConnection, 256, 16, 1, GL_R32I);
}
// copied from http://paulbourke.net/geometry/polygonise/marchingsource.cpp (public domain)
// and modified.
void MarchingCubesTF::initTables() {
mEdgeConnection = new GLint[256 * 16]
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 ,
3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 ,
3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 ,
3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 ,
9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 ,
9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 ,
2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 ,
8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 ,
9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 ,
4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 ,
3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 ,
1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 ,
4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 ,
4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 ,
5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 ,
2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 ,
9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 ,
0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 ,
2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 ,
10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 ,
5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 ,
5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 ,
9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 ,
0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 ,
1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 ,
10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 ,
8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 ,
2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 ,
7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 ,
2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 ,
11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 ,
5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 ,
11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 ,
11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 ,
1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 ,
9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 ,
5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 ,
2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 ,
5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 ,
6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 ,
3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 ,
6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 ,
5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 ,
1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 ,
10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 ,
6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 ,
8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 ,
7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 ,
3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 ,
5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 ,
0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 ,
9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 ,
8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 ,
5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 ,
0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 ,
6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 ,
10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 ,
10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 ,
8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 ,
1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 ,
0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 ,
10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 ,
3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 ,
6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 ,
9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 ,
8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 ,
3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 ,
6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 ,
0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 ,
10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 ,
10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 ,
2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 ,
7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 ,
7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 ,
2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 ,
1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 ,
11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 ,
8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 ,
0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 ,
7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 ,
10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 ,
2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 ,
6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 ,
7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 ,
2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 ,
1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 ,
10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 ,
10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 ,
0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 ,
7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 ,
6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 ,
8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 ,
9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 ,
6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 ,
4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 ,
10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 ,
8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 ,
0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 ,
1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 ,
8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 ,
10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 ,
4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 ,
10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 ,
5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 ,
11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 ,
9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 ,
6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 ,
7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 ,
3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 ,
7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 ,
3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 ,
6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 ,
9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 ,
1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 ,
4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 ,
7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 ,
6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 ,
3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 ,
0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 ,
6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 ,
0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 ,
11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 ,
6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 ,
5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 ,
9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 ,
1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 ,
1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 ,
10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 ,
0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 ,
5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 ,
10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 ,
11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 ,
9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 ,
7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 ,
2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 ,
8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 ,
9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 ,
9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 ,
1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 ,
9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 ,
9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 ,
5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 ,
0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 ,
10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 ,
2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 ,
0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 ,
0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 ,
9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 ,
5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 ,
3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 ,
5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 ,
8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 ,
0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 ,
9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 ,
1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 ,
3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 ,
4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 ,
9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 ,
11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 ,
11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 ,
2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 ,
9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 ,
3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 ,
1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 ,
4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 ,
3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 ,
0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 ,
9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 ,
1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
mEdgeFlags = new GLint[256]
{
0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460,
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0,
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230,
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190,
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000
};
}
|
// Copyright 2015 Dario Domizioli
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "core/chars/NamedCharacters.h"
#include "core/ctrl/DumbCtrl.h"
#include "core/ctrl/ExpertSystemCtrl.h"
#include "core/ctrl/EvolveAICtrl.h"
namespace core {
namespace chars {
using namespace core::game;
using namespace core::ctrl;
/*
c = std::make_shared<Character>(
"", 0, 0, 0, SP_COMBO,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"", MT_SPECIAL,
{}});
c->addMove(Move{"", MT_SPECIAL,
{}});
c->addMove(Move{"", MT_SPECIAL,
{}});
c->addMove(Move{"", MT_SUPER,
{}});
characters.push_back(c);
*/
std::vector<std::shared_ptr<game::Character>> getOriginalCharacters() {
std::vector<std::shared_ptr<game::Character>> characters{};
std::shared_ptr<Character> c;
// Stella
c = std::make_shared<Character>(
"Stella D'Argento", 4, 3, 0, SP_COMBO,
std::make_shared<MarkovAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Colpo Affilato", MT_SPECIAL,
{MS_SMASH}});
c->addMove(Move{"Proiezione Tagliente", MT_SPECIAL,
{MS_FALL, MS_2XCOMBO}});
c->addMove(Move{"Lama Sagittale", MT_SPECIAL,
{MS_BONUS_AIR, MS_BONUS_DOWN}});
c->addMove(Move{"Ruota della Spada", MT_SUPER,
{MS_ULTRA_AGILITY, MS_2XCOMBO, MS_2XCOMBO, MS_2XCOMBO}});
characters.push_back(c);
// Phanumas
c = std::make_shared<Character>(
"Phanumas", 3, 3, 1, SP_WOUND,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Dragon Knee", MT_SPECIAL,
{MS_DASH, MS_THROW}});
c->addMove(Move{"Dragon Fang", MT_SPECIAL,
{MS_ULTRA_HARDNESS, MS_ULTRA_AGILITY}});
c->addMove(Move{"Dragon's Breath", MT_SPECIAL,
{MS_DISTANCE}});
c->addMove(Move{"Flying Dragon", MT_SUPER,
{MS_DASH, MS_SMASH}});
characters.push_back(c);
// Jeanne Roux
c = std::make_shared<Character>(
"Jeanne Roux", 2, 4, 1, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Descending Rotation", MT_SPECIAL,
{MS_FALL, MS_BONUS_AIR}});
c->addMove(Move{"Ascending Rotation", MT_SPECIAL,
{MS_THROW, MS_BONUS_DOWN}});
c->addMove(Move{"Lightning Throw", MT_SPECIAL,
{MS_FALL}});
c->addMove(Move{"Tornado Throw", MT_SUPER,
{MS_THROW, MS_SMASH}});
characters.push_back(c);
// Romeo Rabemanjara
c = std::make_shared<Character>(
"Romeo Rabemanjara", 3, 4, 0, SP_COMBO,
std::make_shared<MarkovAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Gatling Attack", MT_SPECIAL,
{MS_2XCOMBO, MS_2XCOMBO, MS_2XCOMBO}});
c->addMove(Move{"Rampaging Kicks", MT_SPECIAL,
{MS_2XCOMBO}});
c->addMove(Move{"Pressing Punch", MT_SPECIAL,
{MS_DASH}});
c->addMove(Move{"Overwhelming Combo", MT_SUPER,
{MS_ULTRA_AGILITY, MS_THROW, MS_2XCOMBO, MS_2XCOMBO}});
characters.push_back(c);
// Luke Blades
c = std::make_shared<Character>(
"Luke Blades", 3, 3, 1, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Ascending Flash", MT_SPECIAL,
{MS_THROW}});
c->addMove(Move{"Falling Flash", MT_SPECIAL,
{MS_ULTRA_AGILITY, MS_JUMPOK}});
c->addMove(Move{"Lightning Kick", MT_SPECIAL,
{MS_ULTRA_HARDNESS}});
c->addMove(Move{"Tornado Flash", MT_SUPER,
{MS_POWERFUL, MS_ULTRA_AGILITY}});
characters.push_back(c);
// Ryouko Iga
c = std::make_shared<Character>(
"Ryouko Iga", 5, 0, 2, SP_AP,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Cobra no Kyushu", MT_SPECIAL,
{MS_THROW, MS_DISTANCE}});
c->addMove(Move{"Nishikimebi no Toguro", MT_SPECIAL,
{MS_FALL, MS_DISTANCE}});
c->addMove(Move{"Mamushi no Kiba", MT_SPECIAL,
{MS_ULTRA_AGILITY, MS_PUSH}});
c->addMove(Move{"Yamata no Orochi no Kamikizu", MT_SUPER,
{MS_ULTRA_AGILITY, MS_BONUS_AIR}});
characters.push_back(c);
// Johnny Yamashita
c = std::make_shared<Character>(
"Johnny Yamashita", 3, 1, 3, SP_WOUND,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Cross Counter", MT_SPECIAL,
{MS_BONUS_COUNTER, MS_BONUS_COUNTER}});
c->addMove(Move{"Hurricane Punch", MT_SPECIAL,
{MS_POWERFUL, MS_ULTRA_HARDNESS}});
c->addMove(Move{"Tornado Uppercut", MT_SPECIAL,
{MS_THROW}});
c->addMove(Move{"XXX Counter", MT_SUPER,
{MS_ULTRA_AGILITY, MS_BONUS_COUNTER, MS_BONUS_COUNTER}});
characters.push_back(c);
// Namgung Hyon-Su
c = std::make_shared<Character>(
"Namgung Hyon-Su", 3, 2, 2, SP_COMBO,
std::make_shared<MarkovAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Rising Darkness", MT_SPECIAL,
{MS_THROW, MS_ULTRA_AGILITY}});
c->addMove(Move{"Dark Arrows", MT_SPECIAL,
{MS_DISTANCE, MS_2XCOMBO}});
c->addMove(Move{"Dark Moon", MT_SPECIAL,
{MS_THROW, MS_PUSH, MS_2XCOMBO}});
c->addMove(Move{"Hell's Flames", MT_SUPER,
{MS_THROW, MS_DISTANCE, MS_ULTRA_AGILITY}});
characters.push_back(c);
// Zhang Shi
c = std::make_shared<Character>(
"Zhang Shi", 2, 3, 2, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Gang Zhao", MT_SPECIAL,
{MS_ULTRA_HARDNESS}});
c->addMove(Move{"Feng Zhao", MT_SPECIAL,
{MS_DISTANCE}});
c->addMove(Move{"Xin Yue Ti", MT_SPECIAL,
{MS_PUSH, MS_BONUS_AIR}});
c->addMove(Move{"Fengbao Zhao", MT_SUPER,
{MS_ULTRA_AGILITY, MS_DISTANCE, MS_BONUS_FAR}});
characters.push_back(c);
// Rock Stark
c = std::make_shared<Character>(
"Rock Stark", 2, 2, 3, SP_DEFENCE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Radiant Reflection", MT_SPECIAL,
{MS_REFLECT, MS_BONUS_COUNTER}});
c->addMove(Move{"Radiant Kick", MT_SPECIAL,
{MS_THROW}});
c->addMove(Move{"Flash Uppercut", MT_SPECIAL,
{MS_ULTRA_AGILITY, MS_BONUS_AIR}});
c->addMove(Move{"Atomic Punch", MT_SUPER,
{MS_POWERFUL, MS_ULTRA_AGILITY, MS_BONUS_COUNTER}});
characters.push_back(c);
return characters;
}
std::vector<std::shared_ptr<game::Character>> getSiegeOfSydeCharacters() {
std::vector<std::shared_ptr<game::Character>> characters{};
std::shared_ptr<Character> c;
// ========================================================================
// The Army of the Principality
// ========================================================================
// Alexis
c = std::make_shared<Character>(
"Duke Alexis the Sun Spear", 2, 1, 4, SP_DEFENCE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Steel Spear", MT_SPECIAL,
{MS_SMASH}});
c->addMove(Move{"Resounding Parry", MT_SPECIAL,
{MS_REFLECT, MS_PUSH}});
c->addMove(Move{"Rolling Wave of Earth", MT_SPECIAL,
{MS_BONUS_NEAR, MS_THROW}});
c->addMove(Move{"Invincible Kata of the Spear", MT_SUPER,
{MS_SMASH, MS_POWERFUL, MS_BONUS_NEAR}});
characters.push_back(c);
// Gunther
c = std::make_shared<Character>(
"Gunther the Thundering Gryphon", 3, 3, 1, SP_WOUND,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Crackling Mace", MT_SPECIAL,
{MS_PUSH}});
c->addMove(Move{"Thunder Clap", MT_SPECIAL,
{MS_BONUS_NEAR, MS_ULTRA_HARDNESS}});
c->addMove(Move{"Titan's Maul", MT_SPECIAL,
{MS_PUSH, MS_SMASH}});
c->addMove(Move{"Call Lightning", MT_SUPER,
{MS_SMASH, MS_POWERFUL, MS_DISTANCE}});
characters.push_back(c);
// Yavanna
c = std::make_shared<Character>(
"Yavanna the Rampant Bear", 2, 4, 1, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Bear Claw", MT_SPECIAL,
{MS_POWERFUL}});
c->addMove(Move{"Bear Hug", MT_SPECIAL,
{MS_SMASH, MS_BONUS_NEAR}});
c->addMove(Move{"Caber Throw", MT_SPECIAL,
{MS_SMASH, MS_THROW}});
c->addMove(Move{"Fury of the Bear", MT_SUPER,
{MS_PUSH, MS_POWERFUL, MS_SMASH}});
characters.push_back(c);
// Julius
c = std::make_shared<Character>(
"Julius the Sleeping Dragon", 2, 3, 2, SP_WOUND,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Waking the Dragon", MT_SPECIAL,
{MS_THROW}});
c->addMove(Move{"Tidal Wave", MT_SPECIAL,
{MS_DISTANCE, MS_BONUS_FAR}});
c->addMove(Move{"Tears of the Dragon", MT_SPECIAL,
{MS_POWERFUL, MS_FALL}});
c->addMove(Move{"The Storm Where The Sky Meets The Sea", MT_SUPER,
{MS_DISTANCE, MS_POWERFUL, MS_ULTRA_HARDNESS}});
characters.push_back(c);
// Hartwin
c = std::make_shared<Character>(
"Hartwin the White Raven", 3, 3, 1, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Magic Staff", MT_SPECIAL,
{MS_SMASH}});
c->addMove(Move{"Blades of Light", MT_SPECIAL,
{MS_ULTRA_AGILITY, MS_POWERFUL}});
c->addMove(Move{"Pressure Wave", MT_SPECIAL,
{MS_ULTRA_AGILITY, MS_BONUS_NEAR}});
c->addMove(Move{"Summoning the Raven of Light", MT_SUPER,
{MS_DISTANCE, MS_POWERFUL, MS_POWERFUL}});
characters.push_back(c);
// Isolde
c = std::make_shared<Character>(
"Isolde the Chrysalis", 1, 1, 5, SP_DEFENCE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Mantis Pounce", MT_SPECIAL,
{MS_JUMPOK}});
c->addMove(Move{"Falling Tree", MT_SPECIAL,
{MS_POWERFUL, MS_FALL}});
c->addMove(Move{"Horrid Swarm", MT_SPECIAL,
{MS_SMASH, MS_ULTRA_AGILITY}});
c->addMove(Move{"First Flight of the Chrysalis", MT_SUPER,
{MS_JUMPOK, MS_DASH, MS_POWERFUL}});
characters.push_back(c);
// Ross
c = std::make_shared<Character>(
"Ross Garnet the Master of Axes", 4, 2, 1, SP_COMBO,
std::make_shared<BrawlerAtk>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Rising Quarter", MT_SPECIAL,
{MS_THROW}});
c->addMove(Move{"Fleeting Crescent", MT_SPECIAL,
{MS_BONUS_NEAR, MS_2XCOMBO}});
c->addMove(Move{"Rolling Moon", MT_SPECIAL,
{MS_2XCOMBO, MS_2XCOMBO}});
c->addMove(Move{"Feral Fury", MT_SUPER,
{MS_DASH, MS_SMASH, MS_FALL}});
characters.push_back(c);
// ========================================================================
// The Defenders of Syde
// ========================================================================
// Thorsten
c = std::make_shared<Character>(
"Duke Thorsten the Dragonslayer", 2, 4, 1, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Rising Strike", MT_SPECIAL,
{MS_BONUS_NEAR}});
c->addMove(Move{"Away from me!", MT_SPECIAL,
{MS_THROW, MS_PUSH}});
c->addMove(Move{"Bone Crushing Slash", MT_SPECIAL,
{MS_ULTRA_HARDNESS, MS_FALL}});
c->addMove(Move{"Dragon Decapitation", MT_SUPER,
{MS_PUSH, MS_SMASH, MS_POWERFUL}});
characters.push_back(c);
// Bertram
c = std::make_shared<Character>(
"Bertram the Flying Fish", 2, 0, 5, SP_DEFENCE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Ice Mirror", MT_SPECIAL,
{MS_REFLECT}});
c->addMove(Move{"Salmon Leap", MT_SPECIAL,
{MS_JUMPOK, MS_ULTRA_AGILITY}});
c->addMove(Move{"Insidious Ice", MT_SPECIAL,
{MS_BONUS_NEAR, MS_FALL}});
c->addMove(Move{"Snow Blizzard", MT_SUPER,
{MS_DISTANCE, MS_BONUS_FAR, MS_POWERFUL}});
characters.push_back(c);
// Eleanor
c = std::make_shared<Character>(
"Eleanor the Hummingsword", 3, 3, 1, SP_DAMAGE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Hummingbird Kiss", MT_SPECIAL,
{MS_SMASH}});
c->addMove(Move{"Parting the Silk", MT_SPECIAL,
{MS_POWERFUL, MS_BONUS_NEAR}});
c->addMove(Move{"Flight of the Hummingbird", MT_SPECIAL,
{MS_THROW, MS_ULTRA_AGILITY}});
c->addMove(Move{"Virtuoso Sword Dance", MT_SUPER,
{MS_BONUS_NEAR, MS_FALL, MS_ULTRA_HARDNESS}});
characters.push_back(c);
// Lothar
c = std::make_shared<Character>(
"Lothar the Riding Avalanche", 3, 3, 1, SP_WOUND,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Ride-by Attack", MT_SPECIAL,
{MS_PUSH}});
c->addMove(Move{"Impetuous Charge", MT_SPECIAL,
{MS_DASH, MS_BONUS_NEAR}});
c->addMove(Move{"Trampling Assault", MT_SPECIAL,
{MS_ULTRA_HARDNESS, MS_POWERFUL}});
c->addMove(Move{"Riding the Avalanche", MT_SUPER,
{MS_PUSH, MS_POWERFUL, MS_BONUS_NEAR}});
characters.push_back(c);
// Kestin
c = std::make_shared<Character>(
"Kestin the Cloud of Arrows", 1, 1, 5, SP_DEFENCE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Hunter Trap", MT_SPECIAL,
{MS_FALL}});
c->addMove(Move{"Sure Strike", MT_SPECIAL,
{MS_DISTANCE, MS_BONUS_FAR}});
c->addMove(Move{"Arrow Nova", MT_SPECIAL,
{MS_PUSH, MS_THROW}});
c->addMove(Move{"Energy Arrow", MT_SUPER,
{MS_DISTANCE, MS_POWERFUL, MS_ULTRA_HARDNESS}});
characters.push_back(c);
// Scarlet
c = std::make_shared<Character>(
"Scarlet the Ardent Flame", 3, 2, 2, SP_COMBO,
std::make_shared<BrawlerAtk>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Flame Pillar", MT_SPECIAL,
{MS_THROW}});
c->addMove(Move{"Spinning Ring of Fire", MT_SPECIAL,
{MS_2XCOMBO, MS_POWERFUL}});
c->addMove(Move{"The Good Old Fireball", MT_SPECIAL,
{MS_DISTANCE, MS_BONUS_FAR}});
c->addMove(Move{"Burning Wind of Noon", MT_SUPER,
{MS_DASH, MS_SMASH, MS_2XCOMBO}});
characters.push_back(c);
// Vune
c = std::make_shared<Character>(
"Vune the Livid Necromancer", 2, 2, 3, SP_DEFENCE,
std::make_shared<EvolveAIAttack>(),
std::make_shared<EvolveAIDefence>());
c->addMove(Move{"Horror Vacui", MT_SPECIAL,
{MS_FALL}});
c->addMove(Move{"Gust of Lost Souls", MT_SPECIAL,
{MS_ULTRA_AGILITY, MS_BONUS_NEAR}});
c->addMove(Move{"Reaping Darkness", MT_SPECIAL,
{MS_POWERFUL, MS_POWERFUL}});
c->addMove(Move{"Infernal Comet", MT_SUPER,
{MS_DASH, MS_SMASH, MS_ULTRA_HARDNESS}});
characters.push_back(c);
return characters;
}
}
}
|
#ifndef RAYLIB_CPP_INCLUDE_AUDIOSTREAM_HPP_
#define RAYLIB_CPP_INCLUDE_AUDIOSTREAM_HPP_
#include "./raylib.hpp"
#include "./raylib-cpp-utils.hpp"
#include "./RaylibException.hpp"
namespace raylib {
/**
* AudioStream management functions
*/
class AudioStream : public ::AudioStream {
public:
AudioStream(const ::AudioStream& music) {
set(music);
}
AudioStream(rAudioBuffer* buffer = nullptr,
unsigned int sampleRate = 0,
unsigned int sampleSize = 0,
unsigned int channels = 0) : ::AudioStream{buffer, sampleRate, sampleSize, channels} {
// Nothing.
}
/**
* Init audio stream (to stream raw audio pcm data)
*
* @throws raylib::RaylibException Throws if the AudioStream failed to load.
*/
AudioStream(unsigned int SampleRate, unsigned int SampleSize, unsigned int Channels = 2) {
if (!Load(SampleRate, SampleSize, Channels)) {
throw RaylibException("Failed to create AudioStream");
}
}
AudioStream(const AudioStream&) = delete;
AudioStream(AudioStream&& other) {
set(other);
other.buffer = nullptr;
other.sampleRate = 0;
other.sampleSize = 0;
other.channels = 0;
}
~AudioStream() {
Unload();
}
GETTERSETTER(rAudioBuffer *, Buffer, buffer)
GETTERSETTER(unsigned int, SampleRate, sampleRate)
GETTERSETTER(unsigned int, SampleSize, sampleSize)
GETTERSETTER(unsigned int, Channels, channels)
AudioStream& operator=(const ::AudioStream& stream) {
set(stream);
return *this;
}
AudioStream& operator=(const AudioStream&) = delete;
AudioStream& operator=(AudioStream&& other) {
if (this == &other) {
return *this;
}
Unload();
set(other);
other.buffer = nullptr;
other.sampleRate = 0;
other.sampleSize = 0;
other.channels = 0;
return *this;
}
/**
* Update audio stream buffers with data
*/
inline AudioStream& Update(const void *data, int samplesCount) {
::UpdateAudioStream(*this, data, samplesCount);
return *this;
}
/**
* Unload audio stream and free memory
*/
inline void Unload() {
::UnloadAudioStream(*this);
}
/**
* Check if any audio stream buffers requires refill
*/
inline bool IsProcessed() const {
return ::IsAudioStreamProcessed(*this);
}
/**
* Play audio stream
*/
inline AudioStream& Play() {
::PlayAudioStream(*this);
return *this;
}
/**
* Pause audio stream
*/
inline AudioStream& Pause() {
::PauseAudioStream(*this);
return *this;
}
/**
* Resume audio stream
*/
inline AudioStream& Resume() {
::ResumeAudioStream(*this);
return *this;
}
/**
* Check if audio stream is playing
*/
inline bool IsPlaying() const {
return ::IsAudioStreamPlaying(*this);
}
/**
* Stop audio stream
*/
inline AudioStream& Stop() {
::StopAudioStream(*this);
return *this;
}
/**
* Set volume for audio stream (1.0 is max level)
*/
inline AudioStream& SetVolume(float volume) {
::SetAudioStreamVolume(*this, volume);
return *this;
}
/**
* Set pitch for audio stream (1.0 is base level)
*/
inline AudioStream& SetPitch(float pitch) {
::SetAudioStreamPitch(*this, pitch);
return *this;
}
/**
* Default size for new audio streams
*/
inline static void SetBufferSizeDefault(int size) {
::SetAudioStreamBufferSizeDefault(size);
}
/**
* Retrieve whether or not the audio stream is ready.
*/
bool IsReady() {
return channels > 0;
}
/**
* Init audio stream (to stream raw audio pcm data)
*
* @return True or false depending on if the audio stream initialized properly.
*/
bool Load(unsigned int SampleRate, unsigned int SampleSize, unsigned int Channels = 2) {
set(::LoadAudioStream(SampleRate, SampleSize, Channels));
return IsReady();
}
private:
inline void set(const ::AudioStream& stream) {
buffer = stream.buffer;
sampleRate = stream.sampleRate;
sampleSize = stream.sampleSize;
channels = stream.channels;
}
};
} // namespace raylib
#endif // RAYLIB_CPP_INCLUDE_AUDIOSTREAM_HPP_
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// 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/actor/Timeout.h"
#include "td/utils/logging.h"
#include "td/utils/Time.h"
namespace td {
bool MultiTimeout::has_timeout(int64 key) const {
return items_.find(Item(key)) != items_.end();
}
void MultiTimeout::set_timeout_at(int64 key, double timeout) {
LOG(DEBUG) << "Set " << get_name() << " for " << key << " in " << timeout - Time::now();
auto item = items_.emplace(key);
auto heap_node = static_cast<HeapNode *>(const_cast<Item *>(&*item.first));
if (heap_node->in_heap()) {
CHECK(!item.second);
bool need_update_timeout = heap_node->is_top();
timeout_queue_.fix(timeout, heap_node);
if (need_update_timeout || heap_node->is_top()) {
update_timeout();
}
} else {
CHECK(item.second);
timeout_queue_.insert(timeout, heap_node);
if (heap_node->is_top()) {
update_timeout();
}
}
}
void MultiTimeout::add_timeout_at(int64 key, double timeout) {
LOG(DEBUG) << "Add " << get_name() << " for " << key << " in " << timeout - Time::now();
auto item = items_.emplace(key);
auto heap_node = static_cast<HeapNode *>(const_cast<Item *>(&*item.first));
if (heap_node->in_heap()) {
CHECK(!item.second);
} else {
CHECK(item.second);
timeout_queue_.insert(timeout, heap_node);
if (heap_node->is_top()) {
update_timeout();
}
}
}
void MultiTimeout::cancel_timeout(int64 key) {
LOG(DEBUG) << "Cancel " << get_name() << " for " << key;
auto item = items_.find(Item(key));
if (item != items_.end()) {
auto heap_node = static_cast<HeapNode *>(const_cast<Item *>(&*item));
CHECK(heap_node->in_heap());
bool need_update_timeout = heap_node->is_top();
timeout_queue_.erase(heap_node);
items_.erase(item);
if (need_update_timeout) {
update_timeout();
}
}
}
void MultiTimeout::update_timeout() {
if (items_.empty()) {
LOG(DEBUG) << "Cancel timeout of " << get_name();
CHECK(timeout_queue_.empty());
CHECK(Actor::has_timeout());
Actor::cancel_timeout();
} else {
LOG(DEBUG) << "Set timeout of " << get_name() << " in " << timeout_queue_.top_key() - Time::now_cached();
Actor::set_timeout_at(timeout_queue_.top_key());
}
}
vector<int64> MultiTimeout::get_expired_keys(double now) {
vector<int64> expired_keys;
while (!timeout_queue_.empty() && timeout_queue_.top_key() < now) {
int64 key = static_cast<Item *>(timeout_queue_.pop())->key;
items_.erase(Item(key));
expired_keys.push_back(key);
}
return expired_keys;
}
void MultiTimeout::timeout_expired() {
vector<int64> expired_keys = get_expired_keys(Time::now_cached());
if (!items_.empty()) {
update_timeout();
}
for (auto key : expired_keys) {
callback_(data_, key);
}
}
void MultiTimeout::run_all() {
vector<int64> expired_keys = get_expired_keys(Time::now_cached() + 1e10);
if (!expired_keys.empty()) {
update_timeout();
}
for (auto key : expired_keys) {
callback_(data_, key);
}
}
} // namespace td
|
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
char s[1008];
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
#endif
int T, x, n;
scanf("%d", &T);
while(T--){
scanf("%s", s);
int l = strlen(s);
scanf("%d", &n);
assert(n <= 12);
bool ok = true;
for(int i = 0; i < n; i++){
scanf("%d", &x);
int mod = 0;
for(int j = 0; j < l; j++){
mod = (mod * 10 + s[j] - '0');
mod %= x;
}
ok &= mod == 0;
}
printf("%s - ", s);
printf(ok ? "Wonderful." : "Simple.");
printf("\n");
}
return 0;
}
|
// Copyright (c) 2006-2008 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 <stdio.h>
#include <windows.h>
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/src/broker_services.h"
#include "sandbox/src/target_services.h"
#if defined(_WIN64) && !defined(NACL_WIN64)
// We allow building this code for Win64 as part of NaCl to enable development
#error Sandbox code was not tested on 64-bit Windows. See \
http://crbug.com/27218 for details and progress log.
#endif
namespace sandbox {
// The section for IPC and policy.
SANDBOX_INTERCEPT HANDLE g_shared_section = NULL;
static bool s_is_broker = false;
// GetBrokerServices: the current implementation relies on a shared section
// that is created by the broker and opened by the target.
BrokerServices* SandboxFactory::GetBrokerServices() {
// Can't be the broker if the shared section is open.
if (NULL != g_shared_section) {
return NULL;
}
// If the shared section does not exist we are the broker, then create
// the broker object.
s_is_broker = true;
return BrokerServicesBase::GetInstance();
}
// GetTargetServices implementation must follow the same technique as the
// GetBrokerServices, but in this case the logic is the opposite.
TargetServices* SandboxFactory::GetTargetServices() {
// Can't be the target if the section handle is not valid.
if (NULL == g_shared_section) {
return NULL;
}
// We are the target
s_is_broker = false;
// Creates and returns the target services implementation.
return TargetServicesBase::GetInstance();
}
} // namespace sandbox
|
#if defined(LINUX) || defined(FREEBSD)
#define GL_GLEXT_PROTOTYPES
#endif
// Toonz includes
#include "tapp.h"
#include "viewerpane.h"
#include "onionskinmaskgui.h"
#include "viewerdraw.h"
#include "menubarcommandids.h"
#include "ruler.h"
#include "locatorpopup.h"
#include "../stopmotion/stopmotion.h"
// TnzTools includes
#include "tools/cursors.h"
#include "tools/cursormanager.h"
#include "tools/toolhandle.h"
#include "tools/toolcommandids.h"
#include "tools/toolutils.h"
// TnzQt includes
#include "toonzqt/icongenerator.h"
#include "toonzqt/gutil.h"
#include "toonzqt/imageutils.h"
#include "toonzqt/lutcalibrator.h"
#include "toonzqt/viewcommandids.h"
// TnzLib includes
#include "toonz/tscenehandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/tframehandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/sceneproperties.h"
#include "toonz/toonzscene.h"
#include "toonz/levelset.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/tcamera.h"
#include "toonz/stage2.h"
#include "toonz/stage.h"
#include "toonz/stageplayer.h"
#include "toonz/stagevisitor.h"
#include "toonz/txsheet.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/tstageobjectspline.h"
#include "toonz/tobjecthandle.h"
#include "toonz/tonionskinmaskhandle.h"
#include "toonz/palettecontroller.h"
#include "toonz/tpalettehandle.h"
#include "toonz/childstack.h"
#include "toonz/dpiscale.h"
#include "toonz/txshlevel.h"
#include "toonz/txshlevelcolumn.h"
#include "toonz/preferences.h"
#include "toonz/glrasterpainter.h"
#include "toonz/cleanupparameters.h"
#include "toonz/toonzimageutils.h"
#include "toonz/txshleveltypes.h"
#include "subcameramanager.h"
// TnzCore includes
#include "tpalette.h"
#include "tropcm.h"
#include "tgl.h"
#include "tofflinegl.h"
#include "tstopwatch.h"
#include "trop.h"
#include "tproperty.h"
#include "timagecache.h"
#include "trasterimage.h"
#include "tstroke.h"
#include "ttoonzimage.h"
#include "tenv.h"
#include "tcurves.h"
// Qt includes
#include <QMenu>
#include <QApplication>
#include <QDesktopWidget>
#if QT_VERSION >= 0x050000
#include <QInputMethod>
#else
#include <QInputContext>
#endif
#include <QGLContext>
#include <QOpenGLFramebufferObject>
#include <QMainWindow>
#include "sceneviewer.h"
TEnv::IntVar ShowPerspectiveGrids("ShowPerspectiveGrids", 1);
void drawSpline(const TAffine &viewMatrix, const TRect &clipRect, bool camera3d,
double pixelSize);
//-------------------------------------------------------------------------------
namespace {
int l_mainDisplayListsSpaceId =
-1; //!< Display lists space id associated with SceneViewers
std::set<TGlContext>
l_contexts; //!< Stores every SceneViewer context (see ~SceneViewer)
//-------------------------------------------------------------------------------
struct DummyProxy : public TGLDisplayListsProxy {
~DummyProxy() {}
void makeCurrent() {}
void doneCurrent() {}
};
//-------------------------------------------------------------------------------
double getActualFrameRate() {
// compute frame per second
static double fps = 0;
static TStopWatch stopwatch;
static int frame = 0;
++frame;
stopwatch.start();
unsigned long tt = stopwatch.getTotalTime();
// wait a time greater than one second
if (tt > 1000) {
stopwatch.stop();
fps = troundp(((1000 * frame) / (double)tt));
stopwatch.start(true);
frame = 0;
}
return fps;
}
//-----------------------------------------------------------------------------
void copyFrontBufferToBackBuffer() {
static GLint viewport[4];
static GLfloat raster_pos[4];
glGetIntegerv(GL_VIEWPORT, viewport);
/* set source buffer */
glReadBuffer(GL_FRONT);
/* set projection matrix */
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, viewport[2], 0, viewport[3]);
/* set modelview matrix */
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
/* save old raster position */
glGetFloatv(GL_CURRENT_RASTER_POSITION, raster_pos);
/* set raster position */
glRasterPos4f(0.0, 0.0, 0.0, 1.0);
/* copy buffer */
glCopyPixels(0, 0, viewport[2], viewport[3], GL_COLOR);
/* restore old raster position */
glRasterPos4fv(raster_pos);
/* restore old matrices */
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
/* restore source buffer */
glReadBuffer(GL_BACK);
}
//-----------------------------------------------------------------------------
/*! Compute new 3Dposition and new 2D position. */
T3DPointD computeNew3DPosition(T3DPointD start3DPos, TPointD delta2D,
TPointD &new2dPos, GLdouble modelView3D[16],
GLdouble projection3D[16], GLint viewport3D[4],
int devPixRatio) {
GLdouble pos2D_x, pos2D_y, pos2D_z;
gluProject(-start3DPos.x, -start3DPos.y, start3DPos.z, modelView3D,
projection3D, viewport3D, &pos2D_x, &pos2D_y, &pos2D_z);
new2dPos = TPointD(pos2D_x + delta2D.x, pos2D_y + delta2D.y);
GLdouble pos3D_x, pos3D_y, pos3D_z;
gluUnProject(new2dPos.x, new2dPos.y, 1, modelView3D, projection3D, viewport3D,
&pos3D_x, &pos3D_y, &pos3D_z);
new2dPos.y = viewport3D[3] - new2dPos.y - 20 * devPixRatio;
return T3DPointD(pos3D_x, pos3D_y, pos3D_z);
}
//-----------------------------------------------------------------------------
#ifdef DA_RIVEDERE
// Il metodo copia una porzione del BACK_BUFFER definita da rect nel
// FRONTE_BUFFER
// Attualmente si notano delle brutture intorno al rettangolo.
// Per il momento si lavora nel BACK_BUFFER e sicopia tutto il FRONT_BUFFER.
// Riattivando questo metodo bisogna ricordarsi di disattivare lo swapbuffer in
// GLInvalidateRect prima di
// fare updateGL() e riattivarlo immediatamernte dopo!
void copyBackBufferToFrontBuffer(const TRect &rect) {
static GLint viewport[4];
static GLfloat raster_pos[4];
glGetIntegerv(GL_VIEWPORT, viewport);
/* set source buffer */
glReadBuffer(GL_BACK);
glDrawBuffer(GL_FRONT);
/* set projection matrix */
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, viewport[2], 0, viewport[3]);
/* set modelview matrix */
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
/* save old raster position */
glGetFloatv(GL_CURRENT_RASTER_POSITION, raster_pos);
/* set raster position */
glRasterPos4f(0.0, 0.0, 0.0, 1.0);
/* copy buffer */
glCopyPixels(0, 0, viewport[2], viewport[3], GL_COLOR);
/* restore old raster position */
glRasterPos4fv(raster_pos);
/* restore old matrices */
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
/* restore source buffer */
glDrawBuffer(GL_BACK);
}
#endif
double getCubicYfromX(TCubic c, double x, double &s0, double &s1) {
double s = (s1 + s0) * 0.5;
TPointD p = c.getPoint(s);
if (areAlmostEqual(x, p.x, 0.001)) return p.y;
if (areAlmostEqual(s0, s1, 0.0001)) {
return p.y;
}
if (x < p.x)
return getCubicYfromX(c, x, s0, s);
else
return getCubicYfromX(c, x, s, s1);
}
const TRectD InvalidateAllRect(0, 0, -1, -1);
//-----------------------------------------------------------------------------
} // namespace
//-----------------------------------------------------------------------------
//=============================================================================
// ToggleCommand
//-----------------------------------------------------------------------------
ToggleCommandHandler::ToggleCommandHandler(CommandId id, bool startStatus)
: MenuItemHandler(id), m_status(startStatus) {}
void ToggleCommandHandler::execute() {
m_status = !m_status;
// emit sceneChanged WITHOUT dirty flag
TApp::instance()->getCurrentScene()->notifySceneChanged(false);
}
//-----------------------------------------------------------------------------
ToggleCommandHandler viewTableToggle(MI_ViewTable, false);
ToggleCommandHandler editInPlaceToggle(MI_ToggleEditInPlace, false);
ToggleCommandHandler fieldGuideToggle(MI_FieldGuide, false);
ToggleCommandHandler safeAreaToggle(MI_SafeArea, false);
ToggleCommandHandler rasterizePliToggle(MI_RasterizePli, false);
ToggleCommandHandler viewClcToggle("MI_ViewColorcard", false);
ToggleCommandHandler viewCameraToggle("MI_ViewCamera", false);
ToggleCommandHandler viewBBoxToggle("MI_ViewBBox", false);
ToggleCommandHandler viewGuideToggle("MI_ViewGuide", false);
ToggleCommandHandler viewRulerToggle("MI_ViewRuler", false);
//-----------------------------------------------------------------------------
void invalidateIcons() {
ToonzCheck *tc = ToonzCheck::instance();
int mask = tc->getChecks();
IconGenerator::Settings s;
s.m_blackBgCheck = mask & ToonzCheck::eBlackBg;
s.m_transparencyCheck = mask & ToonzCheck::eTransparency;
s.m_inksOnly = mask & ToonzCheck::eInksOnly;
// emphasize lines with style#1 regardless of the current style
if (mask & ToonzCheck::eInk1) s.m_inkIndex = 1;
// emphasize lines with the current style
else if (mask & ToonzCheck::eInk)
s.m_inkIndex = tc->getColorIndex();
else
s.m_inkIndex = -1;
s.m_paintIndex = mask & ToonzCheck::ePaint ? tc->getColorIndex() : -1;
IconGenerator::instance()->setSettings(s);
// Force icons to refresh for Toonz Vector levels
TXshLevel *sl = TApp::instance()->getCurrentLevel()->getLevel();
if (sl && sl->getType() == PLI_XSHLEVEL) {
std::vector<TFrameId> fids;
sl->getFids(fids);
for (int i = 0; i < (int)fids.size(); i++)
IconGenerator::instance()->invalidate(sl, fids[i]);
}
// Do not remove icons here as they will be re-used for updating icons in the
// level strip
// emit sceneChanged WITHOUT dirty flag
TApp::instance()->getCurrentScene()->notifySceneChanged(false);
TApp::instance()->getCurrentLevel()->notifyLevelViewChange();
}
//--------------------------------------------------------------
static void executeCheck(int checkType) {
ToonzCheck::instance()->toggleCheck(checkType);
invalidateIcons();
}
//-----------------------------------------------------------------------------
class TCheckToggleCommand final : public MenuItemHandler {
public:
TCheckToggleCommand() : MenuItemHandler("MI_TCheck") {}
void execute() override { executeCheck(ToonzCheck::eTransparency); }
} tcheckToggle;
//-----------------------------------------------------------------------------
class ICheckToggleCommand final : public MenuItemHandler {
public:
ICheckToggleCommand() : MenuItemHandler("MI_ICheck") {}
void execute() override { executeCheck(ToonzCheck::eInk); }
} icheckToggle;
//-----------------------------------------------------------------------------
class PCheckToggleCommand final : public MenuItemHandler {
public:
PCheckToggleCommand() : MenuItemHandler("MI_PCheck") {}
void execute() override { executeCheck(ToonzCheck::ePaint); }
} pcheckToggle;
//-----------------------------------------------------------------------------
class BCheckToggleCommand final : public MenuItemHandler {
public:
BCheckToggleCommand() : MenuItemHandler("MI_BCheck") {}
void execute() override { executeCheck(ToonzCheck::eBlackBg); }
} bcheckToggle;
//-----------------------------------------------------------------------------
class TAutocloseToggleCommand final : public MenuItemHandler {
public:
TAutocloseToggleCommand() : MenuItemHandler("MI_ACheck") {}
void execute() override { executeCheck(ToonzCheck::eAutoclose); }
} tautocloseToggle;
//-----------------------------------------------------------------------------
class TGapToggleCommand final : public MenuItemHandler {
public:
TGapToggleCommand() : MenuItemHandler("MI_GCheck") {}
void execute() override { executeCheck(ToonzCheck::eGap); }
} tgapToggle;
//-----------------------------------------------------------------------------
class TInksOnlyToggleCommand final : public MenuItemHandler {
public:
TInksOnlyToggleCommand() : MenuItemHandler("MI_IOnly") {}
void execute() override { executeCheck(ToonzCheck::eInksOnly); }
} tinksOnlyToggle;
//-----------------------------------------------------------------------------
/*! emphasize lines with style#1 regardless of the current style
*/
class Ink1CheckToggleCommand final : public MenuItemHandler {
public:
Ink1CheckToggleCommand() : MenuItemHandler("MI_Ink1Check") {}
void execute() override { executeCheck(ToonzCheck::eInk1); }
} ink1checkToggle;
//=============================================================================
class TShiftTraceToggleCommand final : public MenuItemHandler {
CommandId m_cmdId;
public:
TShiftTraceToggleCommand(CommandId cmdId)
: MenuItemHandler(cmdId), m_cmdId(cmdId) {}
void execute() override {
CommandManager *cm = CommandManager::instance();
QAction *action = cm->getAction(m_cmdId);
bool checked = action->isChecked();
if (std::string(m_cmdId) == MI_ShiftTrace) {
cm->enable(MI_EditShift, checked);
cm->enable(MI_NoShift, checked);
if (checked) OnioniSkinMaskGUI::resetShiftTraceFrameOffset();
// cm->getAction(MI_NoShift)->setChecked(false);
TApp::instance()->getCurrentOnionSkin()->notifyOnionSkinMaskChanged();
} else if (std::string(m_cmdId) == MI_EditShift) {
if (checked) {
QAction *noShiftAction =
CommandManager::instance()->getAction(MI_NoShift);
if (noShiftAction) noShiftAction->setChecked(false);
TApp::instance()->getCurrentTool()->setPseudoTool("T_ShiftTrace");
} else {
TApp::instance()->getCurrentTool()->unsetPseudoTool();
}
CommandManager::instance()->enable(MI_NoShift, !checked);
} else if (std::string(m_cmdId) == MI_NoShift) {
}
updateShiftTraceStatus();
}
bool isChecked(CommandId id) const {
QAction *action = CommandManager::instance()->getAction(id);
return action != 0 && action->isChecked();
}
void updateShiftTraceStatus() {
OnionSkinMask::ShiftTraceStatus status = OnionSkinMask::DISABLED;
if (isChecked(MI_ShiftTrace)) {
if (isChecked(MI_EditShift))
status = OnionSkinMask::EDITING_GHOST;
else if (isChecked(MI_NoShift))
status = OnionSkinMask::ENABLED_WITHOUT_GHOST_MOVEMENTS;
else
status = OnionSkinMask::ENABLED;
}
OnionSkinMask osm =
TApp::instance()->getCurrentOnionSkin()->getOnionSkinMask();
osm.setShiftTraceStatus(status);
osm.clearGhostFlipKey();
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
TApp::instance()->getCurrentOnionSkin()->setOnionSkinMask(osm);
}
};
TShiftTraceToggleCommand shiftTraceToggleCommand(MI_ShiftTrace),
editShiftToggleCommand(MI_EditShift), noShiftToggleCommand(MI_NoShift);
class TResetShiftTraceCommand final : public MenuItemHandler {
public:
TResetShiftTraceCommand() : MenuItemHandler(MI_ResetShift) {}
void execute() override {
OnionSkinMask osm =
TApp::instance()->getCurrentOnionSkin()->getOnionSkinMask();
osm.setShiftTraceGhostCenter(0, TPointD());
osm.setShiftTraceGhostCenter(1, TPointD());
osm.setShiftTraceGhostAff(0, TAffine());
osm.setShiftTraceGhostAff(1, TAffine());
TApp::instance()->getCurrentOnionSkin()->setOnionSkinMask(osm);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool) tool->reset();
}
} resetShiftTraceCommand;
//-----------------------------------------------------------------------------
// Following commands (VB_***) are registered for command bar buttons.
// They are separatd from the original visalization commands
// so that they will not break a logic of ShortcutZoomer.
class TViewResetCommand final : public MenuItemHandler {
public:
TViewResetCommand() : MenuItemHandler(VB_ViewReset) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->resetSceneViewer();
}
} viewResetCommand;
class TZoomResetCommand final : public MenuItemHandler {
public:
TZoomResetCommand() : MenuItemHandler(VB_ZoomReset) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->resetZoom();
}
} zoomResetCommand;
class TZoomFitCommand final : public MenuItemHandler {
public:
TZoomFitCommand() : MenuItemHandler(VB_ZoomFit) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->fitToCamera();
}
} zoomFitCommand;
class TActualPixelSizeCommand final : public MenuItemHandler {
public:
TActualPixelSizeCommand() : MenuItemHandler(VB_ActualPixelSize) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->setActualPixelSize();
}
} actualPixelSizeCommand;
class TFlipViewerXCommand final : public MenuItemHandler {
public:
TFlipViewerXCommand() : MenuItemHandler(VB_FlipX) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->flipX();
}
} flipViewerXCommand;
class TFlipViewerYCommand final : public MenuItemHandler {
public:
TFlipViewerYCommand() : MenuItemHandler(VB_FlipY) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->flipY();
}
} flipViewerYCommand;
class TRotateResetCommand final : public MenuItemHandler {
public:
TRotateResetCommand() : MenuItemHandler(VB_RotateReset) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->resetRotation();
}
} rotateResetCommand;
class TPositionResetCommand final : public MenuItemHandler {
public:
TPositionResetCommand() : MenuItemHandler(VB_PositionReset) {}
void execute() override {
if (TApp::instance()->getActiveViewer())
TApp::instance()->getActiveViewer()->resetPosition();
}
} positionResetCommand;
class TVectorGuidedDrawingToggleCommand final : public MenuItemHandler {
public:
TVectorGuidedDrawingToggleCommand()
: MenuItemHandler(MI_VectorGuidedDrawing) {}
void execute() override {
CommandManager *cm = CommandManager::instance();
QAction *action = cm->getAction(MI_VectorGuidedDrawing);
Preferences::instance()->setValue(guidedDrawingType,
action->isChecked() ? 1 : 0);
TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
TApp::instance()->getCurrentScene()->notifyPreferenceChanged(
"GuidedDrawingFrame");
}
bool isChecked(CommandId id) const {
QAction *action = CommandManager::instance()->getAction(id);
return action != 0 && action->isChecked();
}
} vectorGuidedDrawingToggleCommand;
class TSelectGuideStrokeResetCommand final : public MenuItemHandler {
public:
TSelectGuideStrokeResetCommand()
: MenuItemHandler(MI_SelectGuideStrokeReset) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->getViewer()->setGuidedStrokePickerMode(0);
tool->getViewer()->setGuidedBackStroke(-1);
tool->getViewer()->setGuidedFrontStroke(-1);
tool->getViewer()->invalidateAll();
}
} SelectGuideStrokeResetCommand;
class TSelectGuideStrokeNextCommand final : public MenuItemHandler {
public:
TSelectGuideStrokeNextCommand() : MenuItemHandler(MI_SelectNextGuideStroke) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->getViewer()->setGuidedStrokePickerMode(1);
}
} selectGuideStrokeNextCommand;
class TSelectGuideStrokePrevCommand final : public MenuItemHandler {
public:
TSelectGuideStrokePrevCommand() : MenuItemHandler(MI_SelectPrevGuideStroke) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->getViewer()->setGuidedStrokePickerMode(-1);
}
} selectGuideStrokePrevCommand;
class TSelectBothGuideStrokesCommand final : public MenuItemHandler {
public:
TSelectBothGuideStrokesCommand()
: MenuItemHandler(MI_SelectBothGuideStrokes) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->getViewer()->setGuidedStrokePickerMode(-2);
}
} selectBothGuideStrokesCommand;
class TTweenGuideStrokesCommand final : public MenuItemHandler {
public:
TTweenGuideStrokesCommand() : MenuItemHandler(MI_TweenGuideStrokes) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->tweenSelectedGuideStrokes();
}
} tweenGuideStrokesCommand;
class TTweenGuideStrokeToSelectedCommand final : public MenuItemHandler {
public:
TTweenGuideStrokeToSelectedCommand()
: MenuItemHandler(MI_TweenGuideStrokeToSelected) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->tweenGuideStrokeToSelected();
}
} tweenGuideStrokeToSelectedCommand;
class TSelectGuidesAndTweenCommand final : public MenuItemHandler {
public:
TSelectGuidesAndTweenCommand()
: MenuItemHandler(MI_SelectGuidesAndTweenMode) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->getViewer()->setGuidedStrokePickerMode(-3);
}
} selectGuidesAndTweenCommand;
class TFlipNextStrokeDirectionCommand final : public MenuItemHandler {
public:
TFlipNextStrokeDirectionCommand() : MenuItemHandler(MI_FlipNextGuideStroke) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->flipGuideStrokeDirection(1);
}
} flipNextStrokeDirectionCommand;
class TFlipPrevStrokeDirectionCommand final : public MenuItemHandler {
public:
TFlipPrevStrokeDirectionCommand() : MenuItemHandler(MI_FlipPrevGuideStroke) {}
void execute() override {
TVectorImageP vi = (TVectorImageP)TTool::getImage(false);
if (!vi) return;
Preferences *pref = Preferences::instance();
if (!pref->isOnionSkinEnabled() || (pref->getGuidedDrawingType() != 1 &&
pref->getGuidedDrawingType() != 2))
return;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (!tool) return;
tool->flipGuideStrokeDirection(-1);
}
} flipPrevStrokeDirectionCommand;
//=============================================================================
// SceneViewer
//-----------------------------------------------------------------------------
SceneViewer::SceneViewer(ImageUtils::FullScreenWidget *parent)
: GLWidgetForHighDpi(parent)
, m_pressure(0)
, m_lastMousePos(0, 0)
, m_mouseButton(Qt::NoButton)
, m_foregroundDrawing(false)
, m_tabletEvent(false)
, m_tabletMove(false)
, m_buttonClicked(false)
, m_referenceMode(NORMAL_REFERENCE)
, m_previewMode(NO_PREVIEW)
, m_isMouseEntered(false)
, m_forceGlFlush(true)
, m_freezedStatus(NO_FREEZED)
, m_viewGrabImage(0)
, m_FPS(0)
, m_hRuler(0)
, m_vRuler(0)
, m_viewMode(SCENE_VIEWMODE)
, m_pos(0, 0)
, m_pan3D(TPointD(0, 0))
, m_zoomScale3D(0.1)
, m_theta3D(20)
, m_phi3D(30)
, m_dpiScale(TPointD(1, 1))
, m_compareSettings()
, m_minZ(0)
, m_tableDLId(-1)
, m_groupIndexToBeEntered(-1)
, m_pixelSize(1)
, m_eraserPointerOn(false)
, m_backupTool("")
, m_clipRect()
, m_isPicking(false)
, m_current3DDevice(NONE)
, m_sideRasterPos()
, m_topRasterPos()
, m_toolDisableReason("")
, m_editPreviewSubCamera(false)
, m_locator(NULL)
, m_isLocator(false)
, m_isBusyOnTabletMove(false)
, m_mousePanning(0)
, m_mouseZooming(0)
, m_mouseRotating(0)
, m_keyAction(0) {
m_visualSettings.m_sceneProperties =
TApp::instance()->getCurrentScene()->getScene()->getProperties();
m_stopMotion = StopMotion::instance();
// Enables multiple key input.
setAttribute(Qt::WA_KeyCompression);
// Enables input methods for Asian languages.
setAttribute(Qt::WA_InputMethodEnabled);
setFocusPolicy(Qt::StrongFocus);
setAcceptDrops(true);
this->setMouseTracking(true);
// introduced from Qt 5.9
#if QT_VERSION >= 0x050900
this->setTabletTracking(true);
#endif
for (int i = 0; i < m_viewAff.size(); ++i) {
setViewMatrix(getNormalZoomScale(), i);
m_rotationAngle[i] = 0.0;
}
m_3DSideR = rasterFromQPixmap(svgToPixmap(":Resources/3Dside_r.svg"));
m_3DSideL = rasterFromQPixmap(svgToPixmap(":Resources/3Dside_l.svg"));
m_3DTop = rasterFromQPixmap(svgToPixmap(":Resources/3Dtop.svg"));
setAttribute(Qt::WA_AcceptTouchEvents);
grabGesture(Qt::SwipeGesture);
grabGesture(Qt::PanGesture);
grabGesture(Qt::PinchGesture);
setUpdateBehavior(QOpenGLWidget::PartialUpdate);
if (Preferences::instance()->isColorCalibrationEnabled())
m_lutCalibrator = new LutCalibrator();
}
//-----------------------------------------------------------------------------
void SceneViewer::setVisual(const ImagePainter::VisualSettings &settings) {
// m_visualSettings.m_blankColor = settings.m_blankColor;//for the blank
// frames, I don't have to repaint the viewer are using updateGl!
bool repaint = m_visualSettings.needRepaint(settings);
m_visualSettings = settings;
m_visualSettings.m_sceneProperties =
TApp::instance()->getCurrentScene()->getScene()->getProperties();
if (repaint) GLInvalidateAll();
}
//-----------------------------------------------------------------------------
SceneViewer::~SceneViewer() {
if (m_fbo) delete m_fbo;
int ret = l_contexts.erase(m_currentContext);
if (ret) TGLDisplayListsManager::instance()->releaseContext(m_currentContext);
emit viewerDestructing();
}
//-------------------------------------------------------------------------------
// Builds the view area, in camera reference
TRectD SceneViewer::getPreviewRect() const {
TApp *app = TApp::instance();
int row = app->getCurrentFrame()->getFrame();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
double cameraZ = xsh->getZ(cameraId, row);
TAffine cameraAff =
xsh->getPlacement(cameraId, row) * TScale((1000 + cameraZ) / 1000);
TDimensionD cameraSize =
app->getCurrentScene()->getScene()->getCurrentCamera()->getSize();
TDimension cameraRes =
app->getCurrentScene()->getScene()->getCurrentCamera()->getRes();
TScale cameraScale(Stage::inch * cameraSize.lx / cameraRes.lx,
Stage::inch * cameraSize.ly / cameraRes.ly);
TRectD viewRect(-width() * 0.5, -height() * 0.5, width() * 0.5,
height() * 0.5);
return (getViewMatrix() * cameraAff * cameraScale).inv() * viewRect;
}
//-------------------------------------------------------------------------------
void SceneViewer::onRenderStarted(int frame) { emit previewStatusChanged(); }
//-------------------------------------------------------------------------------
void SceneViewer::onRenderCompleted(int frame) {
invalidateAll();
emit previewStatusChanged();
}
//-------------------------------------------------------------------------------
void SceneViewer::onPreviewUpdate() {
update();
emit previewStatusChanged();
}
//-----------------------------------------------------------------------------
void SceneViewer::setReferenceMode(int referenceMode) {
if (m_referenceMode == referenceMode) return;
TApp *app = TApp::instance();
if (app->getCurrentFrame()->isEditingLevel())
app->getCurrentFrame()->setFrame(app->getCurrentFrame()->getFrame());
if (m_freezedStatus != NO_FREEZED) {
freeze(false);
emit freezeStateChanged(false);
}
m_referenceMode = referenceMode;
invalidateAll();
emit onZoomChanged();
}
//-------------------------------------------------------------------------------
void SceneViewer::freeze(bool on) {
if (!on) {
m_viewGrabImage = TRaster32P();
m_freezedStatus = NO_FREEZED;
} else {
setCursor(Qt::ForbiddenCursor);
m_freezedStatus = UPDATE_FREEZED;
}
GLInvalidateAll();
}
//-------------------------------------------------------------------------------
void SceneViewer::enablePreview(int previewMode) {
if (m_previewMode == previewMode) return;
TApp *app = TApp::instance();
if (app->getCurrentFrame()->isEditingLevel() && previewMode != NO_PREVIEW)
app->getCurrentFrame()->setFrame(app->getCurrentFrame()->getFrame());
if (m_freezedStatus != NO_FREEZED) {
freeze(false);
emit freezeStateChanged(false);
}
if (m_previewMode != NO_PREVIEW)
Previewer::instance(m_previewMode == SUBCAMERA_PREVIEW)
->removeListener(this);
// Schedule as a listener to Previewer.
if (previewMode != NO_PREVIEW) {
Previewer *previewer =
Previewer::instance(previewMode == SUBCAMERA_PREVIEW);
previewer->addListener(this);
previewer->update();
}
m_previewMode = previewMode;
GLInvalidateAll();
// for updating the title bar
emit previewToggled();
}
//-----------------------------------------------------------------------------
TPointD SceneViewer::winToWorld(const QPointF &pos) const {
// coordinate window (origine in alto a sinistra) -> coordinate colonna
// (origine al centro dell'immagine)
TPointD pp(pos.x() - (double)width() / 2.0,
-pos.y() + (double)height() / 2.0);
if (is3DView()) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
double z = xsh->getStageObject(cameraId)->getZ(
TApp::instance()->getCurrentFrame()->getFrame());
TPointD p(pp.x - m_pan3D.x, pp.y - m_pan3D.y);
p = p * (1 / m_zoomScale3D);
double theta = m_theta3D * M_PI_180;
double phi = m_phi3D * M_PI_180;
double cs_phi = cos(phi);
double sn_phi = sin(phi);
double cs_theta = cos(theta);
double sn_theta = sin(theta);
TPointD a(cs_phi, sn_theta * sn_phi); // proiezione di (1,0,0)
TPointD b(0, cs_theta); // proiezione di (0,1,0)
TPointD c(sn_phi, -sn_theta * cs_phi); // proiezione di (0,0,1)
TPointD aa = rotate90(a);
TPointD bb = rotate90(b);
double abb = a * bb;
double baa = b * aa;
if (fabs(abb) > 0.001 && fabs(baa) > 0.001) {
p -= c * z;
TPointD g((p * bb) / (a * bb), (p * aa) / (b * aa));
return TAffine() * g;
} else
return TAffine() * TPointD(0, 0);
}
return getViewMatrix().inv() * pp;
}
//-----------------------------------------------------------------------------
TPointD SceneViewer::winToWorld(const TPointD &winPos) const {
return winToWorld(QPointF(winPos.x, height() - winPos.y));
}
//-----------------------------------------------------------------------------
TPointD SceneViewer::worldToPos(const TPointD &worldPos) const {
TPointD p = getViewMatrix() * worldPos;
return TPointD(width() / 2 + p.x, height() / 2 + p.y);
}
//-----------------------------------------------------------------------------
void SceneViewer::showEvent(QShowEvent *) {
m_visualSettings.m_sceneProperties =
TApp::instance()->getCurrentScene()->getScene()->getProperties();
// Se il viewer e' show e il preview e' attivo aggiungo il listner al preview
if (m_previewMode != NO_PREVIEW)
Previewer::instance(m_previewMode == SUBCAMERA_PREVIEW)->addListener(this);
TApp *app = TApp::instance();
TSceneHandle *sceneHandle = app->getCurrentScene();
bool ret = connect(sceneHandle, SIGNAL(sceneSwitched()), this,
SLOT(resetSceneViewer()));
ret = ret && connect(sceneHandle, SIGNAL(sceneChanged()), this,
SLOT(onSceneChanged()));
TFrameHandle *frameHandle = app->getCurrentFrame();
ret = ret && connect(frameHandle, SIGNAL(frameSwitched()), this,
SLOT(onFrameSwitched()));
TPaletteHandle *paletteHandle =
app->getPaletteController()->getCurrentLevelPalette();
ret = ret && connect(paletteHandle, SIGNAL(colorStyleChanged(bool)), this,
SLOT(update()));
ret = ret && connect(app->getCurrentObject(), SIGNAL(objectSwitched()), this,
SLOT(onObjectSwitched()));
ret = ret && connect(app->getCurrentObject(), SIGNAL(objectChanged(bool)),
this, SLOT(update()));
ret =
ret && connect(app->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()),
this, SLOT(onOnionSkinMaskChanged()));
ret = ret && connect(app->getCurrentLevel(), SIGNAL(xshLevelChanged()), this,
SLOT(update()));
ret = ret && connect(app->getCurrentLevel(), SIGNAL(xshCanvasSizeChanged()),
this, SLOT(update()));
// when level is switched, update m_dpiScale in order to show white background
// for Ink&Paint work properly
ret = ret &&
connect(app->getCurrentLevel(), SIGNAL(xshLevelSwitched(TXshLevel *)),
this, SLOT(onLevelSwitched()));
ret = ret && connect(app->getCurrentXsheet(), SIGNAL(xsheetChanged()), this,
SLOT(onXsheetChanged()));
ret = ret && connect(app->getCurrentXsheet(), SIGNAL(xsheetSwitched()), this,
SLOT(update()));
// update tooltip when tool options are changed
ret = ret && connect(app->getCurrentTool(), SIGNAL(toolChanged()), this,
SLOT(onToolChanged()));
ret = ret && connect(app->getCurrentTool(), SIGNAL(toolCursorTypeChanged()),
this, SLOT(onToolChanged()));
ret = ret &&
connect(app, SIGNAL(tabletLeft()), this, SLOT(resetTabletStatus()));
if (m_stopMotion) {
ret = ret && connect(m_stopMotion, SIGNAL(newLiveViewImageReady()), this,
SLOT(onNewStopMotionImageReady()));
ret = ret && connect(m_stopMotion, SIGNAL(liveViewStopped()), this,
SLOT(onStopMotionLiveViewStopped()));
}
assert(ret);
if (m_hRuler && m_vRuler) {
if (!viewRulerToggle.getStatus()) {
m_hRuler->hide();
m_vRuler->hide();
} else {
m_hRuler->show();
m_vRuler->show();
}
}
if (m_shownOnce == false) {
fitToCamera();
m_shownOnce = true;
}
TApp::instance()->setActiveViewer(this);
onPreferenceChanged("ColorCalibration");
update();
}
//-----------------------------------------------------------------------------
void SceneViewer::hideEvent(QHideEvent *) {
// Se il viewer e' hide e il preview e' attivo rimuovo il listner dal preview
if (m_previewMode != NO_PREVIEW)
Previewer::instance(m_previewMode == SUBCAMERA_PREVIEW)
->removeListener(this);
TApp *app = TApp::instance();
TSceneHandle *sceneHandle = app->getCurrentScene();
if (sceneHandle) sceneHandle->disconnect(this);
TFrameHandle *frameHandle = app->getCurrentFrame();
if (frameHandle) frameHandle->disconnect(this);
TPaletteHandle *paletteHandle =
app->getPaletteController()->getCurrentLevelPalette();
if (paletteHandle) paletteHandle->disconnect(this);
TObjectHandle *objectHandle = app->getCurrentObject();
if (objectHandle) objectHandle->disconnect(this);
TOnionSkinMaskHandle *onionHandle = app->getCurrentOnionSkin();
if (onionHandle) onionHandle->disconnect(this);
TXshLevelHandle *levelHandle = app->getCurrentLevel();
if (levelHandle) levelHandle->disconnect(this);
TXsheetHandle *xsheetHandle = app->getCurrentXsheet();
if (xsheetHandle) xsheetHandle->disconnect(this);
ToolHandle *toolHandle = app->getCurrentTool();
if (toolHandle) toolHandle->disconnect(this);
disconnect(app, SIGNAL(tabletLeft()), this, SLOT(resetTabletStatus()));
if (m_stopMotion) {
disconnect(m_stopMotion, SIGNAL(newImageReady()), this,
SLOT(onNewStopMotionImageReady()));
disconnect(m_stopMotion, SIGNAL(liveViewStopped()), this,
SLOT(onStopMotionLiveViewStopped()));
}
// hide locator
if (m_locator && m_locator->isVisible()) m_locator->hide();
}
int SceneViewer::getVGuideCount() {
if (viewGuideToggle.getStatus())
return m_vRuler->getGuideCount();
else
return 0;
}
int SceneViewer::getHGuideCount() {
if (viewGuideToggle.getStatus())
return m_hRuler->getGuideCount();
else
return 0;
}
double SceneViewer::getVGuide(int index) { return m_vRuler->getGuide(index); }
double SceneViewer::getHGuide(int index) { return m_hRuler->getGuide(index); }
//-----------------------------------------------------------------------------
void SceneViewer::onNewStopMotionImageReady() {
if (m_stopMotion->m_hasLineUpImage) {
// if (m_hasStopMotionLineUpImage) delete m_stopMotionLineUpImage;
m_stopMotionLineUpImage =
(TRasterImageP)m_stopMotion->m_lineUpImage->clone();
m_stopMotionLineUpImage->setDpi(m_stopMotion->m_liveViewDpi.x,
m_stopMotion->m_liveViewDpi.y);
m_hasStopMotionLineUpImage = true;
}
if (m_stopMotion->m_hasLiveViewImage) {
// if (m_hasStopMotionImage) delete m_stopMotionImage;
m_stopMotionImage = m_stopMotion->m_liveViewImage->clone();
m_stopMotionImage->setDpi(m_stopMotion->m_liveViewDpi.x,
m_stopMotion->m_liveViewDpi.y);
m_hasStopMotionImage = true;
if (m_stopMotion->m_canon->m_pickLiveViewZoom) {
setToolCursor(this, ToolCursor::ZoomCursor);
}
onSceneChanged();
}
}
//-----------------------------------------------------------------------------
void SceneViewer::onStopMotionLiveViewStopped() {
m_hasStopMotionImage = false;
m_hasStopMotionLineUpImage = false;
onSceneChanged();
}
//-----------------------------------------------------------------------------
void SceneViewer::onPreferenceChanged(const QString &prefName) {
if (prefName == "ColorCalibration") {
if (Preferences::instance()->isColorCalibrationEnabled()) {
// if the window is so shriked that the gl widget is empty,
// showEvent can be called before creating the context.
if (!context()) return;
makeCurrent();
if (!m_lutCalibrator)
m_lutCalibrator = new LutCalibrator();
else
m_lutCalibrator->cleanup();
m_lutCalibrator->initialize();
connect(context(), SIGNAL(aboutToBeDestroyed()), this,
SLOT(onContextAboutToBeDestroyed()));
if (m_lutCalibrator->isValid() && !m_fbo)
m_fbo = new QOpenGLFramebufferObject(width(), height());
doneCurrent();
}
update();
}
}
//-----------------------------------------------------------------------------
void SceneViewer::initializeGL() {
initializeOpenGLFunctions();
registerContext();
// to be computed once through the software
if (m_lutCalibrator && !m_lutCalibrator->isInitialized()) {
m_lutCalibrator->initialize();
connect(context(), SIGNAL(aboutToBeDestroyed()), this,
SLOT(onContextAboutToBeDestroyed()));
}
// glClearColor(1.0,1.0,1.0,1);
glClear(GL_COLOR_BUFFER_BIT);
if (m_firstInitialized)
m_firstInitialized = false;
else {
resizeGL(width(), height());
update();
}
// re-computing the display list for the table
m_tableDLId = -1;
}
//-----------------------------------------------------------------------------
void SceneViewer::resizeGL(int w, int h) {
w *= getDevPixRatio();
h *= getDevPixRatio();
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, w, 0, h, -4000, 4000);
m_projectionMatrix.setToIdentity();
m_projectionMatrix.ortho(0, w, 0, h, -4000, 4000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.375, 0.375, 0.0);
// make the center of the viewer = origin
glTranslated(w * 0.5, h * 0.5, 0);
if (m_freezedStatus == NORMAL_FREEZED) m_freezedStatus = UPDATE_FREEZED;
if (m_previewMode != NO_PREVIEW) requestTimedRefresh();
// remake fbo with new size
if (m_lutCalibrator && m_lutCalibrator->isValid()) {
if (m_fbo) delete m_fbo;
m_fbo = new QOpenGLFramebufferObject(w, h);
}
// for updating the navigator in levelstrip
emit refreshNavi();
}
//-----------------------------------------------------------------------------
void SceneViewer::drawBuildVars() {
TApp *app = TApp::instance();
int frame = app->getCurrentFrame()->getFrame();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
// Camera affine
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
TStageObject *camera = xsh->getStageObject(cameraId);
TAffine cameraPlacement = camera->getPlacement(frame);
double cameraZ = camera->getZ(frame);
m_drawCameraAff =
getViewMatrix() * cameraPlacement * TScale((1000 + cameraZ) / 1000);
// Table affine
TStageObject *table = xsh->getStageObject(TStageObjectId::TableId);
TAffine tablePlacement = table->getPlacement(frame);
double tableZ = table->getZ(frame);
TAffine placement;
m_drawIsTableVisible = TStageObject::perspective(
placement, cameraPlacement, cameraZ, tablePlacement, tableZ, 0);
m_drawTableAff = getViewMatrix() * tablePlacement;
// Camera test check
m_drawCameraTest = CameraTestCheck::instance()->isEnabled();
if (m_previewMode == NO_PREVIEW) {
m_drawEditingLevel = app->getCurrentFrame()->isEditingLevel();
m_viewMode = m_drawEditingLevel ? LEVEL_VIEWMODE : SCENE_VIEWMODE;
m_draw3DMode = is3DView() && (m_previewMode != SUBCAMERA_PREVIEW);
} else {
m_drawEditingLevel = false;
m_viewMode = app->getCurrentFrame()->isEditingLevel();
m_draw3DMode = false;
}
// Clip rect
if (!m_clipRect.isEmpty() && !m_draw3DMode) {
m_actualClipRect = getActualClipRect(getViewMatrix());
m_actualClipRect += TPoint(width() * 0.5, height() * 0.5);
}
TTool *tool = app->getCurrentTool()->getTool();
if (tool && !m_isLocator) tool->setViewer(this);
}
//-----------------------------------------------------------------------------
void SceneViewer::drawEnableScissor() {
if (!m_clipRect.isEmpty() && !m_draw3DMode) {
glEnable(GL_SCISSOR_TEST);
glScissor(m_actualClipRect.x0, m_actualClipRect.y0,
m_actualClipRect.getLx(), m_actualClipRect.getLy());
}
}
//-----------------------------------------------------------------------------
void SceneViewer::drawDisableScissor() {
if (!m_clipRect.isEmpty() && !m_draw3DMode) {
glDisable(GL_SCISSOR_TEST);
}
// clear the clipping rect
m_clipRect.empty();
}
//-----------------------------------------------------------------------------
void SceneViewer::drawBackground() {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
if (m_visualSettings.m_colorMask == 0) {
TPixel32 bgColor;
if (isPreviewEnabled()) {
if (Preferences::instance()->getUseThemeViewerColors()) {
QColor qtBgColor = getPreviewBGColor();
bgColor =
TPixel32(qtBgColor.red(), qtBgColor.green(), qtBgColor.blue());
} else
bgColor = Preferences::instance()->getPreviewBgColor();
} else {
if (Preferences::instance()->getUseThemeViewerColors()) {
QColor qtBgColor = getBGColor();
bgColor =
TPixel32(qtBgColor.red(), qtBgColor.green(), qtBgColor.blue());
} else
bgColor = Preferences::instance()->getViewerBgColor();
}
glClearColor(bgColor.r / 255.0f, bgColor.g / 255.0f, bgColor.b / 255.0f,
1.0);
} else
glClearColor(0, 0, 0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
if (glGetError() == GL_INVALID_FRAMEBUFFER_OPERATION) {
/* 起動時一回目になぜか GL_FRAMEBUFFER_COMPLETE なのに invalid operation
* が出る */
GLenum status = 0;
#ifdef _WIN32
PROC proc = wglGetProcAddress("glCheckFramebufferStatusEXT");
if (proc != nullptr)
status = reinterpret_cast<PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC>(proc)(
GL_FRAMEBUFFER);
#else
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
#endif
printf("GL_INVALID_FRAMEBUFFER_OPERATION: framebuffer:%d\n", status);
}
}
static bool check_framebuffer_status() {
#ifdef _WIN32
PROC proc = wglGetProcAddress("glCheckFramebufferStatusEXT");
if (proc == nullptr) return true;
GLenum s = reinterpret_cast<PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC>(proc)(
GL_FRAMEBUFFER);
#else
GLenum s = glCheckFramebufferStatus(GL_FRAMEBUFFER);
#endif
if (s == GL_FRAMEBUFFER_UNDEFINED)
printf("Warning: FB undefined: %d\n", s);
else if (s == GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT)
printf("Warning: FB incomplete(attachment): %d\n", s);
else if (s == GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT)
printf("Warning: FB incomplete(missing attachment): %d\n", s);
else if (s == GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER)
printf("Warning: FB incomplete(draw buffer): %d\n", s);
else if (s == GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER)
printf("Warning: FB incomplete(read buffer): %d\n", s);
else if (s == GL_FRAMEBUFFER_UNSUPPORTED)
printf("Warning: FB unsupported: %d\n", s);
else if (s == GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE)
printf("Warning: FB incomplete(multi-sample): %d\n", s);
else if (s == GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS)
printf("Warning: FB incomplete(multi-sample): %d\n", s);
else if (s == GL_FRAMEBUFFER_COMPLETE)
;
else
printf("Warning: FB not complete(unknown cause): %d\n", s);
return s == GL_FRAMEBUFFER_COMPLETE;
}
//-----------------------------------------------------------------------------
void SceneViewer::drawCameraStand() {
GLint e = glGetError();
check_framebuffer_status();
assert(e == GL_NO_ERROR);
TXshSimpleLevel::m_rasterizePli = rasterizePliToggle.getStatus();
// clear
if (m_draw3DMode) {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
glClear(GL_DEPTH_BUFFER_BIT);
glPushMatrix();
mult3DMatrix();
} else
glDisable(GL_DEPTH_TEST);
assert(glGetError() == GL_NO_ERROR);
// draw table
if (!m_draw3DMode && viewTableToggle.getStatus() && m_drawIsTableVisible &&
m_visualSettings.m_colorMask == 0 && m_drawEditingLevel == false &&
!m_drawCameraTest) {
glPushMatrix();
tglMultMatrix(m_drawTableAff);
ViewerDraw::drawDisk(m_tableDLId);
glPopMatrix();
}
// draw colorcard (with camera BG color)
// Hide camera BG when level editing mode.
if (m_drawEditingLevel == false && viewClcToggle.getStatus() &&
!m_drawCameraTest) {
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
ViewerDraw::drawColorcard(m_visualSettings.m_colorMask);
glDisable(GL_BLEND);
glPopMatrix();
}
// Show white background when level editing mode.
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (m_drawEditingLevel && tool && tool->isEnabled()) {
if (!m_isLocator) tool->setViewer(this);
glPushMatrix();
if (m_referenceMode == CAMERA3D_REFERENCE) {
mult3DMatrix();
tglMultMatrix(tool->getMatrix());
} else {
tglMultMatrix(getViewMatrix() * tool->getMatrix());
}
glScaled(m_dpiScale.x, m_dpiScale.y, 1);
TImageP image = tool->getImage(false);
TToonzImageP ti = image;
TRasterImageP ri = image;
if (ti) {
TRect imgRect(0, 0, ti->getSize().lx - 1, ti->getSize().ly - 1);
TRectD bbox = ToonzImageUtils::convertRasterToWorld(imgRect, ti);
TPixel32 imgRectColor;
// draw black rectangle instead, if the BlackBG check is ON
if (ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg)
imgRectColor = TPixel::Black;
else
imgRectColor = Preferences::instance()->getLevelEditorBoxColor();
ToolUtils::fillRect(bbox * ti->getSubsampling(), imgRectColor);
} else if (ri) {
TRectD bbox = ri->getBBox();
bbox.x0 -= ri->getBBox().getLx() * 0.5;
bbox.x1 -= ri->getBBox().getLx() * 0.5;
bbox.y0 -= ri->getBBox().getLy() * 0.5;
bbox.y1 -= ri->getBBox().getLy() * 0.5;
TPixel32 imgRectColor;
// draw black rectangle instead, if the BlackBG check is ON
if (ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg)
imgRectColor = TPixel::Black;
else
imgRectColor = Preferences::instance()->getLevelEditorBoxColor();
ToolUtils::fillRect(bbox * ri->getSubsampling(), imgRectColor);
}
glPopMatrix();
}
// draw 3dframe
if (m_draw3DMode) {
glDepthFunc(GL_LEQUAL);
ViewerDraw::draw3DFrame(m_minZ, m_phi3D);
glDepthFunc(GL_ALWAYS);
}
// draw scene
assert(glGetError() == GL_NO_ERROR);
drawScene();
assert((glGetError()) == GL_NO_ERROR);
}
//-----------------------------------------------------------------------------
void SceneViewer::drawPreview() {
const double inch = Stage::inch;
TApp *app = TApp::instance();
int row = app->getCurrentFrame()->getFrame();
TCamera *currCamera = app->getCurrentScene()->getScene()->getCurrentCamera();
TDimensionD cameraSize = currCamera->getSize();
Previewer *previewer =
Previewer::instance(m_previewMode == SUBCAMERA_PREVIEW);
TRasterP ras =
previewer->getRaster(row, m_visualSettings.m_recomputeIfNeeded);
if (ras) {
TRectD previewStageRectD, cameraStageRectD = currCamera->getStageRect();
TRect subCameraRect(currCamera->getInterestRect());
if (m_previewMode == SUBCAMERA_PREVIEW && subCameraRect.getLx() > 0 &&
subCameraRect.getLy() > 0)
previewStageRectD = currCamera->getInterestStageRect();
else
previewStageRectD = cameraStageRectD;
TAffine rasterToStageRef(
previewStageRectD.getLx() / ras->getLx(), 0.0,
previewStageRectD.x0 + 0.5 * previewStageRectD.getLx(), 0.0,
previewStageRectD.getLy() / ras->getLy(),
previewStageRectD.y0 + 0.5 * previewStageRectD.getLy());
TDimension dim(width(), height());
TAffine finalAff = m_drawCameraAff * rasterToStageRef;
m_visualSettings.m_useTexture = !Preferences::instance()->useDrawPixel();
ImagePainter::paintImage(TRasterImageP(ras), ras->getSize(), dim, finalAff,
m_visualSettings, m_compareSettings, TRect());
}
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
TRectD frameRect(cameraSize);
frameRect.x1 *= inch;
frameRect.y1 *= inch;
frameRect -= 0.5 * (frameRect.getP00() + frameRect.getP11());
if (m_visualSettings.m_blankColor != TPixel::Transparent) {
tglColor(m_visualSettings.m_blankColor);
tglFillRect(frameRect);
}
if (!previewer->isFrameReady(row) ||
(app->getCurrentFrame()->isPlaying() && previewer->isBusy())) {
glColor3d(1, 0, 0);
tglDrawRect(frameRect);
tglDrawRect(frameRect.enlarge(5));
}
glPopMatrix();
}
//-----------------------------------------------------------------------------
void SceneViewer::drawOverlay() {
TApp *app = TApp::instance();
// draw camera mask
if (m_referenceMode == CAMERA_REFERENCE && !m_drawCameraTest) {
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
ViewerDraw::drawCameraMask(this);
glPopMatrix();
}
//// draw FieldGuide
// if (fieldGuideToggle.getStatus()) {
// glPushMatrix();
// tglMultMatrix(m_drawTableAff);
// ViewerDraw::drawFieldGuide();
// glPopMatrix();
//}
if (!m_drawCameraTest) {
// draw grid & guides
if (viewGuideToggle.getStatus() &&
((m_vRuler && m_vRuler->getGuideCount()) ||
(m_hRuler && m_hRuler->getGuideCount()))) {
glPushMatrix();
tglMultMatrix(getViewMatrix());
ViewerDraw::drawGridAndGuides(
this, (m_draw3DMode) ? m_zoomScale3D : m_viewAff[m_viewMode].det(),
m_vRuler, m_hRuler, false);
glPopMatrix();
}
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
TStageObjectId objId = app->getCurrentObject()->getObjectId();
bool isMotionPath =
(objId == xsh->getStageObjectTree()->getMotionPathViewerId() &&
app->getCurrentObject()->isSpline());
// draw camera
if (!isMotionPath && viewCameraToggle.getStatus() &&
m_drawEditingLevel == false) {
unsigned long f = 0;
if (m_referenceMode == CAMERA_REFERENCE)
f |= ViewerDraw::CAMERA_REFERENCE;
if (m_draw3DMode) f |= ViewerDraw::CAMERA_3D;
if (m_previewMode == SUBCAMERA_PREVIEW || m_editPreviewSubCamera)
f |= ViewerDraw::SUBCAMERA;
if (m_draw3DMode)
ViewerDraw::draw3DCamera(f, m_minZ, m_phi3D);
else {
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
m_pixelSize = sqrt(tglGetPixelSize2()) * getDevPixRatio();
ViewerDraw::drawCamera(f, m_pixelSize);
glPopMatrix();
}
}
if (fieldGuideToggle.getStatus()) {
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
ViewerDraw::drawCameraOverlays(this, m_pixelSize);
glPopMatrix();
glPushMatrix();
tglMultMatrix(m_drawTableAff);
if (ViewerDraw::getShowFieldGuide()) ViewerDraw::drawFieldGuide();
if (!m_draw3DMode) {
ViewerDraw::drawGridsAndOverlays(this, m_pixelSize);
}
glPopMatrix();
}
#ifdef WITH_CANON
if (m_stopMotion->m_liveViewStatus == StopMotion::LiveViewOpen &&
app->getCurrentFrame()->getFrame() ==
m_stopMotion->getXSheetFrameNumber() - 1) {
int x0, x1, y0, y1;
rect().getCoords(&x0, &y0, &x1, &y1);
x0 = (-(x1 / 2)) + 15;
y0 = ((y1 / 2)) - 15;
glColor3d(1.0, 0.0, 0.0);
tglDrawDisk(TPointD(x0, y0), 10);
}
// draw Stop Motion Zoom Box
if (m_stopMotion->m_liveViewStatus == 2 &&
m_stopMotion->m_canon->m_pickLiveViewZoom) {
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
m_pixelSize = sqrt(tglGetPixelSize2()) * getDevPixRatio();
TRect rect = m_stopMotion->m_canon->m_zoomRect;
glColor3d(1.0, 0.0, 0.0);
// border
glBegin(GL_LINE_STRIP);
glVertex2d(rect.x0, rect.y0);
glVertex2d(rect.x0, rect.y1 - m_pixelSize);
glVertex2d(rect.x1 - m_pixelSize, rect.y1 - m_pixelSize);
glVertex2d(rect.x1 - m_pixelSize, rect.y0);
glVertex2d(rect.x0, rect.y0);
glEnd();
glPopMatrix();
}
#endif
// safe area
if (safeAreaToggle.getStatus() && m_drawEditingLevel == false &&
!is3DView()) {
glPushMatrix();
tglMultMatrix(m_drawCameraAff);
ViewerDraw::drawSafeArea();
glPopMatrix();
}
// record fps (frame per second)
if (app->getCurrentFrame()->isPlaying())
m_FPS = getActualFrameRate();
else
m_FPS = 0;
assert(glGetError() == GL_NO_ERROR);
} //! cameraTest
// draw 3d Top/Side Buttons
if (m_draw3DMode && !m_isPicking) {
tglColor(TPixel32::Black);
GLdouble modelView3D[16];
GLdouble projection3D[16];
GLint viewport3D[4];
glGetDoublev(GL_MODELVIEW_MATRIX, modelView3D);
glGetDoublev(GL_PROJECTION_MATRIX, projection3D);
glGetIntegerv(GL_VIEWPORT, viewport3D);
if (m_phi3D > 0) {
T3DPointD topRasterPos3D = computeNew3DPosition(
T3DPointD(500, 500, 1000), TPointD(-10, -10), m_topRasterPos,
modelView3D, projection3D, viewport3D, getDevPixRatio());
glRasterPos3f(topRasterPos3D.x, topRasterPos3D.y, topRasterPos3D.z);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glDrawPixels(m_3DTop->getWrap(), m_3DTop->getLy(), TGL_FMT, TGL_TYPE,
m_3DTop->getRawData());
T3DPointD sideRasterPos3D = computeNew3DPosition(
T3DPointD(-500, -500, 1000), TPointD(-10, -10), m_sideRasterPos,
modelView3D, projection3D, viewport3D, getDevPixRatio());
glRasterPos3f(sideRasterPos3D.x, sideRasterPos3D.y, sideRasterPos3D.z);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glDrawPixels(m_3DSideR->getWrap(), m_3DSideR->getLy(), TGL_FMT, TGL_TYPE,
m_3DSideR->getRawData());
} else {
T3DPointD topRasterPos3D = computeNew3DPosition(
T3DPointD(-500, 500, 1000), TPointD(-10, -10), m_topRasterPos,
modelView3D, projection3D, viewport3D, getDevPixRatio());
glRasterPos3f(topRasterPos3D.x, topRasterPos3D.y, topRasterPos3D.z);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glDrawPixels(m_3DTop->getWrap(), m_3DTop->getLy(), TGL_FMT, TGL_TYPE,
m_3DTop->getRawData());
T3DPointD sideRasterPos3D = computeNew3DPosition(
T3DPointD(500, -500, 1000), TPointD(-10, -10), m_sideRasterPos,
modelView3D, projection3D, viewport3D, getDevPixRatio());
glRasterPos3f(sideRasterPos3D.x, sideRasterPos3D.y, sideRasterPos3D.z);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glDrawPixels(m_3DSideL->getWrap(), m_3DSideL->getLy(), TGL_FMT, TGL_TYPE,
m_3DSideL->getRawData());
}
}
if (m_draw3DMode) {
glDisable(GL_DEPTH_TEST);
glPopMatrix();
assert(glGetError() == GL_NO_ERROR);
}
// draw tool gadgets
TTool *tool = app->getCurrentTool()->getTool();
TXshSimpleLevel *sl = app->getCurrentLevel()->getSimpleLevel();
if (sl) {
std::vector<TPointD> assistantPoints =
sl->getProperties()->getVanishingPoints();
if (!m_draw3DMode && assistantPoints.size() > 0) {
if (tool->getToolType() & TTool::LevelTool &&
!app->getCurrentObject()->isSpline() &&
(tool->getName() == "T_Brush" || tool->getName() == "T_Geometric")) {
glPushMatrix();
tglMultMatrix(getViewMatrix() * tool->getMatrix());
glScaled(m_dpiScale.x, m_dpiScale.y, 1);
ViewerDraw::drawPerspectiveGuides(this, m_viewAff[m_viewMode].det(),
assistantPoints);
glPopMatrix();
}
}
}
// Call tool->draw() even if the level is read only (i.e. to show hooks)
if (tool && (tool->isEnabled() || (sl && sl->isReadOnly()))) {
// tool->setViewer(this); // Moved at
// drawBuildVars(), before drawing anything
glPushMatrix();
if (m_draw3DMode) {
mult3DMatrix();
tglMultMatrix(tool->getMatrix());
} else
tglMultMatrix(getViewMatrix() * tool->getMatrix());
if (tool->getToolType() & TTool::LevelTool &&
!app->getCurrentObject()->isSpline())
glScaled(m_dpiScale.x, m_dpiScale.y, 1);
m_pixelSize = sqrt(tglGetPixelSize2()) * getDevPixRatio();
tool->draw();
glPopMatrix();
// Used (only in the T_RGBPicker tool) to notify and set the currentColor
// outside the draw() methods:
// using special style there was a conflict between the draw() methods of
// the tool
// and the generation of the icon inside the style editor (makeIcon()) which
// use
// another glContext
if (tool->getName() == "T_RGBPicker") tool->onImageChanged();
// draw cross at the center of the locator window
if (m_isLocator) {
glColor3d(1.0, 0.0, 0.0);
tglDrawSegment(TPointD(-4, 0), TPointD(5, 0));
tglDrawSegment(TPointD(0, -4), TPointD(0, 5));
}
}
}
//-----------------------------------------------------------------------------
void SceneViewer::drawViewerIndicators() {
if (!Preferences::instance()->isViewerIndicatorEnabled()) return;
QStringList checkTexts;
// Frozen Viewer Indicator
if (m_freezedStatus) checkTexts.append(tr("FROZEN"));
// Motion Path Indicator
TApp *app = TApp::instance();
TStageObjectId objId = app->getCurrentObject()->getObjectId();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
if (objId == xsh->getStageObjectTree()->getMotionPathViewerId() &&
app->getCurrentObject()->isSpline())
checkTexts.append(tr("Motion Path Selected"));
// Check Indicators (disabled in Preview mode)
ToonzCheck *tc = ToonzCheck::instance();
int mask = tc->getChecks();
if (!m_previewMode && mask) {
if (mask & ToonzCheck::eTransparency)
checkTexts.append(tr("Transparency Check"));
if (mask & ToonzCheck::eInk) checkTexts.append(tr("Ink Check"));
if (mask & ToonzCheck::eInk1) checkTexts.append(tr("Ink#1 Check"));
if (mask & ToonzCheck::ePaint) checkTexts.append(tr("Paint Check"));
if (mask & ToonzCheck::eInksOnly) checkTexts.append(tr("Inks Only Check"));
if (mask & ToonzCheck::eBlackBg) checkTexts.append(tr("Black BG Check"));
if (mask & ToonzCheck::eGap) checkTexts.append(tr("Fill Check"));
if (mask & ToonzCheck::eAutoclose) checkTexts.append(tr("Gap Check"));
}
if (!checkTexts.size()) return;
int x0, x1, y0, y1;
rect().getCoords(&x0, &y0, &x1, &y1);
x0 = (-(x1 / 2)) + 15;
y0 = ((y1 / 2)) - 25;
glPushMatrix();
glScaled(2, 2, 2);
glColor3d(1.0, 0.0, 0.0);
for (int i = 0; i < checkTexts.size(); i++) {
int y = (y0 / 2) - (i * 10);
tglDrawText(TPointD((x0 / 2), y), checkTexts[i].toStdString());
}
glPopMatrix();
}
//-----------------------------------------------------------------------------
static void drawFpsGraph(int t0, int t1) {
glDisable(GL_BLEND);
static std::deque<std::pair<int, int>> times;
times.push_back(std::make_pair(t0, t1));
while (times.size() > 200) times.pop_front();
double x0 = 10, y0 = 10;
double x1 = x0 + 200;
double y1 = y0 + 150;
glPushMatrix();
glLoadIdentity();
glColor3d(0, 0, 0);
glRectd(x0, y0, x1, y1);
glColor3d(0, 0.5, 1);
glBegin(GL_LINE_STRIP);
glVertex2d(x0, y0);
glVertex2d(x1, y0);
glVertex2d(x1, y1);
glVertex2d(x0, y1);
glVertex2d(x0, y0);
glEnd();
glColor3d(0.5, 0.5, 0.5);
glBegin(GL_LINES);
for (int y = y0 + 5; y < y1; y += 20) {
glVertex2d(x0, y);
glVertex2d(x1, y);
}
for (int i = 0; i < (int)times.size(); i++) {
double x = x1 - i;
glColor3d(1, 0, 0);
glVertex2d(x, y0);
glVertex2d(x, y0 + 5 + times[i].first / 5);
glColor3d(0, 1, 0);
glVertex2d(x, y0 + 5 + times[i].first / 5);
glVertex2d(x, y0 + 5 + times[i].second / 5);
}
glEnd();
glPopMatrix();
}
//-----------------------------------------------------------------------------
//#define FPS_HISTOGRAM
void SceneViewer::paintGL() {
#ifdef _DEBUG
if (!check_framebuffer_status()) {
/* QGLWidget の widget 生成/削除のタイミングで(platform によって?)
* GL_FRAMEBUFFER_UNDEFINED の状態で paintGL() が呼ばれてしまうようだ */
return;
}
#endif
#ifdef MACOSX
// following lines are necessary to solve a problem on iMac20
// It seems that for some errors in the openGl implementation, buffers are not
// set correctly.
if (m_isMouseEntered && m_forceGlFlush) {
m_isMouseEntered = false;
m_forceGlFlush = false;
glDrawBuffer(GL_FRONT);
glFlush();
glDrawBuffer(GL_BACK);
}
#endif
#ifdef FPS_HISTOGRAM
QTime time;
time.start();
#endif
if (!m_isPicking && m_lutCalibrator && m_lutCalibrator->isValid())
m_fbo->bind();
if (m_hRuler && m_vRuler) {
if (!viewRulerToggle.getStatus() &&
(m_hRuler->isVisible() || m_vRuler->isVisible())) {
m_hRuler->hide();
m_vRuler->hide();
} else if (viewRulerToggle.getStatus() &&
(!m_hRuler->isVisible() || !m_vRuler->isVisible())) {
m_hRuler->show();
m_vRuler->show();
}
}
// Il freezed e' attivo ed e' in stato "normale": mostro l'immagine grabbata.
if (m_freezedStatus == NORMAL_FREEZED) {
assert(!!m_viewGrabImage);
m_viewGrabImage->lock();
glPushMatrix();
glLoadIdentity();
glRasterPos2d(0, 0);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glDrawPixels(m_viewGrabImage->getLx(), m_viewGrabImage->getLy(), TGL_FMT,
TGL_TYPE, m_viewGrabImage->getRawData());
glPopMatrix();
m_viewGrabImage->unlock();
if (!m_isPicking && m_lutCalibrator && m_lutCalibrator->isValid())
m_lutCalibrator->onEndDraw(m_fbo);
drawViewerIndicators();
return;
}
drawBuildVars();
// This seems not to be necessary for now.
// copyFrontBufferToBackBuffer();
drawEnableScissor();
drawBackground();
if (m_previewMode != FULL_PREVIEW) {
drawCameraStand();
}
if (isPreviewEnabled()) drawPreview();
drawOverlay();
drawDisableScissor();
drawViewerIndicators();
// Il freezed e' attivo ed e' in stato "update": faccio il grab del viewer.
if (m_freezedStatus == UPDATE_FREEZED) {
m_viewGrabImage = rasterFromQImage(grabFramebuffer());
m_freezedStatus = NORMAL_FREEZED;
}
#ifdef FPS_HISTOGRAM
int t0 = time.elapsed();
glFlush();
glFinish();
int t1 = time.elapsed();
drawFpsGraph(t0, t1);
#endif
// TOfflineGL::setContextManager(0);
if (!m_isPicking && m_lutCalibrator && m_lutCalibrator->isValid())
m_lutCalibrator->onEndDraw(m_fbo);
}
//-----------------------------------------------------------------------------
void SceneViewer::drawScene() {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
int frame = app->getCurrentFrame()->getFrame();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TRect clipRect = getActualClipRect(getViewMatrix());
clipRect += TPoint(width() * 0.5, height() * 0.5);
ChildStack *childStack = scene->getChildStack();
bool editInPlace = editInPlaceToggle.getStatus() &&
!app->getCurrentFrame()->isEditingLevel();
bool fillFullColorRaster = TXshSimpleLevel::m_fillFullColorRaster;
TXshSimpleLevel::m_fillFullColorRaster = false;
// Guided Drawing Check
int useGuidedDrawing = Preferences::instance()->getGuidedDrawingType();
TTool *tool = app->getCurrentTool()->getTool();
int guidedFrontStroke = tool ? tool->getViewer()->getGuidedFrontStroke() : -1;
int guidedBackStroke = tool ? tool->getViewer()->getGuidedBackStroke() : -1;
m_minZ = 0;
if (is3DView()) {
Stage::OpenGlPainter painter(getViewMatrix(), clipRect, m_visualSettings,
true, false);
painter.enableCamera3D(true);
painter.setPhi(m_phi3D);
int xsheetLevel = 0;
std::pair<TXsheet *, int> xr;
if (editInPlace) {
xr = childStack->getAncestor(frame);
xsheetLevel = childStack->getAncestorCount();
} else
xr = std::make_pair(xsh, frame);
TFrameHandle *frameHandle = TApp::instance()->getCurrentFrame();
Stage::VisitArgs args;
args.m_scene = scene;
args.m_xsh = xr.first;
args.m_row = xr.second;
args.m_col = app->getCurrentColumn()->getColumnIndex();
OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask();
args.m_osm = &osm;
args.m_camera3d = true;
args.m_xsheetLevel = xsheetLevel;
args.m_currentFrameId =
app->getCurrentXsheet()
->getXsheet()
->getCell(app->getCurrentFrame()->getFrame(), args.m_col)
.getFrameId();
args.m_isGuidedDrawingEnabled = useGuidedDrawing;
args.m_guidedFrontStroke = guidedFrontStroke;
args.m_guidedBackStroke = guidedBackStroke;
// args.m_currentFrameId = app->getCurrentFrame()->getFid();
if (m_stopMotion->m_alwaysUseLiveViewImages &&
m_stopMotion->m_liveViewStatus > 0 &&
frame != m_stopMotion->getXSheetFrameNumber() - 1 &&
m_hasStopMotionImage && !m_stopMotion->m_reviewTimer->isActive()) {
TRaster32P image;
bool hasImage = m_stopMotion->loadLiveViewImage(frame, image);
if (hasImage) {
Stage::Player smPlayer;
double dpiX, dpiY;
m_stopMotionImage->getDpi(dpiX, dpiY);
smPlayer.m_dpiAff = TScale(Stage::inch / dpiX, Stage::inch / dpiY);
smPlayer.m_opacity = 255;
smPlayer.m_sl = m_stopMotion->m_sl;
args.m_liveViewImage = static_cast<TRasterImageP>(image);
args.m_liveViewPlayer = smPlayer;
// painter.onRasterImage(static_cast<TRasterImageP>(image).getPointer(),
// smPlayer);
}
}
if ( //! m_stopMotion->m_drawBeneathLevels &&
m_stopMotion->m_liveViewStatus == 2 &&
( //! frameHandle->isPlaying() ||
frame == m_stopMotion->getXSheetFrameNumber() - 1)) {
if (m_hasStopMotionLineUpImage && m_stopMotion->m_showLineUpImage) {
Stage::Player smPlayer;
double dpiX, dpiY;
m_stopMotionLineUpImage->getDpi(dpiX, dpiY);
smPlayer.m_dpiAff = TScale(Stage::inch / dpiX, Stage::inch / dpiY);
smPlayer.m_opacity = 255;
smPlayer.m_sl = m_stopMotion->m_sl;
args.m_lineupImage = m_stopMotionLineUpImage;
args.m_lineupPlayer = smPlayer;
// painter.onRasterImage(m_stopMotionLineUpImage.getPointer(),
// smPlayer);
}
if (m_hasStopMotionImage) {
Stage::Player smPlayer;
double dpiX, dpiY;
m_stopMotionImage->getDpi(dpiX, dpiY);
smPlayer.m_dpiAff = TScale(Stage::inch / dpiX, Stage::inch / dpiY);
bool hide_opacity = false;
#ifdef WITH_CANON
hide_opacity = m_stopMotion->m_canon->m_zooming ||
m_stopMotion->m_canon->m_pickLiveViewZoom ||
!m_hasStopMotionLineUpImage;
#endif
smPlayer.m_opacity = hide_opacity ? 255.0 : m_stopMotion->getOpacity();
smPlayer.m_sl = m_stopMotion->m_sl;
args.m_liveViewImage = m_stopMotionImage;
args.m_liveViewPlayer = smPlayer;
// painter.onRasterImage(m_stopMotionImage.getPointer(), smPlayer);
}
}
Stage::visit(painter, args);
m_minZ = painter.getMinZ();
} else {
// camera 2D (normale)
TDimension viewerSize(width(), height());
TAffine viewAff = getViewMatrix();
if (editInPlace) {
TAffine aff;
if (scene->getChildStack()->getAncestorAffine(aff, frame))
viewAff = viewAff * aff.inv();
}
m_visualSettings.m_showBBox = viewBBoxToggle.getStatus();
Stage::RasterPainter painter(viewerSize, viewAff, clipRect,
m_visualSettings, true);
// darken blended view mode for viewing the non-cleanuped and stacked
// drawings
painter.setRasterDarkenBlendedView(
Preferences::instance()
->isShowRasterImagesDarkenBlendedInViewerEnabled());
TFrameHandle *frameHandle = TApp::instance()->getCurrentFrame();
if (app->getCurrentFrame()->isEditingLevel()) {
Stage::visit(painter, app->getCurrentLevel()->getLevel(),
app->getCurrentFrame()->getFid(),
app->getCurrentOnionSkin()->getOnionSkinMask(),
frameHandle->isPlaying(), useGuidedDrawing, guidedBackStroke,
guidedFrontStroke);
} else {
std::pair<TXsheet *, int> xr;
int xsheetLevel = 0;
if (editInPlace) {
xr = scene->getChildStack()->getAncestor(frame);
xsheetLevel = scene->getChildStack()->getAncestorCount();
} else
xr = std::make_pair(xsh, frame);
Stage::VisitArgs args;
args.m_scene = scene;
args.m_xsh = xr.first;
args.m_row = xr.second;
args.m_col = app->getCurrentColumn()->getColumnIndex();
OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask();
args.m_osm = &osm;
args.m_xsheetLevel = xsheetLevel;
args.m_isPlaying = frameHandle->isPlaying();
if (app->getCurrentLevel() && app->getCurrentLevel()->getLevel() &&
!app->getCurrentLevel()->getLevel()->getSoundLevel())
args.m_currentFrameId =
app->getCurrentXsheet()
->getXsheet()
->getCell(app->getCurrentFrame()->getFrame(), args.m_col)
.getFrameId();
args.m_isGuidedDrawingEnabled = useGuidedDrawing;
args.m_guidedFrontStroke = guidedFrontStroke;
args.m_guidedBackStroke = guidedBackStroke;
if (m_stopMotion->m_alwaysUseLiveViewImages &&
m_stopMotion->m_liveViewStatus > 0 &&
frame != m_stopMotion->getXSheetFrameNumber() - 1 &&
m_hasStopMotionImage && !m_stopMotion->m_reviewTimer->isActive()) {
TRaster32P image;
bool hasImage = m_stopMotion->loadLiveViewImage(frame, image);
if (hasImage) {
Stage::Player smPlayer;
double dpiX, dpiY;
m_stopMotionImage->getDpi(dpiX, dpiY);
smPlayer.m_dpiAff = TScale(Stage::inch / dpiX, Stage::inch / dpiY);
smPlayer.m_opacity = 255;
smPlayer.m_sl = m_stopMotion->m_sl;
args.m_liveViewImage = static_cast<TRasterImageP>(image);
args.m_liveViewPlayer = smPlayer;
// painter.onRasterImage(static_cast<TRasterImageP>(image).getPointer(),
// smPlayer);
}
}
if ( //! m_stopMotion->m_drawBeneathLevels &&
m_stopMotion->m_liveViewStatus == 2 &&
( //! frameHandle->isPlaying() ||
frame == m_stopMotion->getXSheetFrameNumber() - 1)) {
if (m_hasStopMotionLineUpImage && m_stopMotion->m_showLineUpImage) {
Stage::Player smPlayer;
double dpiX, dpiY;
m_stopMotionLineUpImage->getDpi(dpiX, dpiY);
smPlayer.m_dpiAff = TScale(Stage::inch / dpiX, Stage::inch / dpiY);
smPlayer.m_opacity = 255;
smPlayer.m_sl = m_stopMotion->m_sl;
args.m_lineupImage = m_stopMotionLineUpImage;
args.m_lineupPlayer = smPlayer;
// painter.onRasterImage(m_stopMotionLineUpImage.getPointer(),
// smPlayer);
}
if (m_hasStopMotionImage) {
Stage::Player smPlayer;
double dpiX, dpiY;
m_stopMotionImage->getDpi(dpiX, dpiY);
smPlayer.m_dpiAff = TScale(Stage::inch / dpiX, Stage::inch / dpiY);
bool hide_opacity = false;
#ifdef WITH_CANON
hide_opacity = m_stopMotion->m_canon->m_zooming ||
m_stopMotion->m_canon->m_pickLiveViewZoom ||
!m_hasStopMotionLineUpImage;
#endif
smPlayer.m_opacity =
hide_opacity ? 255.0 : m_stopMotion->getOpacity();
smPlayer.m_sl = m_stopMotion->m_sl;
args.m_liveViewImage = m_stopMotionImage;
args.m_liveViewPlayer = smPlayer;
// painter.onRasterImage(m_stopMotionImage.getPointer(), smPlayer);
}
}
Stage::visit(painter, args);
}
assert(glGetError() == 0);
painter.flushRasterImages();
TXshSimpleLevel::m_fillFullColorRaster = fillFullColorRaster;
assert(glGetError() == 0);
if (m_viewMode != LEVEL_VIEWMODE)
drawSpline(getViewMatrix(), clipRect,
m_referenceMode == CAMERA3D_REFERENCE, m_pixelSize);
assert(glGetError() == 0);
// gather animated guide strokes' bounding boxes
// it is used for updating viewer next time
std::vector<TStroke *> guidedStrokes = painter.getGuidedStrokes();
for (auto itr = guidedStrokes.begin(); itr != guidedStrokes.end(); ++itr) {
m_guidedDrawingBBox += (*itr)->getBBox();
}
}
}
//------------------------------------------------------------------------------
void SceneViewer::mult3DMatrix() {
glTranslated(m_pan3D.x, m_pan3D.y, 0);
glScaled(m_zoomScale3D, m_zoomScale3D, 1);
glRotated(m_theta3D, 1, 0, 0);
glRotated(m_phi3D, 0, 1, 0);
}
//-----------------------------------------------------------------------------
double SceneViewer::projectToZ(const TPointD &delta) {
glPushMatrix();
mult3DMatrix();
GLint viewport[4];
double modelview[16], projection[16];
glGetIntegerv(GL_VIEWPORT, viewport);
for (int i = 0; i < 16; i++)
projection[i] = (double)m_projectionMatrix.constData()[i];
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
double ax, ay, az, bx, by, bz;
gluProject(0, 0, 0, modelview, projection, viewport, &ax, &ay, &az);
gluProject(0, 0, 1, modelview, projection, viewport, &bx, &by, &bz);
glPopMatrix();
TPointD zdir(bx - ax, by - ay);
double zdirLength2 = norm2(zdir);
if (zdirLength2 > 0.0) {
double dz = (delta * zdir) / zdirLength2;
return dz;
} else
return 0.0;
}
//-----------------------------------------------------------------------------
TRect SceneViewer::getActualClipRect(const TAffine &aff) {
TDimensionD viewerSize(width(), height());
TRectD clipRect(viewerSize);
if (is3DView()) {
TPointD p00 = winToWorld(clipRect.getP00());
TPointD p01 = winToWorld(clipRect.getP01());
TPointD p10 = winToWorld(clipRect.getP10());
TPointD p11 = winToWorld(clipRect.getP11());
clipRect = TRectD(TPointD(std::min(p00.x, p01.x), std::min(p00.y, p10.y)),
TPointD(std::max(p11.x, p10.x), std::max(p11.y, p01.y)));
}
// this condition will catch both cases of m_clipRect == empty and
// m_clipRect == InvalidateAllRect
else if (m_clipRect.isEmpty())
clipRect -= TPointD(viewerSize.lx / 2, viewerSize.ly / 2);
else {
TRectD app = aff * (m_clipRect.enlarge(3));
clipRect =
TRectD(tceil(app.x0), tceil(app.y0), tfloor(app.x1), tfloor(app.y1));
}
return convert(clipRect);
}
//-----------------------------------------------------------------------------
TAffine SceneViewer::getViewMatrix() const {
int viewMode = TApp::instance()->getCurrentFrame()->isEditingLevel()
? LEVEL_VIEWMODE
: SCENE_VIEWMODE;
if (is3DView()) return TAffine();
if (m_referenceMode == CAMERA_REFERENCE) {
int frame = TApp::instance()->getCurrentFrame()->getFrame();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
TAffine aff = xsh->getCameraAff(frame);
return m_viewAff[viewMode] * aff.inv();
} else
return m_viewAff[viewMode];
}
//-----------------------------------------------------------------------------
TAffine SceneViewer::getSceneMatrix() const {
int viewMode = TApp::instance()->getCurrentFrame()->isEditingLevel()
? LEVEL_VIEWMODE
: SCENE_VIEWMODE;
if (is3DView()) return TAffine();
return m_viewAff[viewMode];
}
//-----------------------------------------------------------------------------
void SceneViewer::setViewMatrix(const TAffine &aff, int viewMode) {
m_viewAff[viewMode] = aff;
// In case the previewer is on, request a delayed update
if (m_previewMode != NO_PREVIEW) requestTimedRefresh();
}
//-----------------------------------------------------------------------------
bool SceneViewer::is3DView() const {
bool isCameraTest = CameraTestCheck::instance()->isEnabled();
return (m_referenceMode == CAMERA3D_REFERENCE && !isCameraTest);
}
//-----------------------------------------------------------------------------
void SceneViewer::invalidateAll() {
m_clipRect = InvalidateAllRect;
update();
if (m_vRuler) m_vRuler->update();
if (m_hRuler) m_hRuler->update();
}
//-----------------------------------------------------------------------------
/*! Pan the viewer by using "navigator" (red rectangle) in level strip
*/
void SceneViewer::navigatorPan(const QPoint &delta) {
panQt(delta);
m_pos += delta;
}
//-----------------------------------------------------------------------------
void SceneViewer::GLInvalidateAll() {
m_clipRect = InvalidateAllRect;
update();
if (m_vRuler) m_vRuler->update();
if (m_hRuler) m_hRuler->update();
}
//-----------------------------------------------------------------------------
void SceneViewer::GLInvalidateRect(const TRectD &rect) {
// in case that GLInvalidateAll is called just before coming here,
// ignore the clip rect and refresh entire viewer
if (m_clipRect == InvalidateAllRect)
return;
else if (rect.isEmpty())
m_clipRect = InvalidateAllRect;
else {
m_clipRect += rect;
if (!m_guidedDrawingBBox.isEmpty()) {
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
TPointD topLeft = tool->getMatrix() * m_guidedDrawingBBox.getP00();
TPointD bottomRight = tool->getMatrix() * m_guidedDrawingBBox.getP11();
m_clipRect += TRectD(topLeft, bottomRight);
}
}
update();
if (m_vRuler) m_vRuler->update();
if (m_hRuler) m_hRuler->update();
m_guidedDrawingBBox.empty();
}
//-----------------------------------------------------------------------------
// delta.x: right panning, pixel; delta.y: down panning, pixel
void SceneViewer::panQt(const QPointF &delta) {
if (delta == QPointF()) return;
if (is3DView())
m_pan3D += TPointD(delta.x(), -delta.y());
else {
// TAffine &viewAff = m_viewAff[m_viewMode];
// viewAff = TTranslation(delta.x(), -delta.y()) * viewAff;
setViewMatrix(TTranslation(delta.x(), -delta.y()) * m_viewAff[m_viewMode],
m_viewMode);
}
invalidateAll();
emit refreshNavi();
}
//-----------------------------------------------------------------------------
void SceneViewer::zoomQt(bool forward, bool reset) {
TPointD delta(m_lastMousePos.x() - width() / 2,
-m_lastMousePos.y() + height() / 2);
if (is3DView()) {
if (reset || ((m_zoomScale3D < 500 || !forward) &&
(m_zoomScale3D > 0.01 || forward))) {
double oldZoomScale = m_zoomScale3D;
m_zoomScale3D = reset ? 1 : ImageUtils::getQuantizedZoomFactor(
m_zoomScale3D, forward);
m_pan3D = -(m_zoomScale3D / oldZoomScale) * -m_pan3D;
}
} else {
// a factor for getting pixel-based zoom ratio
double dpiFactor = getDpiFactor();
// when showing the viewer with full-screen mode,
// add a zoom factor which can show image fitting with the screen size
double zoomScaleFittingWithScreen = 0.0f;
if (dpiFactor != 1.0) {
// check if the viewer is in full screen mode
ImageUtils::FullScreenWidget *fsWidget =
dynamic_cast<ImageUtils::FullScreenWidget *>(parentWidget());
if (fsWidget && (fsWidget->windowState() & Qt::WindowFullScreen) != 0)
zoomScaleFittingWithScreen = getZoomScaleFittingWithScreen();
}
int i;
for (i = 0; i < 2; i++) {
TAffine &viewAff = m_viewAff[i];
if (m_isFlippedX) viewAff = viewAff * TScale(-1, 1);
if (m_isFlippedX) viewAff = viewAff * TScale(1, -1);
double scale2 = std::abs(viewAff.det());
if (m_isFlippedX) viewAff = viewAff * TScale(-1, 1);
if (m_isFlippedX) viewAff = viewAff * TScale(1, -1);
if (reset || ((scale2 < 100000 || !forward) &&
(scale2 > 0.001 * 0.05 || forward))) {
double oldZoomScale = sqrt(scale2) * dpiFactor;
double zoomScale = reset ? 1 : ImageUtils::getQuantizedZoomFactor(
oldZoomScale, forward);
// threshold value -0.001 is intended to absorb the error of calculation
if ((oldZoomScale - zoomScaleFittingWithScreen) *
(zoomScale - zoomScaleFittingWithScreen) <
-0.001)
zoomScale = zoomScaleFittingWithScreen;
// zoom center = viewer center
if (Preferences::instance()->getViewerZoomCenter())
setViewMatrix(TScale(zoomScale / oldZoomScale) * viewAff, i);
// zoom center = mouse pos
else
setViewMatrix(TTranslation(delta) * TScale(zoomScale / oldZoomScale) *
TTranslation(-delta) * viewAff,
i);
}
}
}
GLInvalidateAll();
emit onZoomChanged();
}
//-----------------------------------------------------------------------------
/*! a factor for getting pixel-based zoom ratio
*/
double SceneViewer::getDpiFactor() {
// When the current unit is "pixels", always use a standard dpi
double cameraDpi = TApp::instance()
->getCurrentScene()
->getScene()
->getCurrentCamera()
->getDpi()
.x;
if (Preferences::instance()->getPixelsOnly()) {
return Stage::inch / Stage::standardDpi;
}
// When preview mode, use a camera DPI
else if (isPreviewEnabled()) {
return Stage::inch / cameraDpi;
}
// When level editing mode, use an image DPI
else if (TApp::instance()->getCurrentFrame()->isEditingLevel()) {
TXshSimpleLevel *sl;
sl = TApp::instance()->getCurrentLevel()->getSimpleLevel();
if (!sl) return Stage::inch / cameraDpi;
if (sl->getType() == PLI_XSHLEVEL) return Stage::inch / cameraDpi;
if (sl->getImageDpi() != TPointD())
return Stage::inch / sl->getImageDpi().x;
if (sl->getDpi() != TPointD()) return Stage::inch / sl->getDpi().x;
// no valid dpi, use camera dpi
return Stage::inch / cameraDpi;
}
// When the special case in the scene editing mode:
// If the option "ActualPixelViewOnSceneEditingMode" is ON,
// use current level's DPI set in the level settings.
else if (Preferences::instance()
->isActualPixelViewOnSceneEditingModeEnabled()) {
if (CleanupPreviewCheck::instance()->isEnabled() ||
CameraTestCheck::instance()->isEnabled()) {
double cleanupCameraDpi = TApp::instance()
->getCurrentScene()
->getScene()
->getProperties()
->getCleanupParameters()
->m_camera.getDpi()
.x;
return Stage::inch / cleanupCameraDpi;
} else {
TXshSimpleLevel *sl;
sl = TApp::instance()->getCurrentLevel()->getSimpleLevel();
if (!sl) return Stage::inch / cameraDpi;
if (sl->getType() == PLI_XSHLEVEL) return Stage::inch / cameraDpi;
if (sl->getDpi() == TPointD()) return Stage::inch / cameraDpi;
// use default value for the argument of getDpi() (=TFrameId::NO_FRAME)
// so that the dpi of the first frame in the level will be returned.
return Stage::inch / sl->getDpi().x;
}
}
// When the scene editing mode without any option, use the camera dpi
else {
return Stage::inch / cameraDpi;
}
}
//-----------------------------------------------------------------------------
/*! when showing the viewer with full-screen mode,
add a zoom factor which can show image fitting with the screen size
*/
double SceneViewer::getZoomScaleFittingWithScreen() {
TDimension imgSize;
// get the image size to be rendered
if (isPreviewEnabled())
imgSize = TApp::instance()
->getCurrentScene()
->getScene()
->getCurrentCamera()
->getRes();
else if (TApp::instance()->getCurrentFrame()->isEditingLevel()) {
TXshSimpleLevel *sl = TApp::instance()->getCurrentLevel()->getSimpleLevel();
if (!sl || sl->getType() == PLI_XSHLEVEL || sl->getImageDpi() == TPointD())
return 0.0;
imgSize = sl->getResolution();
} else if (Preferences::instance()
->isActualPixelViewOnSceneEditingModeEnabled() &&
!CleanupPreviewCheck::instance()->isEnabled() &&
!CameraTestCheck::instance()->isEnabled()) {
TXshSimpleLevel *sl = TApp::instance()->getCurrentLevel()->getSimpleLevel();
if (!sl || sl->getType() == PLI_XSHLEVEL || sl->getDpi() == TPointD())
return 0.0;
imgSize = sl->getResolution();
} else // SCENE_VIEWMODE
return 0.0;
// add small margin on the edge of the image
int margin = 20;
// get the desktop resolution
QRect rec = QApplication::desktop()->screenGeometry();
// fit to either direction
int moni_x = rec.width() - (margin * 2);
int moni_y = rec.height() - (margin * 2);
return std::min((double)moni_x / (double)imgSize.lx,
(double)moni_y / (double)imgSize.ly);
}
//-----------------------------------------------------------------------------
// center: window coordinate, pixels, topleft origin
void SceneViewer::zoomQt(const QPoint ¢er, double factor) {
if (factor == 1.0) return;
TPointD delta(center.x() - width() / 2, -center.y() + height() / 2);
double oldZoomScale = m_zoomScale3D;
if (is3DView()) {
if ((m_zoomScale3D < 500 || factor < 1) &&
(m_zoomScale3D > 0.01 || factor > 1)) {
m_zoomScale3D *= factor;
m_pan3D = -(m_zoomScale3D / oldZoomScale) * (delta - m_pan3D) + delta;
}
} else {
int i;
for (i = 0; i < 2; i++) {
TAffine &viewAff = m_viewAff[i];
double scale2 = fabs(viewAff.det());
if ((scale2 < 100000 || factor < 1) &&
(scale2 > 0.001 * 0.05 || factor > 1)) {
if (i == m_viewMode) {
// viewAff = TTranslation(delta) * TScale(factor) *
// TTranslation(-delta) * viewAff;
setViewMatrix(TTranslation(delta) * TScale(factor) *
TTranslation(-delta) * viewAff,
i);
} else {
// viewAff = TScale(factor) * viewAff;
setViewMatrix(TScale(factor) * viewAff, i);
}
}
}
}
GLInvalidateAll();
emit onZoomChanged();
}
void SceneViewer::zoom(const TPointD ¢er, double factor) {
zoomQt(QPoint(center.x, height() - center.y), factor);
}
//-----------------------------------------------------------------------------
void SceneViewer::flipX() {
double flipAngle0 = (m_rotationAngle[0] * -1) * 2;
double flipAngle1 = (m_rotationAngle[1] * -1) * 2;
m_rotationAngle[0] += flipAngle0;
m_rotationAngle[1] += flipAngle1;
if (m_isFlippedX != m_isFlippedY) {
flipAngle0 = -flipAngle0;
flipAngle1 = -flipAngle1;
}
m_viewAff[0] = m_viewAff[0] * TRotation(flipAngle0) * TScale(-1, 1);
m_viewAff[1] = m_viewAff[1] * TRotation(flipAngle1) * TScale(-1, 1);
m_viewAff[0].a13 *= -1;
m_viewAff[1].a13 *= -1;
m_isFlippedX = !m_isFlippedX;
invalidateAll();
emit onZoomChanged();
emit onFlipHChanged(m_isFlippedX);
}
//-----------------------------------------------------------------------------
void SceneViewer::flipY() {
double flipAngle0 = (m_rotationAngle[0] * -1) * 2;
double flipAngle1 = (m_rotationAngle[1] * -1) * 2;
m_rotationAngle[0] += flipAngle0;
m_rotationAngle[1] += flipAngle1;
if (m_isFlippedX != m_isFlippedY) {
flipAngle0 = -flipAngle0;
flipAngle1 = -flipAngle1;
}
m_viewAff[0] = m_viewAff[0] * TRotation(flipAngle0) * TScale(1, -1);
m_viewAff[1] = m_viewAff[1] * TRotation(flipAngle1) * TScale(1, -1);
m_viewAff[0].a23 *= -1;
m_viewAff[1].a23 *= -1;
m_isFlippedY = !m_isFlippedY;
invalidateAll();
emit onZoomChanged();
emit onFlipVChanged(m_isFlippedY);
}
//-----------------------------------------------------------------------------
void SceneViewer::zoomIn() {
m_lastMousePos = rect().center();
zoomQt(true, false);
}
//-----------------------------------------------------------------------------
void SceneViewer::zoomOut() {
m_lastMousePos = rect().center();
zoomQt(false, false);
}
//-----------------------------------------------------------------------------
void SceneViewer::rotate(const TPointD ¢er, double angle) {
if (angle == 0) return;
if (m_isFlippedX != m_isFlippedY) angle = -angle;
m_rotationAngle[m_viewMode] += angle;
TPointD realCenter = m_viewAff[m_viewMode] * center;
setViewMatrix(TRotation(realCenter, angle) * m_viewAff[m_viewMode],
m_viewMode);
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::rotate3D(double dPhi, double dTheta) {
if (dPhi == 0 && dTheta == 0) return;
m_phi3D = (float)tcrop(m_phi3D + dPhi, -90.0, 90.0);
m_theta3D = (float)tcrop(m_theta3D + dTheta, 0.0, 90.0);
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::regeneratePreview() {
Previewer::instance(m_previewMode == SUBCAMERA_PREVIEW)->clear();
update();
}
//-----------------------------------------------------------------------------
void SceneViewer::regeneratePreviewFrame() {
Previewer::instance(m_previewMode == SUBCAMERA_PREVIEW)
->clear(TApp::instance()->getCurrentFrame()->getFrame());
update();
}
//-----------------------------------------------------------------------------
void SceneViewer::swapCompared() {
m_compareSettings.m_swapCompared = !m_compareSettings.m_swapCompared;
update();
}
//-----------------------------------------------------------------------------
void SceneViewer::fitToCamera() {
// Reset the view scale to 1:1.
bool tempIsFlippedX = m_isFlippedX;
bool tempIsFlippedY = m_isFlippedY;
resetSceneViewer();
m_isFlippedX = tempIsFlippedX;
m_isFlippedY = tempIsFlippedY;
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
int frame = TApp::instance()->getCurrentFrame()->getFrame();
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
TStageObject *camera = xsh->getStageObject(cameraId);
TAffine cameraPlacement = camera->getPlacement(frame);
double cameraZ = camera->getZ(frame);
TAffine cameraAff =
getViewMatrix() * cameraPlacement * TScale((1000 + cameraZ) / 1000);
QRect viewRect = rect();
TRectD cameraRect = ViewerDraw::getCameraRect();
TPointD P00 = cameraAff * cameraRect.getP00();
TPointD P10 = cameraAff * cameraRect.getP10();
TPointD P01 = cameraAff * cameraRect.getP01();
TPointD P11 = cameraAff * cameraRect.getP11();
TPointD p0 = TPointD(std::min({P00.x, P01.x, P10.x, P11.x}),
std::min({P00.y, P01.y, P10.y, P11.y}));
TPointD p1 = TPointD(std::max({P00.x, P01.x, P10.x, P11.x}),
std::max({P00.y, P01.y, P10.y, P11.y}));
cameraRect = TRectD(p0.x, p0.y, p1.x, p1.y);
// Pan
if (!is3DView()) {
TPointD cameraCenter = (cameraRect.getP00() + cameraRect.getP11()) * 0.5;
panQt(QPoint(-cameraCenter.x, cameraCenter.y));
}
double xratio = (double)viewRect.width() / cameraRect.getLx();
double yratio = (double)viewRect.height() / cameraRect.getLy();
double ratio = std::min(xratio, yratio);
if (ratio == 0.0) return;
if (tempIsFlippedX)
setViewMatrix(TScale(-1, 1) * m_viewAff[m_viewMode], m_viewMode);
if (tempIsFlippedY)
setViewMatrix(TScale(1, -1) * m_viewAff[m_viewMode], m_viewMode);
// Scale and center on the center of \a rect.
QPoint c = viewRect.center();
zoom(TPointD(c.x(), c.y()), ratio);
emit onFlipHChanged(m_isFlippedX);
emit onFlipVChanged(m_isFlippedY);
}
//-----------------------------------------------------------------------------
void SceneViewer::fitToCameraOutline() {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
int frame = TApp::instance()->getCurrentFrame()->getFrame();
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
TStageObject *camera = xsh->getStageObject(cameraId);
TAffine cameraPlacement = camera->getPlacement(frame);
double cameraZ = camera->getZ(frame);
TAffine cameraAff =
getViewMatrix() * cameraPlacement * TScale((1000 + cameraZ) / 1000);
QRect viewRect = rect();
TRectD cameraRect = ViewerDraw::getCameraRect();
TPointD P00 = cameraAff * cameraRect.getP00();
TPointD P10 = cameraAff * cameraRect.getP10();
TPointD P01 = cameraAff * cameraRect.getP01();
TPointD P11 = cameraAff * cameraRect.getP11();
TPointD p0 = TPointD(std::min({P00.x, P01.x, P10.x, P11.x}),
std::min({P00.y, P01.y, P10.y, P11.y}));
TPointD p1 = TPointD(std::max({P00.x, P01.x, P10.x, P11.x}),
std::max({P00.y, P01.y, P10.y, P11.y}));
cameraRect = TRectD(p0.x, p0.y, p1.x, p1.y);
// Pan
if (!is3DView()) {
TPointD cameraCenter = (cameraRect.getP00() + cameraRect.getP11()) * 0.5;
panQt(QPoint(-cameraCenter.x, cameraCenter.y));
}
double xratio = (double)viewRect.width() / cameraRect.getLx();
double yratio = (double)viewRect.height() / cameraRect.getLy();
double ratio = std::min(xratio, yratio);
if (ratio == 0.0) return;
// Scale and center on the center of \a rect.
QPoint c = viewRect.center();
zoom(TPointD(c.x(), c.y()), ratio);
zoom(TPointD(c.x(), c.y()), 0.95);
}
//-----------------------------------------------------------------------------
void SceneViewer::resetSceneViewer() {
m_visualSettings.m_sceneProperties =
TApp::instance()->getCurrentScene()->getScene()->getProperties();
for (int i = 0; i < m_viewAff.size(); ++i) {
setViewMatrix(getNormalZoomScale(), i);
m_rotationAngle[i] = 0.0;
}
m_pos = QPoint(0, 0);
m_pan3D = TPointD(0, 0);
m_zoomScale3D = 0.1;
m_theta3D = 20;
m_phi3D = 30;
m_isFlippedX = false;
m_isFlippedY = false;
fitToCameraOutline();
emit onZoomChanged();
emit onFlipHChanged(m_isFlippedX);
emit onFlipVChanged(m_isFlippedY);
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::resetZoom() {
TPointD realCenter(m_viewAff[m_viewMode].a13, m_viewAff[m_viewMode].a23);
TAffine aff =
getNormalZoomScale() * TRotation(realCenter, m_rotationAngle[m_viewMode]);
aff.a13 = realCenter.x;
aff.a23 = realCenter.y;
if (m_isFlippedX) aff = aff * TScale(-1, 1);
if (m_isFlippedY) aff = aff * TScale(1, -1);
setViewMatrix(aff, m_viewMode);
invalidateAll();
emit onZoomChanged();
}
//-----------------------------------------------------------------------------
void SceneViewer::resetRotation() {
double reverseRotatation = m_rotationAngle[m_viewMode] * -1;
if (m_isFlippedX) reverseRotatation *= -1;
if (m_isFlippedY) reverseRotatation *= -1;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
TPointD center = m_viewAff[m_viewMode].inv() * TPointD(0, 0);
if (tool->getName() == "T_Rotate" &&
tool->getProperties(0)
->getProperty("Rotate On Camera Center")
->getValueAsString() == "1")
center = TPointD(0, 0);
rotate(center, reverseRotatation);
}
//-----------------------------------------------------------------------------
void SceneViewer::resetPosition() {
m_viewAff[m_viewMode].a13 = 0.0;
m_viewAff[m_viewMode].a23 = 0.0;
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::setActualPixelSize() {
TApp *app = TApp::instance();
TXshLevel *l = app->getCurrentLevel()->getLevel();
TXshSimpleLevel *sl = l ? l->getSimpleLevel() : 0;
if (!sl) return;
TFrameId fid(app->getCurrentFrame()->getFid());
TPointD dpi;
if (CleanupPreviewCheck::instance()->isEnabled()) {
// The previewed cleanup image has no image infos yet - retrieve the dpi
// through
// the cleanup camera data
CleanupParameters *cleanupParams = app->getCurrentScene()
->getScene()
->getProperties()
->getCleanupParameters();
TDimension dim(0, 0);
cleanupParams->getOutputImageInfo(dim, dpi.x, dpi.y);
} else
dpi = sl->getDpi(fid);
const double inch = Stage::inch;
TAffine tempAff = getNormalZoomScale();
if (m_isFlippedX) tempAff = tempAff * TScale(-1, 1);
if (m_isFlippedY) tempAff = tempAff * TScale(1, -1);
TPointD tempScale = dpi;
if (m_isFlippedX) tempScale.x = -tempScale.x;
if (m_isFlippedY) tempScale.y = -tempScale.y;
for (int i = 0; i < m_viewAff.size(); ++i)
setViewMatrix(dpi == TPointD(0, 0) ? tempAff : TScale(tempScale.x / inch,
tempScale.y / inch),
i);
m_pos = QPoint(0, 0);
m_pan3D = TPointD(0, 0);
m_zoomScale3D = 0.1;
m_theta3D = 20;
m_phi3D = 30;
emit onZoomChanged();
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::onLevelChanged() {
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool) {
TXshLevel *level = TApp::instance()->getCurrentLevel()->getLevel();
if (level && level->getSimpleLevel())
m_dpiScale =
getCurrentDpiScale(level->getSimpleLevel(), tool->getCurrentFid());
else
m_dpiScale = TPointD(1, 1);
}
}
//-----------------------------------------------------------------------------
/*! when level is switched, update m_dpiScale in order to show white background
* for Ink&Paint work properly
*/
void SceneViewer::onLevelSwitched() {
invalidateToolStatus();
TApp *app = TApp::instance();
TTool *tool = app->getCurrentTool()->getTool();
TXshLevel *level = app->getCurrentLevel()->getLevel();
if (level && level->getSimpleLevel())
m_dpiScale =
getCurrentDpiScale(level->getSimpleLevel(), tool->getCurrentFid());
else
m_dpiScale = TPointD(1, 1);
}
//-----------------------------------------------------------------------------
void SceneViewer::onXsheetChanged() {
m_forceGlFlush = true;
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool && tool->isEnabled()) tool->updateMatrix();
onLevelChanged();
GLInvalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::onObjectSwitched() {
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool && tool->isEnabled()) tool->updateMatrix();
onLevelChanged();
GLInvalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::onSceneChanged() {
onLevelChanged();
GLInvalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::onFrameSwitched() {
invalidateToolStatus();
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool && tool->isEnabled()) {
tool->setViewer(this);
tool->updateMatrix();
tool->onEnter();
}
GLInvalidateAll();
}
//-----------------------------------------------------------------------------
/*! when tool options are changed, update tooltip immediately
*/
void SceneViewer::onToolChanged() {
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool) setToolCursor(this, tool->getCursorId());
GLInvalidateAll();
}
//-----------------------------------------------------------------------------
int SceneViewer::pick(const TPointD &point) {
// pick is typically called in a mouse event handler.
// QGLWidget::makeCurrent() is not automatically called in these events.
// (to exploit the bug: open the FxEditor preview and then select the edit
// tool)
m_isPicking = true;
makeCurrent();
assert(glGetError() == GL_NO_ERROR);
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
std::array<GLuint, 512> selectBuffer;
glSelectBuffer(selectBuffer.size(), selectBuffer.data());
glRenderMode(GL_SELECT);
// definisco la matrice di proiezione
glMatrixMode(GL_PROJECTION);
GLdouble mat[16];
glGetDoublev(GL_PROJECTION_MATRIX, mat);
glPushMatrix();
glLoadIdentity();
gluPickMatrix(point.x, point.y, 5, 5, viewport);
glMultMatrixd(mat);
assert(glGetError() == GL_NO_ERROR);
// disegno la scena
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glInitNames();
assert(glGetError() == GL_NO_ERROR);
// WARNING: We have to draw the scene in CAMERASTAND mode. Observe that the
// preview mode may
// invoke event processing - therefore triggering other pick events while in
// GL_SELECT
// render mode...
int previewMode = m_previewMode;
m_previewMode = NO_PREVIEW;
// OPTIMIZATION / QUICK FIX
// A 1x1 clipping rect around the picked pos can very well be used instead of
// redrawing
// the *entire viewer*.
// This is needed especially since some graphic cards (all NVidias we have
// tested) are
// very slow otherwise. This could be due to this particular rendering mode -
// or because
// we could be painting OUTSIDE a paintEvent()...
TRectD oldClipRect(m_clipRect);
m_clipRect = TRectD(point.x, point.y, point.x + 1, point.y + 1);
paintGL(); // draw identifiable objects
m_clipRect = oldClipRect;
m_previewMode = previewMode;
assert(glGetError() == GL_NO_ERROR);
glPopMatrix();
// rimetto a posto la matrice di proiezione
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
assert(glGetError() == GL_NO_ERROR);
// conto gli hits
int ret = -1;
int hitCount = glRenderMode(GL_RENDER);
GLuint *p = selectBuffer.data();
for (int i = 0; i < hitCount; ++i) {
GLuint nameCount = *p++;
GLuint zmin = *p++;
GLuint zmax = *p++;
if (nameCount > 0) {
GLuint name = *p;
ret = name; // items.push_back(PickItem(name, zmin, zmax));
}
p += nameCount;
}
assert(glGetError() == GL_NO_ERROR);
m_isPicking = false;
return ret;
}
//-----------------------------------------------------------------------------
int SceneViewer::posToColumnIndex(const TPointD &p, double distance,
bool includeInvisible) const {
std::vector<int> ret;
posToColumnIndexes(p, ret, distance, includeInvisible);
return ret.empty() ? -1 : ret.back();
}
//-----------------------------------------------------------------------------
void SceneViewer::posToColumnIndexes(const TPointD &p,
std::vector<int> &indexes, double distance,
bool includeInvisible) const {
int oldRasterizePli = TXshSimpleLevel::m_rasterizePli;
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
int frame = app->getCurrentFrame()->getFrame();
int currentColumnIndex = app->getCurrentColumn()->getColumnIndex();
OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask();
TPointD pos = TPointD(p.x - width() / 2, p.y - height() / 2);
Stage::Picker picker(getViewMatrix(), pos, m_visualSettings,
getDevPixRatio());
picker.setMinimumDistance(distance);
TXshSimpleLevel::m_rasterizePli = 0;
Stage::VisitArgs args;
args.m_scene = scene;
args.m_xsh = xsh;
args.m_row = frame;
args.m_col = currentColumnIndex;
args.m_osm = &osm;
args.m_onlyVisible = includeInvisible;
Stage::visit(picker, args); /*
picker,
scene,
xsh,
frame,
currentColumnIndex,
osm,
false,
0,
false,
includeInvisible);
*/
TXshSimpleLevel::m_rasterizePli = oldRasterizePli;
picker.getColumnIndexes(indexes);
}
//-----------------------------------------------------------------------------
int SceneViewer::posToRow(const TPointD &p, double distance,
bool includeInvisible, bool currentColumnOnly) const {
int oldRasterizePli = TXshSimpleLevel::m_rasterizePli;
TApp *app = TApp::instance();
OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask();
TPointD pos = TPointD(p.x - width() / 2, p.y - height() / 2);
Stage::Picker picker(getViewMatrix(), pos, m_visualSettings,
getDevPixRatio());
picker.setMinimumDistance(distance);
if (app->getCurrentFrame()->isEditingLevel()) {
Stage::visit(picker, app->getCurrentLevel()->getLevel(),
app->getCurrentFrame()->getFid(), osm,
app->getCurrentFrame()->isPlaying(), false);
} else {
ToonzScene *scene = app->getCurrentScene()->getScene();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
int frame = app->getCurrentFrame()->getFrame();
int currentColumnIndex = app->getCurrentColumn()->getColumnIndex();
TXshSimpleLevel::m_rasterizePli = 0;
Stage::VisitArgs args;
args.m_scene = scene;
args.m_xsh = xsh;
args.m_row = frame;
args.m_col = currentColumnIndex;
args.m_osm = &osm;
args.m_onlyVisible = includeInvisible;
if (currentColumnOnly) picker.setCurrentColumnIndex(currentColumnIndex);
Stage::visit(picker, args);
}
TXshSimpleLevel::m_rasterizePli = oldRasterizePli;
return picker.getRow();
}
//-----------------------------------------------------------------------------
void drawSpline(const TAffine &viewMatrix, const TRect &clipRect, bool camera3d,
double pixelsize) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
TStageObjectId objId = TApp::instance()->getCurrentObject()->getObjectId();
TStageObject *pegbar =
(objId != TStageObjectId::NoneId) //&&
// objId != xsh->getStageObjectTree()->getMotionPathViewerId())
? xsh->getStageObject(objId)
: 0;
bool isMotionPathViewer =
objId == xsh->getStageObjectTree()->getMotionPathViewerId() &&
TApp::instance()->getCurrentObject()->isSpline();
TStageObjectSpline *pegbarSpline = 0;
if (TApp::instance()->getCurrentObject()->isSpline() && pegbar &&
pegbar->getSpline()) {
const TStroke *stroke = 0;
pegbarSpline = pegbar->getSpline();
if (!isMotionPathViewer) {
stroke = pegbar->getSpline()->getStroke();
if (!stroke) return;
int frame = TApp::instance()->getCurrentFrame()->getFrame();
TAffine aff;
double objZ = 0, objNoScaleZ = 0;
if (objId != TStageObjectId::NoneId) {
aff = xsh->getParentPlacement(objId, frame);
objZ = xsh->getZ(objId, frame);
objNoScaleZ = xsh->getStageObject(objId)->getGlobalNoScaleZ();
}
glPushMatrix();
if (camera3d) {
tglMultMatrix(aff);
aff = TAffine();
glTranslated(0, 0, objZ);
} else {
TStageObjectId cameraId =
xsh->getStageObjectTree()->getCurrentCameraId();
double camZ = xsh->getZ(cameraId, frame);
TAffine camAff = xsh->getPlacement(cameraId, frame);
TAffine tmp;
TStageObject::perspective(tmp, camAff, camZ, aff, objZ, objNoScaleZ);
aff = viewMatrix * tmp;
}
if (TApp::instance()->getCurrentObject()->isSpline()) {
glColor3d(1.0, 0.5, 0);
glLineStipple(1, 0x18FF);
} else {
glLineStipple(1, 0xCCCC);
glColor3d(1, 0, 1);
}
glEnable(GL_LINE_STIPPLE);
tglMultMatrix(aff);
double pixelSize = std::max(0.1, pixelsize);
double strokeLength = stroke->getLength();
int n = (int)(5 + (strokeLength / pixelSize) * 0.1);
glBegin(GL_LINE_STRIP);
for (int i = 0; i < n; i++)
tglVertex(stroke->getPoint((double)i / (double)(n - 1)));
glEnd();
glDisable(GL_LINE_STIPPLE);
int cpCount = stroke->getControlPointCount();
for (int i = 0; i * 4 < cpCount; i++) {
double t = stroke->getParameterAtControlPoint(i * 4);
TPointD pos = stroke->getPoint(t);
tglDrawText(pos, QString::number(i).toStdString().c_str());
}
{
TAffine parentAff = xsh->getParentPlacement(objId, frame);
TAffine aff = xsh->getPlacement(objId, frame);
TPointD center = Stage::inch * xsh->getCenter(objId, frame);
glPushMatrix();
tglMultMatrix(parentAff.inv() * TTranslation(aff * center));
center = TPointD();
// draw center
// tglDrawDisk(center,pixelSize*5);
tglDrawDisk(center, sqrt(tglGetPixelSize2()) * 5);
glPopMatrix();
}
glPopMatrix();
}
}
int splineCount = xsh->getStageObjectTree()->getSplineCount();
for (int i = 0; i < splineCount; i++) {
TStageObjectSpline *spline = xsh->getStageObjectTree()->getSpline(i);
if (isMotionPathViewer && (pegbarSpline && pegbarSpline == spline))
int z;
else if (!spline->getActive())
continue;
const TStroke *stroke = 0;
int steps = 0;
bool showSteps = false;
stroke = spline->getStroke();
showSteps = true;
steps = spline->getSteps();
if (!stroke) return;
int frame = TApp::instance()->getCurrentFrame()->getFrame();
TAffine aff;
double objZ = 0, objNoScaleZ = 0;
if (objId != TStageObjectId::NoneId) {
aff = xsh->getParentPlacement(objId, frame);
objZ = xsh->getZ(objId, frame);
objNoScaleZ = xsh->getStageObject(objId)->getGlobalNoScaleZ();
}
glPushMatrix();
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (camera3d) {
tglMultMatrix(aff);
aff = TAffine();
glTranslated(0, 0, objZ);
} else {
TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();
double camZ = xsh->getZ(cameraId, frame);
TAffine camAff = xsh->getPlacement(cameraId, frame);
TAffine tmp;
TStageObject::perspective(tmp, camAff, camZ, aff, objZ, objNoScaleZ);
aff = viewMatrix * tmp;
}
int width = spline->getWidth();
glLineWidth((double)width);
std::vector<double> reds{1.0, 1.0, 0.0, 1.0, 0.0, 0.0,
0.0, 1.0, 0.7, 0.5, 0.3};
std::vector<double> greens{0.0, 1.0, 1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.7, 0.5, 0.3};
std::vector<double> blues{1.0, 0.0, 1.0, 0.0, 1.0, 0.0,
0.0, 1.0, 0.7, 0.5, 0.3};
int color = spline->getColor();
glColor3d(reds.at(color), greens.at(color), blues.at(color));
// glEnable(GL_LINE_STIPPLE);
tglMultMatrix(aff);
double pixelSize = std::max(0.1, pixelsize);
double strokeLength = stroke->getLength();
int n = (int)(5 + (strokeLength / pixelSize) * 0.1);
glBegin(GL_LINE_STRIP);
for (int i = 0; i < n; i++)
tglVertex(stroke->getPoint((double)i / (double)(n - 1)));
glEnd();
// glDisable(GL_LINE_STIPPLE);
if (showSteps && steps > 0) {
QList<TPointD> interpolationStroke = spline->getInterpolationStroke();
int cp = 3;
TPointD startPoint = interpolationStroke.at(cp);
TPointD control1 = interpolationStroke.at(cp + 1);
TPointD control2 = interpolationStroke.at(cp + 2);
TPointD endPoint = interpolationStroke.at(cp + 3);
TCubic cubic(startPoint, control1, control2, endPoint);
double length = stroke->getLength(0.0, 1.0);
double step = 1.0 / (double)(steps > 1 ? steps - 1 : 1);
double currentPosition = 0.0;
double s0 = 0.0;
double s1 = 1.0;
bool playing = spline->getIsPlaying();
int currentStep = spline->getCurrentStep();
TPointD prePoint, point, postPoint;
for (int i = 0; i <= steps; i++) {
double y = -1;
if (i == 0)
y = 0;
else if (i == steps)
y = 1000.0;
else {
currentPosition = (double)i * step;
if (currentPosition > 1.0) currentPosition = 1.0;
double tempX = std::round(currentPosition * 1000.0);
if (tempX > endPoint.x) {
cp += 3;
startPoint = interpolationStroke.at(cp);
control1 = interpolationStroke.at(cp + 1);
control2 = interpolationStroke.at(cp + 2);
endPoint = interpolationStroke.at(cp + 3);
cubic = TCubic(startPoint, control1, control2, endPoint);
}
y = getCubicYfromX(cubic, tempX, s0, s1);
}
if (y >= 0) {
double newY = std::min((double)y, 1000.0) / 1000.0;
point = stroke->getPointAtLength(length * newY);
prePoint = (i == 0)
? point
: stroke->getPointAtLength(length * (newY - 0.02));
postPoint = (i == steps)
? point
: stroke->getPointAtLength(length * (newY + 0.02));
if (prePoint == postPoint) continue;
double radian =
std::atan2(postPoint.y - prePoint.y, postPoint.x - prePoint.x);
double degree = radian * 180.0 / 3.14159265;
glPushMatrix();
glTranslated(point.x, point.y, 0);
glRotated(degree, 0, 0, 1);
glBegin(GL_LINES);
glVertex2d(0, 3 + width);
glVertex2d(0, -3 - width);
glEnd();
if (playing && currentStep == i) {
tglDrawDisk(TPointD(0, 0), 4 + width * 3);
}
glPopMatrix();
}
}
}
glLineWidth(1.0);
glDisable(GL_LINE_SMOOTH);
glDisable(GL_BLEND);
glPopMatrix();
}
}
//-----------------------------------------------------------------------------
void SceneViewer::resetInputMethod() {
#if QT_VERSION >= 0x050000
QGuiApplication::inputMethod()->reset();
#else
qApp->inputContext()->reset();
#endif
}
//-----------------------------------------------------------------------------
void SceneViewer::set3DLeftSideView() {
m_phi3D = -90;
m_theta3D = 0;
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::set3DRightSideView() {
m_phi3D = 90;
m_theta3D = 0;
invalidateAll();
}
//-----------------------------------------------------------------------------
void SceneViewer::set3DTopView() {
m_phi3D = 0;
m_theta3D = 90;
invalidateAll();
}
//-----------------------------------------------------------------------------
bool SceneViewer::canSwapCompared() const {
return m_visualSettings.m_doCompare && m_previewMode != NO_PREVIEW;
}
//-----------------------------------------------------------------------------
TAffine SceneViewer::getNormalZoomScale() {
return TScale(getDpiFactor()).inv();
}
//-----------------------------------------------------------------------------
void SceneViewer::invalidateToolStatus() {
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
if (tool) {
m_toolDisableReason = tool->updateEnabled();
if (tool->isEnabled()) {
setToolCursor(this, tool->getCursorId());
tool->setViewer(this);
tool->updateMatrix();
} else
setCursor(Qt::ForbiddenCursor);
} else
setCursor(Qt::ForbiddenCursor);
}
//-----------------------------------------------------------------------------
/*! return the viewer geometry in order to avoid picking the style outside of
the viewer
when using the stylepicker and the finger tools
*/
TRectD SceneViewer::getGeometry() const {
int devPixRatio = getDevPixRatio();
TTool *tool = TApp::instance()->getCurrentTool()->getTool();
TPointD topLeft =
tool->getMatrix().inv() * winToWorld(geometry().topLeft() * devPixRatio);
TPointD bottomRight = tool->getMatrix().inv() *
winToWorld(geometry().bottomRight() * devPixRatio);
TObjectHandle *objHandle = TApp::instance()->getCurrentObject();
if (tool->getToolType() & TTool::LevelTool && !objHandle->isSpline()) {
topLeft.x /= m_dpiScale.x;
topLeft.y /= m_dpiScale.y;
bottomRight.x /= m_dpiScale.x;
bottomRight.y /= m_dpiScale.y;
}
return TRectD(topLeft, bottomRight);
}
//-----------------------------------------------------------------------------
/*! delete preview - subcamera executed from context menu
*/
void SceneViewer::doDeleteSubCamera() {
PreviewSubCameraManager::instance()->deleteSubCamera(this);
}
//-----------------------------------------------------------------------------
void SceneViewer::bindFBO() {
if (m_fbo) m_fbo->bind();
}
//-----------------------------------------------------------------------------
void SceneViewer::releaseFBO() {
if (m_fbo) m_fbo->release();
}
//-----------------------------------------------------------------------------
void SceneViewer::onContextAboutToBeDestroyed() {
if (!m_lutCalibrator) return;
makeCurrent();
m_lutCalibrator->cleanup();
doneCurrent();
disconnect(context(), SIGNAL(aboutToBeDestroyed()), this,
SLOT(onContextAboutToBeDestroyed()));
}
//-----------------------------------------------------------------------------
// called from SceneViewer::initializeGL()
void SceneViewer::registerContext() {
// release the old context, if any
// this will be happen when dock / float the viewer panel.
bool hasOldContext;
#ifdef _WIN32
hasOldContext =
(m_currentContext.first != nullptr && m_currentContext.second != nullptr);
#else
hasOldContext = m_currentContext != nullptr;
#endif
if (hasOldContext) {
int ret = l_contexts.erase(m_currentContext);
if (ret)
TGLDisplayListsManager::instance()->releaseContext(m_currentContext);
}
// then, register context and the space Id correspondent to it.
int displayListId;
if (TApp::instance()->getMainWindow() &&
TApp::instance()->getMainWindow()->isAncestorOf(this) &&
QThread::currentThread() == qGuiApp->thread()) {
// obtain displaySpaceId for main thread
if (l_mainDisplayListsSpaceId == -1)
l_mainDisplayListsSpaceId =
TGLDisplayListsManager::instance()->storeProxy(new DummyProxy);
displayListId = l_mainDisplayListsSpaceId;
}
// for the other cases (such as for floating viewer), it can't share the
// context so
// obtain different id
else
displayListId =
TGLDisplayListsManager::instance()->storeProxy(new DummyProxy);
TGlContext tglContext(tglGetCurrentContext());
TGLDisplayListsManager::instance()->attachContext(displayListId, tglContext);
l_contexts.insert(tglContext);
m_currentContext = tglContext;
}
|
#ifndef CL_GAMEOFLIFE_CLASS_H
#define CL_GAMEOFLIFE_CLASS_H
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl.hpp>
#else
#include <CL/cl.hpp>
#endif
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <time.h>
#include <stdexcept>
#include <cv.h>
#include <highgui.h>
class CLGameOfLife {
public:
// Constructeurs et destructeur
// de la classe OpenCL
CLGameOfLife(int width, int height, int nbPoint); // constructeur
~CLGameOfLife(void); // destructeur
// fonction
void run(int ms);
void generateDot(int nbPoint);
void makeKernel(void);
void writeMemory(void);
void execKernel(void);
void readMemory(void);
private:
// platform model
std::vector<cl::Platform> platforms;
// contexte d'exécution
cl::Context context;
// propriétés du contexte
std::vector<cl_context_properties> context_properties;
// périphériques du contexte
std::vector<cl::Device> context_devices;
// identifiant du GPU
cl_device_type id_GPU;
// queue d'exécution
cl::CommandQueue queue;
// programme
cl::Program program;
// kernel
cl::Kernel kernel;
// buffer mémoire
cl::Buffer inputImg;
cl::Buffer imgWidth;
cl::Buffer imgSize;
cl::Buffer outputImg;
// gestion d'événement
cl::Event event;
//gestion d'erreur
cl_int err;
// Matrice de l'image
cv::Mat img;
// Taille de la matrice
int * matSize;
};
#endif
|
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"
#include <ctype.h>
#include <stdlib.h>
#include <float.h>
#include <errno.h>
#include <tools/date.hxx>
#include <tools/debug.hxx>
#include <rtl/math.hxx>
#include <unotools/charclass.hxx>
#include <unotools/calendarwrapper.hxx>
#include <unotools/localedatawrapper.hxx>
#include <com/sun/star/i18n/CalendarFieldIndex.hpp>
#include <unotools/digitgroupingiterator.hxx>
#include <svl/zforlist.hxx> // NUMBERFORMAT_XXX
#include "zforscan.hxx"
#include <svl/zformat.hxx>
#define _ZFORFIND_CXX
#include "zforfind.hxx"
#undef _ZFORFIND_CXX
#ifndef DBG_UTIL
#define NF_TEST_CALENDAR 0
#else
#define NF_TEST_CALENDAR 0
#endif
#if NF_TEST_CALENDAR
#include <comphelper/processfactory.hxx>
#include <com/sun/star/i18n/XExtendedCalendar.hpp>
#endif
const sal_uInt8 ImpSvNumberInputScan::nMatchedEndString = 0x01;
const sal_uInt8 ImpSvNumberInputScan::nMatchedMidString = 0x02;
const sal_uInt8 ImpSvNumberInputScan::nMatchedStartString = 0x04;
const sal_uInt8 ImpSvNumberInputScan::nMatchedVirgin = 0x08;
const sal_uInt8 ImpSvNumberInputScan::nMatchedUsedAsReturn = 0x10;
/* It is not clear how we want timezones to be handled. Convert them to local
* time isn't wanted, as it isn't done in any other place and timezone
* information isn't stored anywhere. Ignoring them and pretending local time
* may be wrong too and might not be what the user expects. Keep the input as
* string so that no information is lost.
* Anyway, defining NF_RECOGNIZE_ISO8601_TIMEZONES to 1 would be the way how it
* would work, together with the nTimezonePos handling in GetTimeRef(). */
#define NF_RECOGNIZE_ISO8601_TIMEZONES 0
//---------------------------------------------------------------------------
// Konstruktor
ImpSvNumberInputScan::ImpSvNumberInputScan( SvNumberFormatter* pFormatterP )
:
pUpperMonthText( NULL ),
pUpperAbbrevMonthText( NULL ),
pUpperDayText( NULL ),
pUpperAbbrevDayText( NULL )
{
pFormatter = pFormatterP;
pNullDate = new Date(30,12,1899);
nYear2000 = SvNumberFormatter::GetYear2000Default();
Reset();
ChangeIntl();
}
//---------------------------------------------------------------------------
// Destruktor
ImpSvNumberInputScan::~ImpSvNumberInputScan()
{
Reset();
delete pNullDate;
delete [] pUpperMonthText;
delete [] pUpperAbbrevMonthText;
delete [] pUpperDayText;
delete [] pUpperAbbrevDayText;
}
//---------------------------------------------------------------------------
// Reset
void ImpSvNumberInputScan::Reset()
{
#if 0
// ER 16.06.97 18:56 Vorbelegung erfolgt jetzt in NumberStringDivision,
// wozu immer alles loeschen wenn einiges wieder benutzt oder gar nicht
// gebraucht wird..
for (sal_uInt16 i = 0; i < SV_MAX_ANZ_INPUT_STRINGS; i++)
{
sStrArray[i].Erase();
nNums[i] = SV_MAX_ANZ_INPUT_STRINGS-1;
IsNum[i] = sal_False;
}
#endif
nMonth = 0;
nMonthPos = 0;
nTimePos = 0;
nSign = 0;
nESign = 0;
nDecPos = 0;
nNegCheck = 0;
nAnzStrings = 0;
nAnzNums = 0;
nThousand = 0;
eScannedType = NUMBERFORMAT_UNDEFINED;
nAmPm = 0;
nPosThousandString = 0;
nLogical = 0;
nStringScanNumFor = 0;
nStringScanSign = 0;
nMatchedAllStrings = nMatchedVirgin;
nMayBeIso8601 = 0;
nTimezonePos = 0;
}
//---------------------------------------------------------------------------
//
// static
inline sal_Bool ImpSvNumberInputScan::MyIsdigit( sal_Unicode c )
{
// If the input string wouldn't be converted using TransformInput() we'd
// to use something similar to the following and to adapt many places.
#if 0
// use faster isdigit() if possible
if ( c < 128 )
return isdigit( (unsigned char) c ) != 0;
if ( c < 256 )
return sal_False;
String aTmp( c );
return pFormatter->GetCharClass()->isDigit( aTmp, 0 );
#else
return c < 128 && isdigit( (unsigned char) c );
#endif
}
//---------------------------------------------------------------------------
//
void ImpSvNumberInputScan::TransformInput( String& rStr )
{
xub_StrLen nPos, nLen;
for ( nPos = 0, nLen = rStr.Len(); nPos < nLen; ++nPos )
{
if ( 256 <= rStr.GetChar( nPos ) &&
pFormatter->GetCharClass()->isDigit( rStr, nPos ) )
break;
}
if ( nPos < nLen )
rStr = pFormatter->GetNatNum()->getNativeNumberString( rStr,
pFormatter->GetLocale(), 0 );
}
//---------------------------------------------------------------------------
// StringToDouble
//
// Only simple unsigned floating point values without any error detection,
// decimal separator has to be '.'
double ImpSvNumberInputScan::StringToDouble( const String& rStr, sal_Bool bForceFraction )
{
double fNum = 0.0;
double fFrac = 0.0;
int nExp = 0;
xub_StrLen nPos = 0;
xub_StrLen nLen = rStr.Len();
sal_Bool bPreSep = !bForceFraction;
while (nPos < nLen)
{
if (rStr.GetChar(nPos) == '.')
bPreSep = sal_False;
else if (bPreSep)
fNum = fNum * 10.0 + (double) (rStr.GetChar(nPos) - '0');
else
{
fFrac = fFrac * 10.0 + (double) (rStr.GetChar(nPos) - '0');
--nExp;
}
nPos++;
}
if ( fFrac )
return fNum + ::rtl::math::pow10Exp( fFrac, nExp );
return fNum;
}
//---------------------------------------------------------------------------
// NextNumberStringSymbol
//
// Zerlegt die Eingabe in Zahlen und Strings fuer die weitere
// Verarbeitung (Turing-Maschine).
//---------------------------------------------------------------------------
// Ausgangs Zustand = GetChar
//---------------+-------------------+-----------------------+---------------
// Alter Zustand | gelesenes Zeichen | Aktion | Neuer Zustand
//---------------+-------------------+-----------------------+---------------
// GetChar | Ziffer | Symbol=Zeichen | GetValue
// | Sonst | Symbol=Zeichen | GetString
//---------------|-------------------+-----------------------+---------------
// GetValue | Ziffer | Symbol=Symbol+Zeichen | GetValue
// | Sonst | Dec(CharPos) | Stop
//---------------+-------------------+-----------------------+---------------
// GetString | Ziffer | Dec(CharPos) | Stop
// | Sonst | Symbol=Symbol+Zeichen | GetString
//---------------+-------------------+-----------------------+---------------
enum ScanState // States der Turing-Maschine
{
SsStop = 0,
SsStart = 1,
SsGetValue = 2,
SsGetString = 3
};
sal_Bool ImpSvNumberInputScan::NextNumberStringSymbol(
const sal_Unicode*& pStr,
String& rSymbol )
{
sal_Bool isNumber = sal_False;
sal_Unicode cToken;
ScanState eState = SsStart;
const sal_Unicode* pHere = pStr;
xub_StrLen nChars = 0;
while ( ((cToken = *pHere) != 0) && eState != SsStop)
{
pHere++;
switch (eState)
{
case SsStart:
if ( MyIsdigit( cToken ) )
{
eState = SsGetValue;
isNumber = sal_True;
}
else
eState = SsGetString;
nChars++;
break;
case SsGetValue:
if ( MyIsdigit( cToken ) )
nChars++;
else
{
eState = SsStop;
pHere--;
}
break;
case SsGetString:
if ( !MyIsdigit( cToken ) )
nChars++;
else
{
eState = SsStop;
pHere--;
}
break;
default:
break;
} // switch
} // while
if ( nChars )
rSymbol.Assign( pStr, nChars );
else
rSymbol.Erase();
pStr = pHere;
return isNumber;
}
//---------------------------------------------------------------------------
// SkipThousands
// FIXME: should be grouping; it is only used though in case nAnzStrings is
// near SV_MAX_ANZ_INPUT_STRINGS, in NumberStringDivision().
sal_Bool ImpSvNumberInputScan::SkipThousands(
const sal_Unicode*& pStr,
String& rSymbol )
{
sal_Bool res = sal_False;
sal_Unicode cToken;
const String& rThSep = pFormatter->GetNumThousandSep();
const sal_Unicode* pHere = pStr;
ScanState eState = SsStart;
xub_StrLen nCounter = 0; // counts 3 digits
while ( ((cToken = *pHere) != 0) && eState != SsStop)
{
pHere++;
switch (eState)
{
case SsStart:
if ( StringPtrContains( rThSep, pHere-1, 0 ) )
{
nCounter = 0;
eState = SsGetValue;
pHere += rThSep.Len()-1;
}
else
{
eState = SsStop;
pHere--;
}
break;
case SsGetValue:
if ( MyIsdigit( cToken ) )
{
rSymbol += cToken;
nCounter++;
if (nCounter == 3)
{
eState = SsStart;
res = sal_True; // .000 combination found
}
}
else
{
eState = SsStop;
pHere--;
}
break;
default:
break;
} // switch
} // while
if (eState == SsGetValue) // break witth less than 3 digits
{
if ( nCounter )
rSymbol.Erase( rSymbol.Len() - nCounter, nCounter );
pHere -= nCounter + rThSep.Len(); // put back ThSep also
}
pStr = pHere;
return res;
}
//---------------------------------------------------------------------------
// NumberStringDivision
void ImpSvNumberInputScan::NumberStringDivision( const String& rString )
{
const sal_Unicode* pStr = rString.GetBuffer();
const sal_Unicode* const pEnd = pStr + rString.Len();
while ( pStr < pEnd && nAnzStrings < SV_MAX_ANZ_INPUT_STRINGS )
{
if ( NextNumberStringSymbol( pStr, sStrArray[nAnzStrings] ) )
{ // Zahl
IsNum[nAnzStrings] = sal_True;
nNums[nAnzNums] = nAnzStrings;
nAnzNums++;
if (nAnzStrings >= SV_MAX_ANZ_INPUT_STRINGS - 7 &&
nPosThousandString == 0) // nur einmal
if ( SkipThousands( pStr, sStrArray[nAnzStrings] ) )
nPosThousandString = nAnzStrings;
}
else
{
IsNum[nAnzStrings] = sal_False;
}
nAnzStrings++;
}
}
//---------------------------------------------------------------------------
// Whether rString contains rWhat at nPos
sal_Bool ImpSvNumberInputScan::StringContainsImpl( const String& rWhat,
const String& rString, xub_StrLen nPos )
{
if ( nPos + rWhat.Len() <= rString.Len() )
return StringPtrContainsImpl( rWhat, rString.GetBuffer(), nPos );
return sal_False;
}
//---------------------------------------------------------------------------
// Whether pString contains rWhat at nPos
sal_Bool ImpSvNumberInputScan::StringPtrContainsImpl( const String& rWhat,
const sal_Unicode* pString, xub_StrLen nPos )
{
if ( rWhat.Len() == 0 )
return sal_False;
const sal_Unicode* pWhat = rWhat.GetBuffer();
const sal_Unicode* const pEnd = pWhat + rWhat.Len();
const sal_Unicode* pStr = pString + nPos;
while ( pWhat < pEnd )
{
if ( *pWhat != *pStr )
return sal_False;
pWhat++;
pStr++;
}
return sal_True;
}
//---------------------------------------------------------------------------
// SkipChar
//
// ueberspringt genau das angegebene Zeichen
inline sal_Bool ImpSvNumberInputScan::SkipChar( sal_Unicode c, const String& rString,
xub_StrLen& nPos )
{
if ((nPos < rString.Len()) && (rString.GetChar(nPos) == c))
{
nPos++;
return sal_True;
}
return sal_False;
}
//---------------------------------------------------------------------------
// SkipBlanks
//
// Ueberspringt Leerzeichen
inline void ImpSvNumberInputScan::SkipBlanks( const String& rString,
xub_StrLen& nPos )
{
if ( nPos < rString.Len() )
{
const sal_Unicode* p = rString.GetBuffer() + nPos;
while ( *p == ' ' )
{
nPos++;
p++;
}
}
}
//---------------------------------------------------------------------------
// SkipString
//
// jump over rWhat in rString at nPos
inline sal_Bool ImpSvNumberInputScan::SkipString( const String& rWhat,
const String& rString, xub_StrLen& nPos )
{
if ( StringContains( rWhat, rString, nPos ) )
{
nPos = nPos + rWhat.Len();
return sal_True;
}
return sal_False;
}
//---------------------------------------------------------------------------
// GetThousandSep
//
// recognizes exactly ,111 in {3} and {3,2} or ,11 in {3,2} grouping
inline sal_Bool ImpSvNumberInputScan::GetThousandSep(
const String& rString,
xub_StrLen& nPos,
sal_uInt16 nStringPos )
{
const String& rSep = pFormatter->GetNumThousandSep();
// Is it an ordinary space instead of a non-breaking space?
bool bSpaceBreak = rSep.GetChar(0) == 0xa0 && rString.GetChar(0) == 0x20 &&
rSep.Len() == 1 && rString.Len() == 1;
if (!( (rString == rSep || bSpaceBreak) // nothing else
&& nStringPos < nAnzStrings - 1 // safety first!
&& IsNum[nStringPos+1] )) // number follows
return sal_False; // no? => out
utl::DigitGroupingIterator aGrouping(
pFormatter->GetLocaleData()->getDigitGrouping());
// Match ,### in {3} or ,## in {3,2}
/* FIXME: this could be refined to match ,## in {3,2} only if ,##,## or
* ,##,### and to match ,### in {3,2} only if it's the last. However,
* currently there is no track kept where group separators occur. In {3,2}
* #,###,### and #,##,## would be valid input, which maybe isn't even bad
* for #,###,###. Other combinations such as #,###,## maybe not. */
xub_StrLen nLen = sStrArray[nStringPos+1].Len();
if (nLen == aGrouping.get() // with 3 (or so) digits
|| nLen == aGrouping.advance().get() // or with 2 (or 3 or so) digits
|| nPosThousandString == nStringPos+1 // or concatenated
)
{
nPos = nPos + rSep.Len();
return sal_True;
}
return sal_False;
}
//---------------------------------------------------------------------------
// GetLogical
//
// Conversion of text to logial value
// "sal_True" => 1:
// "sal_False"=> -1:
// else => 0:
short ImpSvNumberInputScan::GetLogical( const String& rString )
{
short res;
const ImpSvNumberformatScan* pFS = pFormatter->GetFormatScanner();
if ( rString == pFS->GetTrueString() )
res = 1;
else if ( rString == pFS->GetFalseString() )
res = -1;
else
res = 0;
return res;
}
//---------------------------------------------------------------------------
// GetMonth
//
// Converts a string containing a month name (JAN, January) at nPos into the
// month number (negative if abbreviated), returns 0 if nothing found
short ImpSvNumberInputScan::GetMonth( const String& rString, xub_StrLen& nPos )
{
// #102136# The correct English form of month September abbreviated is
// SEPT, but almost every data contains SEP instead.
static const String aSeptCorrect( RTL_CONSTASCII_USTRINGPARAM( "SEPT" ) );
static const String aSepShortened( RTL_CONSTASCII_USTRINGPARAM( "SEP" ) );
short res = 0; // no month found
if (rString.Len() > nPos) // only if needed
{
if ( !bTextInitialized )
InitText();
sal_Int16 nMonths = pFormatter->GetCalendar()->getNumberOfMonthsInYear();
for ( sal_Int16 i = 0; i < nMonths; i++ )
{
if ( StringContains( pUpperMonthText[i], rString, nPos ) )
{ // full names first
nPos = nPos + pUpperMonthText[i].Len();
res = i+1;
break; // for
}
else if ( StringContains( pUpperAbbrevMonthText[i], rString, nPos ) )
{ // abbreviated
nPos = nPos + pUpperAbbrevMonthText[i].Len();
res = sal::static_int_cast< short >(-(i+1)); // negative
break; // for
}
else if ( i == 8 && pUpperAbbrevMonthText[i] == aSeptCorrect &&
StringContains( aSepShortened, rString, nPos ) )
{ // #102136# SEPT/SEP
nPos = nPos + aSepShortened.Len();
res = sal::static_int_cast< short >(-(i+1)); // negative
break; // for
}
}
}
return res;
}
//---------------------------------------------------------------------------
// GetDayOfWeek
//
// Converts a string containing a DayOfWeek name (Mon, Monday) at nPos into the
// DayOfWeek number + 1 (negative if abbreviated), returns 0 if nothing found
int ImpSvNumberInputScan::GetDayOfWeek( const String& rString, xub_StrLen& nPos )
{
int res = 0; // no day found
if (rString.Len() > nPos) // only if needed
{
if ( !bTextInitialized )
InitText();
sal_Int16 nDays = pFormatter->GetCalendar()->getNumberOfDaysInWeek();
for ( sal_Int16 i = 0; i < nDays; i++ )
{
if ( StringContains( pUpperDayText[i], rString, nPos ) )
{ // full names first
nPos = nPos + pUpperDayText[i].Len();
res = i + 1;
break; // for
}
if ( StringContains( pUpperAbbrevDayText[i], rString, nPos ) )
{ // abbreviated
nPos = nPos + pUpperAbbrevDayText[i].Len();
res = -(i + 1); // negative
break; // for
}
}
}
return res;
}
//---------------------------------------------------------------------------
// GetCurrency
//
// Lesen eines Waehrungssysmbols
// '$' => sal_True
// sonst => sal_False
sal_Bool ImpSvNumberInputScan::GetCurrency( const String& rString, xub_StrLen& nPos,
const SvNumberformat* pFormat )
{
if ( rString.Len() > nPos )
{
if ( !aUpperCurrSymbol.Len() )
{ // if no format specified the currency of the initialized formatter
LanguageType eLang = (pFormat ? pFormat->GetLanguage() :
pFormatter->GetLanguage());
aUpperCurrSymbol = pFormatter->GetCharClass()->upper(
SvNumberFormatter::GetCurrencyEntry( eLang ).GetSymbol() );
}
if ( StringContains( aUpperCurrSymbol, rString, nPos ) )
{
nPos = nPos + aUpperCurrSymbol.Len();
return sal_True;
}
if ( pFormat )
{
String aSymbol, aExtension;
if ( pFormat->GetNewCurrencySymbol( aSymbol, aExtension ) )
{
if ( aSymbol.Len() <= rString.Len() - nPos )
{
pFormatter->GetCharClass()->toUpper( aSymbol );
if ( StringContains( aSymbol, rString, nPos ) )
{
nPos = nPos + aSymbol.Len();
return sal_True;
}
}
}
}
}
return sal_False;
}
//---------------------------------------------------------------------------
// GetTimeAmPm
//
// Lesen des Zeitsymbols (AM od. PM) f. kurze Zeitangabe
//
// Rueckgabe:
// "AM" od. "PM" => sal_True
// sonst => sal_False
//
// nAmPos:
// "AM" => 1
// "PM" => -1
// sonst => 0
sal_Bool ImpSvNumberInputScan::GetTimeAmPm( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const CharClass* pChr = pFormatter->GetCharClass();
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
if ( StringContains( pChr->upper( pLoc->getTimeAM() ), rString, nPos ) )
{
nAmPm = 1;
nPos = nPos + pLoc->getTimeAM().Len();
return sal_True;
}
else if ( StringContains( pChr->upper( pLoc->getTimePM() ), rString, nPos ) )
{
nAmPm = -1;
nPos = nPos + pLoc->getTimePM().Len();
return sal_True;
}
}
return sal_False;
}
//---------------------------------------------------------------------------
// GetDecSep
//
// Lesen eines Dezimaltrenners (',')
// ',' => sal_True
// sonst => sal_False
inline sal_Bool ImpSvNumberInputScan::GetDecSep( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const String& rSep = pFormatter->GetNumDecimalSep();
if ( rString.Equals( rSep, nPos, rSep.Len() ) )
{
nPos = nPos + rSep.Len();
return sal_True;
}
}
return sal_False;
}
//---------------------------------------------------------------------------
// read a hundredth seconds separator
inline sal_Bool ImpSvNumberInputScan::GetTime100SecSep( const String& rString, xub_StrLen& nPos )
{
if ( rString.Len() > nPos )
{
const String& rSep = pFormatter->GetLocaleData()->getTime100SecSep();
if ( rString.Equals( rSep, nPos, rSep.Len() ) )
{
nPos = nPos + rSep.Len();
return sal_True;
}
}
return sal_False;
}
//---------------------------------------------------------------------------
// GetSign
//
// Lesen eines Vorzeichens, auch Klammer !?!
// '+' => 1
// '-' => -1
// '(' => -1, nNegCheck = 1
// sonst => 0
int ImpSvNumberInputScan::GetSign( const String& rString, xub_StrLen& nPos )
{
if (rString.Len() > nPos)
switch (rString.GetChar(nPos))
{
case '+':
nPos++;
return 1;
case '(': // '(' aehnlich wie '-' ?!?
nNegCheck = 1;
//! fallthru
case '-':
nPos++;
return -1;
default:
break;
}
return 0;
}
//---------------------------------------------------------------------------
// GetESign
//
// Lesen eines Vorzeichens, gedacht fuer Exponent ?!?
// '+' => 1
// '-' => -1
// sonst => 0
short ImpSvNumberInputScan::GetESign( const String& rString, xub_StrLen& nPos )
{
if (rString.Len() > nPos)
switch (rString.GetChar(nPos))
{
case '+':
nPos++;
return 1;
case '-':
nPos++;
return -1;
default:
break;
}
return 0;
}
//---------------------------------------------------------------------------
// GetNextNumber
//
// i counts string portions, j counts numbers thereof.
// It should had been called SkipNumber instead.
inline sal_Bool ImpSvNumberInputScan::GetNextNumber( sal_uInt16& i, sal_uInt16& j )
{
if ( i < nAnzStrings && IsNum[i] )
{
j++;
i++;
return sal_True;
}
return sal_False;
}
//---------------------------------------------------------------------------
// GetTimeRef
void ImpSvNumberInputScan::GetTimeRef(
double& fOutNumber,
sal_uInt16 nIndex, // j-value of the first numeric time part of input, default 0
sal_uInt16 nAnz ) // count of numeric time parts
{
sal_uInt16 nHour;
sal_uInt16 nMinute = 0;
sal_uInt16 nSecond = 0;
double fSecond100 = 0.0;
sal_uInt16 nStartIndex = nIndex;
if (nTimezonePos)
{
// find first timezone number index and adjust count
for (sal_uInt16 j=0; j<nAnzNums; ++j)
{
if (nNums[j] == nTimezonePos)
{
// nAnz is not total count, but count of time relevant strings.
if (nStartIndex < j && j - nStartIndex < nAnz)
nAnz = j - nStartIndex;
break; // for
}
}
}
if (nDecPos == 2 && (nAnz == 3 || nAnz == 2)) // 20:45.5 or 45.5
nHour = 0;
else if (nIndex - nStartIndex < nAnz)
nHour = (sal_uInt16) sStrArray[nNums[nIndex++]].ToInt32();
else
{
nHour = 0;
DBG_ERRORFILE( "ImpSvNumberInputScan::GetTimeRef: bad number index");
}
if (nDecPos == 2 && nAnz == 2) // 45.5
nMinute = 0;
else if (nIndex - nStartIndex < nAnz)
nMinute = (sal_uInt16) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
nSecond = (sal_uInt16) sStrArray[nNums[nIndex++]].ToInt32();
if (nIndex - nStartIndex < nAnz)
fSecond100 = StringToDouble( sStrArray[nNums[nIndex]], sal_True );
if (nAmPm == -1 && nHour != 12) // PM
nHour += 12;
else if (nAmPm == 1 && nHour == 12) // 12 AM
nHour = 0;
fOutNumber = ((double)nHour*3600 +
(double)nMinute*60 +
(double)nSecond +
fSecond100)/86400.0;
}
//---------------------------------------------------------------------------
// ImplGetDay
sal_uInt16 ImpSvNumberInputScan::ImplGetDay( sal_uInt16 nIndex )
{
sal_uInt16 nRes = 0;
if (sStrArray[nNums[nIndex]].Len() <= 2)
{
sal_uInt16 nNum = (sal_uInt16) sStrArray[nNums[nIndex]].ToInt32();
if (nNum <= 31)
nRes = nNum;
}
return nRes;
}
//---------------------------------------------------------------------------
// ImplGetMonth
sal_uInt16 ImpSvNumberInputScan::ImplGetMonth( sal_uInt16 nIndex )
{
// preset invalid month number
sal_uInt16 nRes = pFormatter->GetCalendar()->getNumberOfMonthsInYear();
if (sStrArray[nNums[nIndex]].Len() <= 2)
{
sal_uInt16 nNum = (sal_uInt16) sStrArray[nNums[nIndex]].ToInt32();
if ( 0 < nNum && nNum <= nRes )
nRes = nNum - 1; // zero based for CalendarFieldIndex::MONTH
}
return nRes;
}
//---------------------------------------------------------------------------
// ImplGetYear
//
// 30 -> 1930, 29 -> 2029, oder 56 -> 1756, 55 -> 1855, ...
sal_uInt16 ImpSvNumberInputScan::ImplGetYear( sal_uInt16 nIndex )
{
sal_uInt16 nYear = 0;
if (sStrArray[nNums[nIndex]].Len() <= 4)
{
nYear = (sal_uInt16) sStrArray[nNums[nIndex]].ToInt32();
nYear = SvNumberFormatter::ExpandTwoDigitYear( nYear, nYear2000 );
}
return nYear;
}
//---------------------------------------------------------------------------
bool ImpSvNumberInputScan::MayBeIso8601()
{
if (nMayBeIso8601 == 0)
{
if (nAnzNums >= 3 && nNums[0] < nAnzStrings &&
sStrArray[nNums[0]].ToInt32() > 31)
nMayBeIso8601 = 1;
else
nMayBeIso8601 = 2;
}
return nMayBeIso8601 == 1;
}
//---------------------------------------------------------------------------
// GetDateRef
sal_Bool ImpSvNumberInputScan::GetDateRef( double& fDays, sal_uInt16& nCounter,
const SvNumberformat* pFormat )
{
using namespace ::com::sun::star::i18n;
NfEvalDateFormat eEDF;
int nFormatOrder;
if ( pFormat && ((pFormat->GetType() & NUMBERFORMAT_DATE) == NUMBERFORMAT_DATE) )
{
eEDF = pFormatter->GetEvalDateFormat();
switch ( eEDF )
{
case NF_EVALDATEFORMAT_INTL :
case NF_EVALDATEFORMAT_FORMAT :
nFormatOrder = 1; // only one loop
break;
default:
nFormatOrder = 2;
if ( nMatchedAllStrings )
eEDF = NF_EVALDATEFORMAT_FORMAT_INTL;
// we have a complete match, use it
}
}
else
{
eEDF = NF_EVALDATEFORMAT_INTL;
nFormatOrder = 1;
}
sal_Bool res = sal_True;
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
CalendarWrapper* pCal = pFormatter->GetCalendar();
for ( int nTryOrder = 1; nTryOrder <= nFormatOrder; nTryOrder++ )
{
pCal->setGregorianDateTime( Date() ); // today
String aOrgCalendar; // empty => not changed yet
DateFormat DateFmt;
sal_Bool bFormatTurn;
switch ( eEDF )
{
case NF_EVALDATEFORMAT_INTL :
bFormatTurn = sal_False;
DateFmt = pLoc->getDateFormat();
break;
case NF_EVALDATEFORMAT_FORMAT :
bFormatTurn = sal_True;
DateFmt = pFormat->GetDateOrder();
break;
case NF_EVALDATEFORMAT_INTL_FORMAT :
if ( nTryOrder == 1 )
{
bFormatTurn = sal_False;
DateFmt = pLoc->getDateFormat();
}
else
{
bFormatTurn = sal_True;
DateFmt = pFormat->GetDateOrder();
}
break;
case NF_EVALDATEFORMAT_FORMAT_INTL :
if ( nTryOrder == 2 )
{
bFormatTurn = sal_False;
DateFmt = pLoc->getDateFormat();
}
else
{
bFormatTurn = sal_True;
DateFmt = pFormat->GetDateOrder();
}
break;
default:
DBG_ERROR( "ImpSvNumberInputScan::GetDateRef: unknown NfEvalDateFormat" );
DateFmt = YMD;
bFormatTurn = sal_False;
}
if ( bFormatTurn )
{
#if 0
/* TODO:
We are currently not able to fully support a switch to another calendar during
input for the following reasons:
1. We do have a problem if both (locale's default and format's) calendars
define the same YMD order and use the same date separator, there is no way
to distinguish between them if the input results in valid calendar input for
both calendars. How to solve? Would NfEvalDateFormat be sufficient? Should
it always be set to NF_EVALDATEFORMAT_FORMAT_INTL and thus the format's
calendar be preferred? This could be confusing if a Calc cell was formatted
different to the locale's default and has no content yet, then the user has
no clue about the format or calendar being set.
2. In Calc cell edit mode a date is always displayed and edited using the
default edit format of the default calendar (normally being Gregorian). If
input was ambiguous due to issue #1 we'd need a mechanism to tell that a
date was edited and not newly entered. Not feasible. Otherwise we'd need a
mechanism to use a specific edit format with a specific calendar according
to the format set.
3. For some calendars like Japanese Gengou we'd need era input, which isn't
implemented at all. Though this is a rare and special case, forcing a
calendar dependent edit format as suggested in item #2 might require era
input, if it shouldn't result in a fallback to Gregorian calendar.
4. Last and least: the GetMonth() method currently only matches month names of
the default calendar. Alternating month names of the actual format's
calendar would have to be implemented. No problem.
*/
if ( pFormat->IsOtherCalendar( nStringScanNumFor ) )
pFormat->SwitchToOtherCalendar( aOrgCalendar, fOrgDateTime );
else
pFormat->SwitchToSpecifiedCalendar( aOrgCalendar, fOrgDateTime,
nStringScanNumFor );
#endif
}
res = sal_True;
nCounter = 0;
// For incomplete dates, always assume first day of month if not specified.
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
switch (nAnzNums) // count of numbers in string
{
case 0: // none
if (nMonthPos) // only month (Jan)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
else
res = sal_False;
break;
case 1: // only one number
nCounter = 1;
switch (nMonthPos) // where is the month
{
case 0: // not found => only day entered
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case 1: // month at the beginning (Jan 01)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case MDY:
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = sal_False;
break;
}
break;
case 3: // month at the end (10 Jan)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = sal_False;
break;
}
break;
default:
res = sal_False;
break;
} // switch (nMonthPos)
break;
case 2: // 2 numbers
nCounter = 2;
switch (nMonthPos) // where is the month
{
case 0: // not found
{
bool bHadExact;
sal_uInt32 nExactDateOrder = (bFormatTurn ? pFormat->GetExactDateOrder() : 0);
if ( 0xff < nExactDateOrder && nExactDateOrder <= 0xffff )
{ // formatted as date and exactly 2 parts
bHadExact = true;
switch ( (nExactDateOrder >> 8) & 0xff )
{
case 'Y':
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
case 'M':
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
break;
case 'D':
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
break;
default:
bHadExact = false;
}
switch ( nExactDateOrder & 0xff )
{
case 'Y':
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case 'M':
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
break;
case 'D':
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
break;
default:
bHadExact = false;
}
}
else
bHadExact = false;
if ( !bHadExact || !pCal->isValid() )
{
if ( !bHadExact && nExactDateOrder )
pCal->setGregorianDateTime( Date() ); // reset today
switch (DateFmt)
{
case MDY:
// M D
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( !pCal->isValid() ) // 2nd try
{ // M Y
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
}
break;
case DMY:
// D M
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
if ( !pCal->isValid() ) // 2nd try
{ // M Y
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
}
break;
case YMD:
// M D
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( !pCal->isValid() ) // 2nd try
{ // Y M
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, 1 );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
}
break;
default:
res = sal_False;
break;
}
}
}
break;
case 1: // month at the beginning (Jan 01 01)
{
// The input is valid as MDY in almost any
// constellation, there is no date order (M)YD except if
// set in a format applied.
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
sal_uInt32 nExactDateOrder = (bFormatTurn ? pFormat->GetExactDateOrder() : 0);
if ((((nExactDateOrder >> 8) & 0xff) == 'Y') && ((nExactDateOrder & 0xff) == 'D'))
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
}
else
{
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
}
}
break;
case 2: // month in the middle (10 Jan 94)
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case MDY: // yes, "10-Jan-94" is valid
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = sal_False;
break;
}
break;
default: // else, e.g. month at the end (94 10 Jan)
res = sal_False;
break;
} // switch (nMonthPos)
break;
default: // more than two numbers (31.12.94 8:23) (31.12. 8:23)
switch (nMonthPos) // where is the month
{
case 0: // not found
{
nCounter = 3;
if ( nTimePos > 1 )
{ // find first time number index (should only be 3 or 2 anyway)
for ( sal_uInt16 j = 0; j < nAnzNums; j++ )
{
if ( nNums[j] == nTimePos - 2 )
{
nCounter = j;
break; // for
}
}
}
// ISO 8601 yyyy-mm-dd forced recognition
DateFormat eDF = (MayBeIso8601() ? YMD : DateFmt);
switch (eDF)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(0) );
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(2) );
break;
case YMD:
if ( nCounter > 2 )
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(2) );
pCal->setValue( CalendarFieldIndex::MONTH, ImplGetMonth(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = sal_False;
break;
}
}
break;
case 1: // month at the beginning (Jan 01 01 8:23)
nCounter = 2;
switch (DateFmt)
{
case MDY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
default:
res = sal_False;
break;
}
break;
case 2: // month in the middle (10 Jan 94 8:23)
nCounter = 2;
pCal->setValue( CalendarFieldIndex::MONTH, Abs(nMonth)-1 );
switch (DateFmt)
{
case DMY:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(0) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(1) );
break;
case YMD:
pCal->setValue( CalendarFieldIndex::DAY_OF_MONTH, ImplGetDay(1) );
pCal->setValue( CalendarFieldIndex::YEAR, ImplGetYear(0) );
break;
default:
res = sal_False;
break;
}
break;
default: // else, e.g. month at the end (94 10 Jan 8:23)
nCounter = 2;
res = sal_False;
break;
} // switch (nMonthPos)
break;
} // switch (nAnzNums)
if ( res && pCal->isValid() )
{
double fDiff = DateTime(*pNullDate) - pCal->getEpochStart();
fDays = ::rtl::math::approxFloor( pCal->getLocalDateTime() );
fDays -= fDiff;
nTryOrder = nFormatOrder; // break for
}
else
res = sal_False;
if ( aOrgCalendar.Len() )
pCal->loadCalendar( aOrgCalendar, pLoc->getLocale() ); // restore calendar
#if NF_TEST_CALENDAR
{
using namespace ::com::sun::star;
struct entry { const char* lan; const char* cou; const char* cal; };
const entry cals[] = {
{ "en", "US", "gregorian" },
{ "ar", "TN", "hijri" },
{ "he", "IL", "jewish" },
{ "ja", "JP", "gengou" },
{ "ko", "KR", "hanja_yoil" },
{ "th", "TH", "buddhist" },
{ "zh", "TW", "ROC" },
{0,0,0}
};
lang::Locale aLocale;
sal_Bool bValid;
sal_Int16 nDay, nMyMonth, nYear, nHour, nMinute, nSecond;
sal_Int16 nDaySet, nMonthSet, nYearSet, nHourSet, nMinuteSet, nSecondSet;
sal_Int16 nZO, nDST1, nDST2, nDST, nZOmillis, nDST1millis, nDST2millis, nDSTmillis;
sal_Int32 nZoneInMillis, nDST1InMillis, nDST2InMillis;
uno::Reference< lang::XMultiServiceFactory > xSMgr =
::comphelper::getProcessServiceFactory();
uno::Reference< ::com::sun::star::i18n::XExtendedCalendar > xCal(
xSMgr->createInstance( ::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.i18n.LocaleCalendar" ) ) ),
uno::UNO_QUERY );
for ( const entry* p = cals; p->lan; ++p )
{
aLocale.Language = ::rtl::OUString::createFromAscii( p->lan );
aLocale.Country = ::rtl::OUString::createFromAscii( p->cou );
xCal->loadCalendar( ::rtl::OUString::createFromAscii( p->cal ),
aLocale );
double nDateTime = 0.0; // 1-Jan-1970 00:00:00
nZO = xCal->getValue( i18n::CalendarFieldIndex::ZONE_OFFSET );
nZOmillis = xCal->getValue( i18n::CalendarFieldIndex::ZONE_OFFSET_SECOND_MILLIS );
nZoneInMillis = static_cast<sal_Int32>(nZO) * 60000 +
(nZO < 0 ? -1 : 1) * static_cast<sal_uInt16>(nZOmillis);
nDST1 = xCal->getValue( i18n::CalendarFieldIndex::DST_OFFSET );
nDST1millis = xCal->getValue( i18n::CalendarFieldIndex::DST_OFFSET_SECOND_MILLIS );
nDST1InMillis = static_cast<sal_Int32>(nDST1) * 60000 +
(nDST1 < 0 ? -1 : 1) * static_cast<sal_uInt16>(nDST1millis);
nDateTime -= (double)(nZoneInMillis + nDST1InMillis) / 1000.0 / 60.0 / 60.0 / 24.0;
xCal->setDateTime( nDateTime );
nDST2 = xCal->getValue( i18n::CalendarFieldIndex::DST_OFFSET );
nDST2millis = xCal->getValue( i18n::CalendarFieldIndex::DST_OFFSET_SECOND_MILLIS );
nDST2InMillis = static_cast<sal_Int32>(nDST2) * 60000 +
(nDST2 < 0 ? -1 : 1) * static_cast<sal_uInt16>(nDST2millis);
if ( nDST1InMillis != nDST2InMillis )
{
nDateTime = 0.0 - (double)(nZoneInMillis + nDST2InMillis) / 1000.0 / 60.0 / 60.0 / 24.0;
xCal->setDateTime( nDateTime );
}
nDaySet = xCal->getValue( i18n::CalendarFieldIndex::DAY_OF_MONTH );
nMonthSet = xCal->getValue( i18n::CalendarFieldIndex::MONTH );
nYearSet = xCal->getValue( i18n::CalendarFieldIndex::YEAR );
nHourSet = xCal->getValue( i18n::CalendarFieldIndex::HOUR );
nMinuteSet = xCal->getValue( i18n::CalendarFieldIndex::MINUTE );
nSecondSet = xCal->getValue( i18n::CalendarFieldIndex::SECOND );
nZO = xCal->getValue( i18n::CalendarFieldIndex::ZONE_OFFSET );
nZOmillis = xCal->getValue( i18n::CalendarFieldIndex::ZONE_OFFSET_SECOND_MILLIS );
nDST = xCal->getValue( i18n::CalendarFieldIndex::DST_OFFSET );
nDSTmillis = xCal->getValue( i18n::CalendarFieldIndex::DST_OFFSET_SECOND_MILLIS );
xCal->setValue( i18n::CalendarFieldIndex::DAY_OF_MONTH, nDaySet );
xCal->setValue( i18n::CalendarFieldIndex::MONTH, nMonthSet );
xCal->setValue( i18n::CalendarFieldIndex::YEAR, nYearSet );
xCal->setValue( i18n::CalendarFieldIndex::HOUR, nHourSet );
xCal->setValue( i18n::CalendarFieldIndex::MINUTE, nMinuteSet );
xCal->setValue( i18n::CalendarFieldIndex::SECOND, nSecondSet );
bValid = xCal->isValid();
nDay = xCal->getValue( i18n::CalendarFieldIndex::DAY_OF_MONTH );
nMyMonth= xCal->getValue( i18n::CalendarFieldIndex::MONTH );
nYear = xCal->getValue( i18n::CalendarFieldIndex::YEAR );
nHour = xCal->getValue( i18n::CalendarFieldIndex::HOUR );
nMinute = xCal->getValue( i18n::CalendarFieldIndex::MINUTE );
nSecond = xCal->getValue( i18n::CalendarFieldIndex::SECOND );
bValid = bValid && nDay == nDaySet && nMyMonth == nMonthSet && nYear ==
nYearSet && nHour == nHourSet && nMinute == nMinuteSet && nSecond
== nSecondSet;
}
}
#endif // NF_TEST_CALENDAR
}
return res;
}
//---------------------------------------------------------------------------
// ScanStartString
//
// ersten String analysieren
// Alles weg => sal_True
// sonst => sal_False
sal_Bool ImpSvNumberInputScan::ScanStartString( const String& rString,
const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
int nDayOfWeek;
// First of all, eat leading blanks
SkipBlanks(rString, nPos);
// Yes, nMatchedAllStrings should know about the sign position
nSign = GetSign(rString, nPos);
if ( nSign ) // sign?
SkipBlanks(rString, nPos);
// #102371# match against format string only if start string is not a sign character
if ( nMatchedAllStrings && !(nSign && rString.Len() == 1) )
{ // Match against format in any case, so later on for a "x1-2-3" input
// we may distinguish between a xy-m-d (or similar) date and a x0-0-0
// format. No sign detection here!
if ( ScanStringNumFor( rString, nPos, pFormat, 0, sal_True ) )
nMatchedAllStrings |= nMatchedStartString;
else
nMatchedAllStrings = 0;
}
if ( GetDecSep(rString, nPos) ) // decimal separator in start string
{
nDecPos = 1;
SkipBlanks(rString, nPos);
}
else if ( GetCurrency(rString, nPos, pFormat) ) // currency (DM 1)?
{
eScannedType = NUMBERFORMAT_CURRENCY; // !!! it IS currency !!!
SkipBlanks(rString, nPos);
if (nSign == 0) // no sign yet
{
nSign = GetSign(rString, nPos);
if ( nSign ) // DM -1
SkipBlanks(rString, nPos);
}
}
else
{
nMonth = GetMonth(rString, nPos);
if ( nMonth ) // month (Jan 1)?
{
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date !!!
nMonthPos = 1; // month at the beginning
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
else
{
nDayOfWeek = GetDayOfWeek( rString, nPos );
if ( nDayOfWeek )
{ // day of week is just parsed away
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date !!!
if ( nPos < rString.Len() )
{
if ( nDayOfWeek < 0 )
{ // abbreviated
if ( rString.GetChar( nPos ) == '.' )
++nPos;
}
else
{ // full long name
SkipBlanks(rString, nPos);
SkipString( pFormatter->GetLocaleData()->getLongDateDayOfWeekSep(), rString, nPos );
}
SkipBlanks(rString, nPos);
nMonth = GetMonth(rString, nPos);
if ( nMonth ) // month (Jan 1)?
{
nMonthPos = 1; // month a the beginning
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
}
}
}
}
if (nPos < rString.Len()) // not everything consumed
{
// Does input StartString equal StartString of format?
// This time with sign detection!
if ( !ScanStringNumFor( rString, nPos, pFormat, 0 ) )
return MatchedReturn();
}
return sal_True;
}
//---------------------------------------------------------------------------
// ScanMidString
//
// String in der Mitte analysieren
// Alles weg => sal_True
// sonst => sal_False
sal_Bool ImpSvNumberInputScan::ScanMidString( const String& rString,
sal_uInt16 nStringPos, const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
short eOldScannedType = eScannedType;
if ( nMatchedAllStrings )
{ // Match against format in any case, so later on for a "1-2-3-4" input
// we may distinguish between a y-m-d (or similar) date and a 0-0-0-0
// format.
if ( ScanStringNumFor( rString, 0, pFormat, nStringPos ) )
nMatchedAllStrings |= nMatchedMidString;
else
nMatchedAllStrings = 0;
}
SkipBlanks(rString, nPos);
if (GetDecSep(rString, nPos)) // decimal separator?
{
if (nDecPos == 1 || nDecPos == 3) // .12.4 or 1.E2.1
return MatchedReturn();
else if (nDecPos == 2) // . dup: 12.4.
{
if (bDecSepInDateSeps) // . also date separator
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE &&
eScannedType != NUMBERFORMAT_DATETIME) // already another type
return MatchedReturn();
if (eScannedType == NUMBERFORMAT_UNDEFINED)
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
SkipBlanks(rString, nPos);
}
else
return MatchedReturn();
}
else
{
nDecPos = 2; // . in mid string
SkipBlanks(rString, nPos);
}
}
else if ( ((eScannedType & NUMBERFORMAT_TIME) == NUMBERFORMAT_TIME)
&& GetTime100SecSep( rString, nPos ) )
{ // hundredth seconds separator
if ( nDecPos )
return MatchedReturn();
nDecPos = 2; // . in mid string
SkipBlanks(rString, nPos);
}
if (SkipChar('/', rString, nPos)) // fraction?
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return MatchedReturn(); // => jan/31/1994
else if ( eScannedType != NUMBERFORMAT_DATE // analyzed date until now
&& ( eSetType == NUMBERFORMAT_FRACTION // and preset was fraction
|| (nAnzNums == 3 // or 3 numbers
&& nStringPos > 2) ) ) // and what ???
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_FRACTION; // !!! it IS a fraction
}
else
nPos--; // put '/' back
}
if (GetThousandSep(rString, nPos, nStringPos)) // 1,000
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_CURRENCY) // except currency
return MatchedReturn();
nThousand++;
}
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const String& rDate = pFormatter->GetDateSep();
const String& rTime = pLoc->getTimeSep();
sal_Unicode cTime = rTime.GetChar(0);
SkipBlanks(rString, nPos);
if ( SkipString(rDate, rString, nPos) // 10., 10-, 10/
|| ((cTime != '.') && SkipChar('.', rString, nPos)) // TRICKY:
|| ((cTime != '/') && SkipChar('/', rString, nPos)) // short boolean
|| ((cTime != '-') && SkipChar('-', rString, nPos)) ) // evaluation!
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return MatchedReturn();
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
short nTmpMonth = GetMonth(rString, nPos); // 10. Jan 94
if (nMonth && nTmpMonth) // month dup
return MatchedReturn();
if (nTmpMonth)
{
nMonth = nTmpMonth;
nMonthPos = 2; // month in the middle
if ( nMonth < 0 && SkipChar( '.', rString, nPos ) )
; // short month may be abbreviated Jan.
else if ( SkipChar( '-', rString, nPos ) )
; // #79632# recognize 17-Jan-2001 to be a date
// #99065# short and long month name
else
SkipString( pLoc->getLongDateMonthSep(), rString, nPos );
SkipBlanks(rString, nPos);
}
}
short nTempMonth = GetMonth(rString, nPos); // month in the middle (10 Jan 94)
if (nTempMonth)
{
if (nMonth != 0) // month dup
return MatchedReturn();
if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_DATE) // except date
return MatchedReturn();
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
nMonth = nTempMonth;
nMonthPos = 2; // month in the middle
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipString( pLoc->getLongDateMonthSep(), rString, nPos );
SkipBlanks(rString, nPos);
}
if ( SkipChar('E', rString, nPos) // 10E, 10e, 10,Ee
|| SkipChar('e', rString, nPos) )
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // already another type
return MatchedReturn();
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_SCIENTIFIC; // !!! it IS scientific
if ( nThousand+2 == nAnzNums // special case 1.E2
&& nDecPos == 2 )
nDecPos = 3; // 1,100.E2 1,100,100.E3
}
nESign = GetESign(rString, nPos); // signed exponent?
SkipBlanks(rString, nPos);
}
if ( SkipString(rTime, rString, nPos) ) // time separator?
{
if (nDecPos) // already . => maybe error
{
if (bDecSepInDateSeps) // . also date sep
{
if ( eScannedType != NUMBERFORMAT_DATE && // already another type than date
eScannedType != NUMBERFORMAT_DATETIME) // or date time
return MatchedReturn();
if (eScannedType == NUMBERFORMAT_DATE)
nDecPos = 0; // reset for time transition
}
else
return MatchedReturn();
}
if ( ( eScannedType == NUMBERFORMAT_DATE // already date type
|| eScannedType == NUMBERFORMAT_DATETIME) // or date time
&& nAnzNums > 3) // and more than 3 numbers? (31.Dez.94 8:23)
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATETIME; // !!! it IS date with time
}
else if ( eScannedType != NUMBERFORMAT_UNDEFINED // already another type
&& eScannedType != NUMBERFORMAT_TIME) // except time
return MatchedReturn();
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_TIME; // !!! it IS a time
}
if ( !nTimePos )
nTimePos = nStringPos + 1;
}
if (nPos < rString.Len())
{
switch (eScannedType)
{
case NUMBERFORMAT_DATE:
if (nMonthPos == 1 && pLoc->getLongDateFormat() == MDY)
{
// #68232# recognize long date separators like ", " in "September 5, 1999"
if (SkipString( pLoc->getLongDateDaySep(), rString, nPos ))
SkipBlanks( rString, nPos );
}
else if (nStringPos == 5 && nPos == 0 && rString.Len() == 1 &&
rString.GetChar(0) == 'T' && MayBeIso8601())
{
// ISO 8601 combined date and time, yyyy-mm-ddThh:mm
++nPos;
}
break;
#if NF_RECOGNIZE_ISO8601_TIMEZONES
case NUMBERFORMAT_DATETIME:
if (nPos == 0 && rString.Len() == 1 && nStringPos >= 9 &&
MayBeIso8601())
{
// ISO 8601 timezone offset
switch (rString.GetChar(0))
{
case '+':
case '-':
if (nStringPos == nAnzStrings-2 ||
nStringPos == nAnzStrings-4)
{
++nPos; // yyyy-mm-ddThh:mm[:ss]+xx[[:]yy]
// nTimezonePos needed for GetTimeRef()
if (!nTimezonePos)
nTimezonePos = nStringPos + 1;
}
break;
case ':':
if (nTimezonePos && nStringPos >= 11 &&
nStringPos == nAnzStrings-2)
++nPos; // yyyy-mm-ddThh:mm[:ss]+xx:yy
break;
}
}
break;
#endif
}
}
if (nPos < rString.Len()) // not everything consumed?
{
if ( nMatchedAllStrings & ~nMatchedVirgin )
eScannedType = eOldScannedType;
else
return sal_False;
}
return sal_True;
}
//---------------------------------------------------------------------------
// ScanEndString
//
// Schlussteil analysieren
// Alles weg => sal_True
// sonst => sal_False
sal_Bool ImpSvNumberInputScan::ScanEndString( const String& rString,
const SvNumberformat* pFormat )
{
xub_StrLen nPos = 0;
if ( nMatchedAllStrings )
{ // Match against format in any case, so later on for a "1-2-3-4" input
// we may distinguish between a y-m-d (or similar) date and a 0-0-0-0
// format.
if ( ScanStringNumFor( rString, 0, pFormat, 0xFFFF ) )
nMatchedAllStrings |= nMatchedEndString;
else
nMatchedAllStrings = 0;
}
SkipBlanks(rString, nPos);
if (GetDecSep(rString, nPos)) // decimal separator?
{
if (nDecPos == 1 || nDecPos == 3) // .12.4 or 12.E4.
return MatchedReturn();
else if (nDecPos == 2) // . dup: 12.4.
{
if (bDecSepInDateSeps) // . also date sep
{
if ( eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE &&
eScannedType != NUMBERFORMAT_DATETIME) // already another type
return MatchedReturn();
if (eScannedType == NUMBERFORMAT_UNDEFINED)
eScannedType = NUMBERFORMAT_DATE; // !!! it IS a date
SkipBlanks(rString, nPos);
}
else
return MatchedReturn();
}
else
{
nDecPos = 3; // . in end string
SkipBlanks(rString, nPos);
}
}
if ( nSign == 0 // conflict - not signed
&& eScannedType != NUMBERFORMAT_DATE) // and not date
//!? catch time too?
{ // not signed yet
nSign = GetSign(rString, nPos); // 1- DM
if (nNegCheck) // '(' as sign
return MatchedReturn();
}
SkipBlanks(rString, nPos);
if (nNegCheck && SkipChar(')', rString, nPos)) // skip ')' if appropriate
{
nNegCheck = 0;
SkipBlanks(rString, nPos);
}
if ( GetCurrency(rString, nPos, pFormat) ) // currency symbol?
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // currency dup
return MatchedReturn();
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_CURRENCY;
} // behind currency a '-' is allowed
if (nSign == 0) // not signed yet
{
nSign = GetSign(rString, nPos); // DM -
SkipBlanks(rString, nPos);
if (nNegCheck) // 3 DM (
return MatchedReturn();
}
if ( nNegCheck && eScannedType == NUMBERFORMAT_CURRENCY
&& SkipChar(')', rString, nPos) )
{
nNegCheck = 0; // ')' skipped
SkipBlanks(rString, nPos); // only if currency
}
}
if ( SkipChar('%', rString, nPos) ) // 1 %
{
if (eScannedType != NUMBERFORMAT_UNDEFINED) // already another type
return MatchedReturn();
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_PERCENT;
}
const LocaleDataWrapper* pLoc = pFormatter->GetLocaleData();
const String& rDate = pFormatter->GetDateSep();
const String& rTime = pLoc->getTimeSep();
if ( SkipString(rTime, rString, nPos) ) // 10:
{
if (nDecPos) // already , => error
return MatchedReturn();
if (eScannedType == NUMBERFORMAT_DATE && nAnzNums > 2) // 31.Dez.94 8:
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATETIME;
}
else if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_TIME) // already another type
return MatchedReturn();
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_TIME;
}
if ( !nTimePos )
nTimePos = nAnzStrings;
}
sal_Unicode cTime = rTime.GetChar(0);
if ( SkipString(rDate, rString, nPos) // 10., 10-, 10/
|| ((cTime != '.') && SkipChar('.', rString, nPos)) // TRICKY:
|| ((cTime != '/') && SkipChar('/', rString, nPos)) // short boolean
|| ((cTime != '-') && SkipChar('-', rString, nPos)) ) // evaluation!
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return MatchedReturn();
else
{
SkipBlanks(rString, nPos);
eScannedType = NUMBERFORMAT_DATE;
}
short nTmpMonth = GetMonth(rString, nPos); // 10. Jan
if (nMonth && nTmpMonth) // month dup
return MatchedReturn();
if (nTmpMonth)
{
nMonth = nTmpMonth;
nMonthPos = 3; // month at end
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
}
short nTempMonth = GetMonth(rString, nPos); // 10 Jan
if (nTempMonth)
{
if (nMonth) // month dup
return MatchedReturn();
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_DATE) // already another type
return MatchedReturn();
eScannedType = NUMBERFORMAT_DATE;
nMonth = nTempMonth;
nMonthPos = 3; // month at end
if ( nMonth < 0 )
SkipChar( '.', rString, nPos ); // abbreviated
SkipBlanks(rString, nPos);
}
xub_StrLen nOrigPos = nPos;
if (GetTimeAmPm(rString, nPos))
{
if (eScannedType != NUMBERFORMAT_UNDEFINED &&
eScannedType != NUMBERFORMAT_TIME &&
eScannedType != NUMBERFORMAT_DATETIME) // already another type
return MatchedReturn();
else
{
// If not already scanned as time, 6.78am does not result in 6
// seconds and 78 hundredths in the morning. Keep as suffix.
if (eScannedType != NUMBERFORMAT_TIME && nDecPos == 2 && nAnzNums == 2)
nPos = nOrigPos; // rewind am/pm
else
{
SkipBlanks(rString, nPos);
if ( eScannedType != NUMBERFORMAT_DATETIME )
eScannedType = NUMBERFORMAT_TIME;
}
}
}
if ( nNegCheck && SkipChar(')', rString, nPos) )
{
if (eScannedType == NUMBERFORMAT_CURRENCY) // only if currency
{
nNegCheck = 0; // skip ')'
SkipBlanks(rString, nPos);
}
else
return MatchedReturn();
}
if ( nPos < rString.Len() &&
(eScannedType == NUMBERFORMAT_DATE
|| eScannedType == NUMBERFORMAT_DATETIME) )
{ // day of week is just parsed away
xub_StrLen nOldPos = nPos;
const String& rSep = pFormatter->GetLocaleData()->getLongDateDayOfWeekSep();
if ( StringContains( rSep, rString, nPos ) )
{
nPos = nPos + rSep.Len();
SkipBlanks(rString, nPos);
}
int nDayOfWeek = GetDayOfWeek( rString, nPos );
if ( nDayOfWeek )
{
if ( nPos < rString.Len() )
{
if ( nDayOfWeek < 0 )
{ // short
if ( rString.GetChar( nPos ) == '.' )
++nPos;
}
SkipBlanks(rString, nPos);
}
}
else
nPos = nOldPos;
}
#if NF_RECOGNIZE_ISO8601_TIMEZONES
if (nPos == 0 && eScannedType == NUMBERFORMAT_DATETIME &&
rString.Len() == 1 && rString.GetChar(0) == 'Z' && MayBeIso8601())
{
// ISO 8601 timezone UTC yyyy-mm-ddThh:mmZ
++nPos;
}
#endif
if (nPos < rString.Len()) // everything consumed?
{
// does input EndString equal EndString in Format?
if ( !ScanStringNumFor( rString, nPos, pFormat, 0xFFFF ) )
return sal_False;
}
return sal_True;
}
sal_Bool ImpSvNumberInputScan::ScanStringNumFor(
const String& rString, // String to scan
xub_StrLen nPos, // Position until which was consumed
const SvNumberformat* pFormat, // The format to match
sal_uInt16 nString, // Substring of format, 0xFFFF => last
sal_Bool bDontDetectNegation // Suppress sign detection
)
{
if ( !pFormat )
return sal_False;
const ::utl::TransliterationWrapper* pTransliteration = pFormatter->GetTransliteration();
const String* pStr;
String aString( rString );
sal_Bool bFound = sal_False;
sal_Bool bFirst = sal_True;
sal_Bool bContinue = sal_True;
sal_uInt16 nSub;
do
{
// Don't try "lower" subformats ff the very first match was the second
// or third subformat.
nSub = nStringScanNumFor;
do
{ // Step through subformats, first positive, then negative, then
// other, but not the last (text) subformat.
pStr = pFormat->GetNumForString( nSub, nString, sal_True );
if ( pStr && pTransliteration->isEqual( aString, *pStr ) )
{
bFound = sal_True;
bContinue = sal_False;
}
else if ( nSub < 2 )
++nSub;
else
bContinue = sal_False;
} while ( bContinue );
if ( !bFound && bFirst && nPos )
{ // try remaining substring
bFirst = sal_False;
aString.Erase( 0, nPos );
bContinue = sal_True;
}
} while ( bContinue );
if ( !bFound )
{
if ( !bDontDetectNegation && (nString == 0) && !bFirst && (nSign < 0)
&& pFormat->IsNegativeRealNegative() )
{ // simply negated twice? --1
aString.EraseAllChars( ' ' );
if ( (aString.Len() == 1) && (aString.GetChar(0) == '-') )
{
bFound = sal_True;
nStringScanSign = -1;
nSub = 0; //! not 1
}
}
if ( !bFound )
return sal_False;
}
else if ( !bDontDetectNegation && (nSub == 1) &&
pFormat->IsNegativeRealNegative() )
{ // negative
if ( nStringScanSign < 0 )
{
if ( (nSign < 0) && (nStringScanNumFor != 1) )
nStringScanSign = 1; // triple negated --1 yyy
}
else if ( nStringScanSign == 0 )
{
if ( nSign < 0 )
{ // nSign and nStringScanSign will be combined later,
// flip sign if doubly negated
if ( (nString == 0) && !bFirst
&& SvNumberformat::HasStringNegativeSign( aString ) )
nStringScanSign = -1; // direct double negation
else if ( pFormat->IsNegativeWithoutSign() )
nStringScanSign = -1; // indirect double negation
}
else
nStringScanSign = -1;
}
else // > 0
nStringScanSign = -1;
}
nStringScanNumFor = nSub;
return sal_True;
}
//---------------------------------------------------------------------------
// IsNumberFormatMain
//
// Recognizes types of number, exponential, fraction, percent, currency, date, time.
// Else text => return sal_False
sal_Bool ImpSvNumberInputScan::IsNumberFormatMain(
const String& rString, // string to be analyzed
double& , // OUT: result as number, if possible
const SvNumberformat* pFormat ) // maybe number format set to match against
{
Reset();
NumberStringDivision( rString ); // breakdown into strings and numbers
if (nAnzStrings >= SV_MAX_ANZ_INPUT_STRINGS) // too many elements
return sal_False; // Njet, Nope, ...
if (nAnzNums == 0) // no number in input
{
if ( nAnzStrings > 0 )
{
// Here we may change the original, we don't need it anymore.
// This saves copies and ToUpper() in GetLogical() and is faster.
String& rStrArray = sStrArray[0];
rStrArray.EraseTrailingChars( ' ' );
rStrArray.EraseLeadingChars( ' ' );
nLogical = GetLogical( rStrArray );
if ( nLogical )
{
eScannedType = NUMBERFORMAT_LOGICAL; // !!! it's a BOOLEAN
nMatchedAllStrings &= ~nMatchedVirgin;
return sal_True;
}
else
return sal_False; // simple text
}
else
return sal_False; // simple text
}
sal_uInt16 i = 0; // mark any symbol
sal_uInt16 j = 0; // mark only numbers
switch ( nAnzNums )
{
case 1 : // Exactly 1 number in input
{ // nAnzStrings >= 1
if (GetNextNumber(i,j)) // i=1,0
{ // Number at start
if (eSetType == NUMBERFORMAT_FRACTION) // Fraction 1 = 1/1
{
if (i >= nAnzStrings || // no end string nor decimal separator
sStrArray[i] == pFormatter->GetNumDecimalSep())
{
eScannedType = NUMBERFORMAT_FRACTION;
nMatchedAllStrings &= ~nMatchedVirgin;
return sal_True;
}
}
}
else
{ // Analyze start string
if (!ScanStartString( sStrArray[i], pFormat )) // i=0
return sal_False; // already an error
i++; // next symbol, i=1
}
GetNextNumber(i,j); // i=1,2
if (eSetType == NUMBERFORMAT_FRACTION) // Fraction -1 = -1/1
{
if (nSign && !nNegCheck && // Sign +, -
eScannedType == NUMBERFORMAT_UNDEFINED && // not date or currency
nDecPos == 0 && // no previous decimal separator
(i >= nAnzStrings || // no end string nor decimal separator
sStrArray[i] == pFormatter->GetNumDecimalSep())
)
{
eScannedType = NUMBERFORMAT_FRACTION;
nMatchedAllStrings &= ~nMatchedVirgin;
return sal_True;
}
}
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return sal_False;
}
break;
case 2 : // Exactly 2 numbers in input
{ // nAnzStrings >= 3
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyze start string
if (!ScanStartString( sStrArray[i], pFormat ))
return sal_False; // already an error
i++; // i=1
}
GetNextNumber(i,j); // i=1,2
if ( !ScanMidString( sStrArray[i], i, pFormat ) )
return sal_False;
i++; // next symbol, i=2,3
GetNextNumber(i,j); // i=3,4
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return sal_False;
if (eSetType == NUMBERFORMAT_FRACTION) // -1,200. as fraction
{
if (!nNegCheck && // no sign '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // no decimal separator or at end
)
{
eScannedType = NUMBERFORMAT_FRACTION;
nMatchedAllStrings &= ~nMatchedVirgin;
return sal_True;
}
}
}
break;
case 3 : // Exactly 3 numbers in input
{ // nAnzStrings >= 5
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyze start string
if (!ScanStartString( sStrArray[i], pFormat ))
return sal_False; // already an error
i++; // i=1
if (nDecPos == 1) // decimal separator at start => error
return sal_False;
}
GetNextNumber(i,j); // i=1,2
if ( !ScanMidString( sStrArray[i], i, pFormat ) )
return sal_False;
i++; // i=2,3
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E only at end
return sal_False;
GetNextNumber(i,j); // i=3,4
if ( !ScanMidString( sStrArray[i], i, pFormat ) )
return sal_False;
i++; // i=4,5
GetNextNumber(i,j); // i=5,6
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return sal_False;
if (eSetType == NUMBERFORMAT_FRACTION) // -1,200,100. as fraction
{
if (!nNegCheck && // no sign '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // no decimal separator or at end
)
{
eScannedType = NUMBERFORMAT_FRACTION;
nMatchedAllStrings &= ~nMatchedVirgin;
return sal_True;
}
}
if ( eScannedType == NUMBERFORMAT_FRACTION && nDecPos )
return sal_False; // #36857# not a real fraction
}
break;
default: // More than 3 numbers in input
{ // nAnzStrings >= 7
if (!GetNextNumber(i,j)) // i=1,0
{ // Analyze startstring
if (!ScanStartString( sStrArray[i], pFormat ))
return sal_False; // already an error
i++; // i=1
if (nDecPos == 1) // decimal separator at start => error
return sal_False;
}
GetNextNumber(i,j); // i=1,2
if ( !ScanMidString( sStrArray[i], i, pFormat ) )
return sal_False;
i++; // i=2,3
sal_uInt16 nThOld = 10; // just not 0 or 1
while (nThOld != nThousand && j < nAnzNums-1)
// Execute at least one time
// but leave one number.
{ // Loop over group separators
nThOld = nThousand;
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E only at end
return sal_False;
GetNextNumber(i,j);
if ( i < nAnzStrings && !ScanMidString( sStrArray[i], i, pFormat ) )
return sal_False;
i++;
}
if (eScannedType == NUMBERFORMAT_DATE || // long date or
eScannedType == NUMBERFORMAT_TIME || // long time or
eScannedType == NUMBERFORMAT_UNDEFINED) // long number
{
for (sal_uInt16 k = j; k < nAnzNums-1; k++)
{
if (eScannedType == NUMBERFORMAT_SCIENTIFIC) // E only at endd
return sal_False;
GetNextNumber(i,j);
if ( i < nAnzStrings && !ScanMidString( sStrArray[i], i, pFormat ) )
return sal_False;
i++;
}
}
GetNextNumber(i,j);
if (i < nAnzStrings && !ScanEndString( sStrArray[i], pFormat ))
return sal_False;
if (eSetType == NUMBERFORMAT_FRACTION) // -1,200,100. as fraction
{
if (!nNegCheck && // no sign '('
eScannedType == NUMBERFORMAT_UNDEFINED &&
(nDecPos == 0 || nDecPos == 3) // no decimal separator or at end
)
{
eScannedType = NUMBERFORMAT_FRACTION;
nMatchedAllStrings &= ~nMatchedVirgin;
return sal_True;
}
}
if ( eScannedType == NUMBERFORMAT_FRACTION && nDecPos )
return sal_False; // #36857# not a real fraction
}
}
if (eScannedType == NUMBERFORMAT_UNDEFINED)
{
nMatchedAllStrings &= ~nMatchedVirgin;
// did match including nMatchedUsedAsReturn
sal_Bool bDidMatch = (nMatchedAllStrings != 0);
if ( nMatchedAllStrings )
{
sal_Bool bMatch = (pFormat ? pFormat->IsNumForStringElementCountEqual(
nStringScanNumFor, nAnzStrings, nAnzNums ) : sal_False);
if ( !bMatch )
nMatchedAllStrings = 0;
}
if ( nMatchedAllStrings )
eScannedType = eSetType;
else if ( bDidMatch )
return sal_False;
else
eScannedType = NUMBERFORMAT_NUMBER;
// everything else should have been recognized by now
}
else if ( eScannedType == NUMBERFORMAT_DATE )
{ // the very relaxed date input checks may interfere with a preset format
nMatchedAllStrings &= ~nMatchedVirgin;
sal_Bool bWasReturn = ((nMatchedAllStrings & nMatchedUsedAsReturn) != 0);
if ( nMatchedAllStrings )
{
sal_Bool bMatch = (pFormat ? pFormat->IsNumForStringElementCountEqual(
nStringScanNumFor, nAnzStrings, nAnzNums ) : sal_False);
if ( !bMatch )
nMatchedAllStrings = 0;
}
if ( nMatchedAllStrings )
eScannedType = eSetType;
else if ( bWasReturn )
return sal_False;
}
else
nMatchedAllStrings = 0; // reset flag to no substrings matched
return sal_True;
}
//---------------------------------------------------------------------------
// return sal_True or sal_False depending on the nMatched... state and remember usage
sal_Bool ImpSvNumberInputScan::MatchedReturn()
{
if ( nMatchedAllStrings & ~nMatchedVirgin )
{
nMatchedAllStrings |= nMatchedUsedAsReturn;
return sal_True;
}
return sal_False;
}
//---------------------------------------------------------------------------
// Initialize uppercase months and weekdays
void ImpSvNumberInputScan::InitText()
{
sal_Int32 j, nElems;
const CharClass* pChrCls = pFormatter->GetCharClass();
const CalendarWrapper* pCal = pFormatter->GetCalendar();
delete [] pUpperMonthText;
delete [] pUpperAbbrevMonthText;
::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > xElems
= pCal->getMonths();
nElems = xElems.getLength();
pUpperMonthText = new String[nElems];
pUpperAbbrevMonthText = new String[nElems];
for ( j=0; j<nElems; j++ )
{
pUpperMonthText[j] = pChrCls->upper( xElems[j].FullName );
pUpperAbbrevMonthText[j] = pChrCls->upper( xElems[j].AbbrevName );
}
delete [] pUpperDayText;
delete [] pUpperAbbrevDayText;
xElems = pCal->getDays();
nElems = xElems.getLength();
pUpperDayText = new String[nElems];
pUpperAbbrevDayText = new String[nElems];
for ( j=0; j<nElems; j++ )
{
pUpperDayText[j] = pChrCls->upper( xElems[j].FullName );
pUpperAbbrevDayText[j] = pChrCls->upper( xElems[j].AbbrevName );
}
bTextInitialized = sal_True;
}
//===========================================================================
// P U B L I C
//---------------------------------------------------------------------------
// ChangeIntl
//
// MUST be called if International/Locale is changed
void ImpSvNumberInputScan::ChangeIntl()
{
sal_Unicode cDecSep = pFormatter->GetNumDecimalSep().GetChar(0);
bDecSepInDateSeps = ( cDecSep == '-' ||
cDecSep == '/' ||
cDecSep == '.' ||
cDecSep == pFormatter->GetDateSep().GetChar(0) );
bTextInitialized = sal_False;
aUpperCurrSymbol.Erase();
}
//---------------------------------------------------------------------------
// ChangeNullDate
void ImpSvNumberInputScan::ChangeNullDate(
const sal_uInt16 Day,
const sal_uInt16 Month,
const sal_uInt16 Year )
{
if ( pNullDate )
*pNullDate = Date(Day, Month, Year);
else
pNullDate = new Date(Day, Month, Year);
}
//---------------------------------------------------------------------------
// IsNumberFormat
//
// => does rString represent a number (also date, time et al)
sal_Bool ImpSvNumberInputScan::IsNumberFormat(
const String& rString, // string to be analyzed
short& F_Type, // IN: old type, OUT: new type
double& fOutNumber, // OUT: number if convertable
const SvNumberformat* pFormat ) // maybe a number format to match against
{
String sResString;
String aString;
sal_Bool res; // return value
eSetType = F_Type; // old type set
if ( !rString.Len() )
res = sal_False;
else if (rString.Len() > 308) // arbitrary
res = sal_False;
else
{
// NoMoreUpperNeeded, all comparisons on UpperCase
aString = pFormatter->GetCharClass()->upper( rString );
// convert native number to ASCII if necessary
TransformInput( aString );
res = IsNumberFormatMain( aString, fOutNumber, pFormat );
}
if (res)
{
if ( nNegCheck // ')' not found for '('
|| (nSign && (eScannedType == NUMBERFORMAT_DATE
|| eScannedType == NUMBERFORMAT_DATETIME))
) // signed date/datetime
res = sal_False;
else
{ // check count of partial number strings
switch (eScannedType)
{
case NUMBERFORMAT_PERCENT:
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_NUMBER:
if (nDecPos == 1) // .05
{
// matched MidStrings function like group separators
if ( nMatchedAllStrings )
nThousand = nAnzNums - 1;
else if ( nAnzNums != 1 )
res = sal_False;
}
else if (nDecPos == 2) // 1.05
{
// matched MidStrings function like group separators
if ( nMatchedAllStrings )
nThousand = nAnzNums - 1;
else if ( nAnzNums != nThousand+2 )
res = sal_False;
}
else // 1,100 or 1,100.
{
// matched MidStrings function like group separators
if ( nMatchedAllStrings )
nThousand = nAnzNums - 1;
else if ( nAnzNums != nThousand+1 )
res = sal_False;
}
break;
case NUMBERFORMAT_SCIENTIFIC: // 1.0e-2
if (nDecPos == 1) // .05
{
if (nAnzNums != 2)
res = sal_False;
}
else if (nDecPos == 2) // 1.05
{
if (nAnzNums != nThousand+3)
res = sal_False;
}
else // 1,100 or 1,100.
{
if (nAnzNums != nThousand+2)
res = sal_False;
}
break;
case NUMBERFORMAT_DATE:
if (nMonth)
{ // month name and numbers
if (nAnzNums > 2)
res = sal_False;
}
else
{
if (nAnzNums > 3)
res = sal_False;
}
break;
case NUMBERFORMAT_TIME:
if (nDecPos)
{ // hundredth seconds included
if (nAnzNums > 4)
res = sal_False;
}
else
{
if (nAnzNums > 3)
res = sal_False;
}
break;
case NUMBERFORMAT_DATETIME:
if (nMonth)
{ // month name and numbers
if (nDecPos)
{ // hundredth seconds included
if (nAnzNums > 6)
res = sal_False;
}
else
{
if (nAnzNums > 5)
res = sal_False;
}
}
else
{
if (nDecPos)
{ // hundredth seconds included
if (nAnzNums > 7)
res = sal_False;
}
else
{
if (nAnzNums > 6)
res = sal_False;
}
}
break;
default:
break;
} // switch
} // else
} // if (res)
if (res)
{ // we finally have a number
switch (eScannedType)
{
case NUMBERFORMAT_LOGICAL:
if (nLogical == 1)
fOutNumber = 1.0; // True
else if (nLogical == -1)
fOutNumber = 0.0; // False
else
res = sal_False; // Oops
break;
case NUMBERFORMAT_PERCENT:
case NUMBERFORMAT_CURRENCY:
case NUMBERFORMAT_NUMBER:
case NUMBERFORMAT_SCIENTIFIC:
case NUMBERFORMAT_DEFINED: // if no category detected handle as number
{
if ( nDecPos == 1 ) // . at start
sResString.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "0." ) );
else
sResString.Erase();
sal_uInt16 k;
for ( k = 0; k <= nThousand; k++)
sResString += sStrArray[nNums[k]]; // integer part
if ( nDecPos == 2 && k < nAnzNums ) // . somewhere
{
sResString += '.';
sal_uInt16 nStop = (eScannedType == NUMBERFORMAT_SCIENTIFIC ?
nAnzNums-1 : nAnzNums);
for ( ; k < nStop; k++)
sResString += sStrArray[nNums[k]]; // fractional part
}
if (eScannedType != NUMBERFORMAT_SCIENTIFIC)
fOutNumber = StringToDouble(sResString);
else
{ // append exponent
sResString += 'E';
if ( nESign == -1 )
sResString += '-';
sResString += sStrArray[nNums[nAnzNums-1]];
rtl_math_ConversionStatus eStatus;
fOutNumber = ::rtl::math::stringToDouble(
sResString, '.', ',', &eStatus, NULL );
if ( eStatus == rtl_math_ConversionStatus_OutOfRange )
{
F_Type = NUMBERFORMAT_TEXT; // overflow/underflow -> Text
if (nESign == -1)
fOutNumber = 0.0;
else
fOutNumber = DBL_MAX;
/*!*/ return sal_True;
}
}
if ( nStringScanSign )
{
if ( nSign )
nSign *= nStringScanSign;
else
nSign = nStringScanSign;
}
if ( nSign < 0 )
fOutNumber = -fOutNumber;
if (eScannedType == NUMBERFORMAT_PERCENT)
fOutNumber/= 100.0;
}
break;
case NUMBERFORMAT_FRACTION:
if (nAnzNums == 1)
fOutNumber = StringToDouble(sStrArray[nNums[0]]);
else if (nAnzNums == 2)
{
if (nThousand == 1)
{
sResString = sStrArray[nNums[0]];
sResString += sStrArray[nNums[1]]; // integer part
fOutNumber = StringToDouble(sResString);
}
else
{
double fZaehler = StringToDouble(sStrArray[nNums[0]]);
double fNenner = StringToDouble(sStrArray[nNums[1]]);
if (fNenner != 0.0)
fOutNumber = fZaehler/fNenner;
else
res = sal_False;
}
}
else // nAnzNums > 2
{
sal_uInt16 k = 1;
sResString = sStrArray[nNums[0]];
if (nThousand > 0)
for (k = 1; k <= nThousand; k++)
sResString += sStrArray[nNums[k]];
fOutNumber = StringToDouble(sResString);
if (k == nAnzNums-2)
{
double fZaehler = StringToDouble(sStrArray[nNums[k]]);
double fNenner = StringToDouble(sStrArray[nNums[k+1]]);
if (fNenner != 0.0)
fOutNumber += fZaehler/fNenner;
else
res = sal_False;
}
}
if ( nStringScanSign )
{
if ( nSign )
nSign *= nStringScanSign;
else
nSign = nStringScanSign;
}
if ( nSign < 0 )
fOutNumber = -fOutNumber;
break;
case NUMBERFORMAT_TIME:
GetTimeRef(fOutNumber, 0, nAnzNums);
if ( nSign < 0 )
fOutNumber = -fOutNumber;
break;
case NUMBERFORMAT_DATE:
{
sal_uInt16 nCounter = 0; // dummy here
res = GetDateRef( fOutNumber, nCounter, pFormat );
}
break;
case NUMBERFORMAT_DATETIME:
{
sal_uInt16 nCounter = 0; // needed here
res = GetDateRef( fOutNumber, nCounter, pFormat );
if ( res )
{
double fTime;
GetTimeRef( fTime, nCounter, nAnzNums - nCounter );
fOutNumber += fTime;
}
}
break;
default:
DBG_ERRORFILE( "Some number recognized but what's it?" );
fOutNumber = 0.0;
break;
}
}
if (res) // overflow/underflow -> Text
{
if (fOutNumber < -DBL_MAX) // -1.7E308
{
F_Type = NUMBERFORMAT_TEXT;
fOutNumber = -DBL_MAX;
return sal_True;
}
else if (fOutNumber > DBL_MAX) // 1.7E308
{
F_Type = NUMBERFORMAT_TEXT;
fOutNumber = DBL_MAX;
return sal_True;
}
}
if (res == sal_False)
{
eScannedType = NUMBERFORMAT_TEXT;
fOutNumber = 0.0;
}
F_Type = eScannedType;
return res;
}
|
#include "desktop_record.h"
desktop_record::desktop_record(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
|
/**
* @file TLE5012-pal-ino.cpp
* @brief TLE5012 Arduino Hardware Platforms
* @date October 2020
* @copyright Copyright (c) 2019-2020 Infineon Technologies AG
*
* SPDX-License-Identifier: MIT
*/
#include "TLE5012-pal-ino.hpp"
#if (TLE5012_FRAMEWORK == TLE5012_FRMWK_ARDUINO)
/**
* @addtogroup arduinoPal
*/
/**
* Construct a new Tle5012Ino::Tle5012Ino object with default SPI and pin assignment.
* Use this if:
* - you have TLE5012B Sensor2go kit (all types)
* - attached the breakout board on the default SPI of your MCU
* - attached a bulk chip with the SSC interface to the default SPI of your MCU
*/
Tle5012Ino::Tle5012Ino():Tle5012b()
{
Tle5012b::mSlave = TLE5012B_S0;
Tle5012b::sBus = new SPICIno();
}
/**
* @brief Construct a new Tle5012Ino::Tle5012Ino object with chipselect and sensor slave
* Use this constructor if:
* - you use more than one sensor with one SPI channel (up to four are possible)
*
* @param csPin pin number of the CS pin
* @param slave optional sensor slave setting
*/
Tle5012Ino::Tle5012Ino(uint8_t csPin, slaveNum slave):Tle5012b()
{
Tle5012b::mSlave = slave;
Tle5012b::sBus = new SPICIno(csPin);
}
/**
* Construct a new Tle5012Ino::Tle5012Ino object with individual SPI and pin assignment
* Use this if:
* - you use different SPI channels than default
* - you use a software SPI with different pin settings than default
*
* @param bus void pointer to the object representing the SPI class
* @param csPin pin number of the CS pin
* @param misoPin MISO pin for the SPI/SSC interface
* @param mosiPin MOSI pin for the SPI/SSC interface
* @param sckPin system clock pin for external sensor clock setting
* @param slave optional sensor slave setting
*/
Tle5012Ino::Tle5012Ino(SPIClass3W *bus, uint8_t csPin, uint8_t misoPin, uint8_t mosiPin, uint8_t sckPin, slaveNum slave):Tle5012b()
{
Tle5012b::mSlave = slave;
Tle5012b::sBus = new SPICIno(*bus,csPin,misoPin,mosiPin,sckPin);
}
/**
* @brief begin method with default assignments for the SPI bus
* and pin setting.
* The EN pin is only available for the Sensor2go kit, therefore we only
* set it in that case, otherwise it will be NULL.
*
* @return errorTypes
*/
errorTypes Tle5012Ino::begin(void)
{
#if defined(XMC1100_XMC2GO) || defined(XMC1100_H_BRIDGE2GO)
#undef PIN_SPI_EN
#define PIN_SPI_EN 8 /*!< TLE5012 Sensor2Go Kit has a switch on/off pin */
#endif
// init helper libs
sBus->init();
if (PIN_SPI_EN != UNUSED_PIN) {
Tle5012b::en = new GPIOIno(PIN_SPI_EN, OUTPUT, GPIOIno::POSITIVE);
Tle5012b::en->init();
}else{
Tle5012b::en = NULL;
}
// start sensor
enableSensor();
writeSlaveNumber(Tle5012b::mSlave);
// initial CRC check, should be = 0
return (readBlockCRC());
}
#endif /** TLE5012_FRAMEWORK **/
/** @} */
|
#include <iostream>
#include <cmath>
using namespace std;
int main(void) {
int n;
int result;
bool ok;
while (cin >> n) {
if (n < 0)
break;
result = -1;
for (int i = sqrt(n) + 1; i >= 2; i--) {
int tmp = n;
ok = true;
for (int j = 0; j < i; j++) {
if (tmp % i != 1) {
ok = false;
break;
}
tmp -= tmp / i;
tmp--;
}
if (!ok)
continue;
if (tmp % i == 0) {
result = i;
break;
}
}
cout << n << " coconuts, ";
if (result == -1) {
cout << "no solution" << endl;
} else {
cout << result << " people and 1 monkey" << endl;
}
}
return 0;
}
|
/*****************************************************************************
* *
* Copyright 2018 Rice University *
* *
* 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 TPCH_Q03LINEITEMSELECTION_CC
#define TPCH_Q03LINEITEMSELECTION_CC
#include "GetVTable.h"
#include "Query03.h"
GET_V_TABLE(tpch::Q03TPCHLineItemSelection)
#endif
|
/*
* Copyright (c) 2012 Glen Joseph Fernandes
* glenfe at live dot com
*
* Distributed under the Boost Software License,
* Version 1.0. (See accompanying file LICENSE_1_0.txt
* or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_SMART_PTR_DETAIL_MAKE_ARRAY_HELPER_HPP
#define BOOST_SMART_PTR_DETAIL_MAKE_ARRAY_HELPER_HPP
#include <boost/type_traits/alignment_of.hpp>
namespace boost {
namespace detail {
template<typename T, typename Y = char>
class make_array_helper;
template<typename T, typename Y>
class make_array_helper<T[], Y> {
template<typename T2, typename Y2>
friend class make_array_helper;
public:
typedef Y value_type;
typedef Y* pointer;
typedef const Y* const_pointer;
typedef Y& reference;
typedef const Y& const_reference;
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
template<typename U>
struct rebind {
typedef make_array_helper<T[], U> other;
};
make_array_helper(std::size_t size, T** data)
: size(sizeof(T) * size),
data(data) {
}
template<class U>
make_array_helper(const make_array_helper<T[], U>& other)
: size(other.size),
data(other.data) {
}
pointer address(reference value) const {
return &value;
}
const_pointer address(const_reference value) const {
return &value;
}
size_type max_size() const {
return static_cast<std::size_t>(-1) / sizeof(Y);
}
pointer allocate(size_type count, const void* = 0) {
std::size_t a1 = boost::alignment_of<T>::value;
std::size_t n1 = count * sizeof(Y) + a1 - 1;
void* p1 = ::operator new(n1 + size);
char* p2 = static_cast<char*>(p1) + n1;
while (std::size_t(p2) % a1 != 0) {
p2--;
}
*data = reinterpret_cast<T*>(p2);
return reinterpret_cast<Y*>(p1);
}
void deallocate(pointer memory, size_type) {
void* p1 = memory;
::operator delete(p1);
}
void construct(pointer memory, const Y& value) {
void* p1 = memory;
::new(p1) Y(value);
}
void destroy(pointer memory) {
memory->~Y();
}
template<typename U>
bool operator==(const make_array_helper<T[], U>& other) const {
return true;
}
template<typename U>
bool operator!=(const make_array_helper<T[], U>& other) const {
return !(*this == other);
}
private:
std::size_t size;
T** data;
};
template<typename T, std::size_t N, typename Y>
class make_array_helper<T[N], Y> {
template<typename T2, typename Y2>
friend class make_array_helper;
public:
typedef Y value_type;
typedef Y* pointer;
typedef const Y* const_pointer;
typedef Y& reference;
typedef const Y& const_reference;
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
template<typename U>
struct rebind {
typedef make_array_helper<T[N], U> other;
};
make_array_helper(T** data)
: data(data) {
}
template<class U>
make_array_helper(const make_array_helper<T[N], U>& other)
: data(other.data) {
}
pointer address(reference value) const {
return &value;
}
const_pointer address(const_reference value) const {
return &value;
}
size_type max_size() const {
return static_cast<std::size_t>(-1) / sizeof(Y);
}
pointer allocate(size_type count, const void* = 0) {
std::size_t a1 = boost::alignment_of<T>::value;
std::size_t n1 = count * sizeof(Y) + a1 - 1;
void* p1 = ::operator new(n1 + N1);
char* p2 = static_cast<char*>(p1) + n1;
while (std::size_t(p2) % a1 != 0) {
p2--;
}
*data = reinterpret_cast<T*>(p2);
return reinterpret_cast<Y*>(p1);
}
void deallocate(pointer memory, size_type) {
void* p1 = memory;
::operator delete(p1);
}
void construct(pointer memory, const Y& value) {
void* p1 = memory;
::new(p1) Y(value);
}
void destroy(pointer memory) {
memory->~Y();
}
template<typename U>
bool operator==(const make_array_helper<T[N], U>& other) const {
return true;
}
template<typename U>
bool operator!=(const make_array_helper<T[N], U>& other) const {
return !(*this == other);
}
private:
enum {
N1 = N * sizeof(T)
};
T** data;
};
}
}
#endif
|
#include "content/nw/src/browser/menubar_controller.h"
#include "content/nw/src/browser/menubar_view.h"
#include "ui/views/controls/menu/menu_item_view.h"
namespace nw {
MenuBarController::ModelToMenuMap MenuBarController::model_to_menu_map_;
MenuBarController::MenuBarController(MenuBarView* menubar, ui::MenuModel* menu_model)
:MenuModelAdapter(menu_model), menubar_(menubar) {
}
MenuBarController::~MenuBarController() {
}
views::MenuItemView* MenuBarController::GetSiblingMenu(
views::MenuItemView* menu,
const gfx::Point& screen_point,
views::MenuAnchorPosition* anchor,
bool* has_mnemonics,
views::MenuButton** button) {
if (!menubar_)
return NULL;
gfx::Point menubar_loc(screen_point);
views::View::ConvertPointFromScreen(menubar_, &menubar_loc);
ui::MenuModel* model;
if (!menubar_->GetMenuButtonAtLocation(menubar_loc, &model, button))
return NULL;
*has_mnemonics = false;
*anchor = views::MENU_ANCHOR_TOPLEFT;
if (!model_to_menu_map_[model])
CreateMenu(menubar_, model);
return model_to_menu_map_[model];
}
views::MenuItemView* MenuBarController::CreateMenu(MenuBarView* menubar, ui::MenuModel* model) {
MenuBarController* controller = new MenuBarController(menubar, model);
views::MenuItemView* menu = new views::MenuItemView(controller);
controller->BuildMenu(menu);
model_to_menu_map_[model] = menu;
return menu;
}
} //namespace nw
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <EMotionFX/Source/Actor.h>
#include <EMotionFX/Source/ActorInstance.h>
#include <EMotionFX/Source/ActorUpdateScheduler.h>
#include <EMotionFX/Source/MultiThreadScheduler.h>
#include <Tests/SystemComponentFixture.h>
#include <Tests/TestAssetCode/JackActor.h>
#include <Tests/TestAssetCode/ActorFactory.h>
namespace EMotionFX
{
// This turned into an assert and is now being catched in the actual code. Skip this test, as we don't test and return at runtime anymore.
TEST_F(SystemComponentFixture, DISABLED_InsertActorInstanceTwice)
{
ActorUpdateScheduler* baseScheduler = GetEMotionFX().GetActorManager()->GetScheduler();
ASSERT_EQ(baseScheduler->GetType(), MultiThreadScheduler::TYPE_ID) << "Expected multi thread scheduler.";
MultiThreadScheduler* scheduler = static_cast<MultiThreadScheduler*>(baseScheduler);
// Create the actor (internally creates an actor instance for the static AABB calculation and removes it again).
AZStd::unique_ptr<JackNoMeshesActor> actor = ActorFactory::CreateAndInit<JackNoMeshesActor>();
EXPECT_EQ(scheduler->GetNumScheduleSteps(), 0)
<< "Expected an empty scheduler as the temporarily created actor instance got destroyed again.";
// Create an actor instance and make sure it is in the scheduler.
ActorInstance* actorInstance = ActorInstance::Create(actor.get());
EXPECT_EQ(scheduler->GetNumScheduleSteps(), 1) << "The actor instance should be part of the scheduler.";
EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances.size(), 1) << "The step should hold exactly one actor instance.";
EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances[0], actorInstance) << "The actor instance should be part of the step.";
// Insert the actor instance manually again and make sure there is no duplicate.
scheduler->RecursiveInsertActorInstance(actorInstance);
EXPECT_EQ(scheduler->GetNumScheduleSteps(), 1) << "The actor instance should be part of the scheduler.";
EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances.size(), 1) << "The step should hold exactly one actor instance.";
EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances[0], actorInstance) << "The actor instance should be part of the step.";
actorInstance->Destroy();
}
} // namespace EMotionFX
|
/*
* Copyright (c) 2020, Hüseyin Aslıtürk <asliturk@hotmail.com>
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AppletManager.h"
#include <AK/QuickSort.h>
#include <LibCore/EventLoop.h>
#include <LibGfx/Painter.h>
#include <WindowServer/MenuManager.h>
namespace WindowServer {
static AppletManager* s_the;
Vector<String> order_vector;
AppletManager::AppletManager()
{
s_the = this;
auto wm_config = Core::ConfigFile::open("/etc/WindowServer/WindowServer.ini");
auto order = wm_config->read_entry("Applet", "Order");
order_vector = order.split(',');
}
AppletManager::~AppletManager()
{
}
AppletManager& AppletManager::the()
{
VERIFY(s_the);
return *s_the;
}
void AppletManager::set_position(const Gfx::IntPoint& position)
{
m_window->move_to(position);
m_window->set_visible(true);
}
void AppletManager::set_hovered_applet(Window* applet)
{
if (m_hovered_applet == applet)
return;
if (m_hovered_applet)
Core::EventLoop::current().post_event(*m_hovered_applet, make<Event>(Event::WindowLeft));
m_hovered_applet = applet;
if (m_hovered_applet)
Core::EventLoop::current().post_event(*m_hovered_applet, make<Event>(Event::WindowEntered));
}
void AppletManager::event(Core::Event& event)
{
if (event.type() == Event::WindowLeft && m_hovered_applet) {
set_hovered_applet(nullptr);
return;
}
if (!is<MouseEvent>(event))
return;
auto& mouse_event = static_cast<MouseEvent&>(event);
for (auto& applet : m_applets) {
if (!applet)
continue;
if (!applet->rect_in_applet_area().contains(mouse_event.position()))
continue;
auto local_event = mouse_event.translated(-applet->rect_in_applet_area().location());
set_hovered_applet(applet);
Core::EventLoop::current().post_event(*applet, make<MouseEvent>(local_event));
return;
}
}
void AppletManager::add_applet(Window& applet)
{
m_applets.append(applet);
// Prune any dead weak pointers from the applet list.
m_applets.remove_all_matching([](auto& entry) {
return entry.is_null();
});
quick_sort(m_applets, [](auto& a, auto& b) {
auto index_a = order_vector.find_first_index(a->title());
auto index_b = order_vector.find_first_index(b->title());
return index_a.value_or(0) > index_b.value_or(0);
});
relayout();
MenuManager::the().refresh();
}
void AppletManager::relayout()
{
constexpr int applet_spacing = 4;
constexpr int applet_window_height = 20;
int total_width = 0;
for (auto& existing_applet : m_applets) {
total_width += max(0, existing_applet->size().width()) + applet_spacing;
}
if (total_width > 0)
total_width -= applet_spacing;
auto right_edge_x = total_width;
for (auto& existing_applet : m_applets) {
auto applet_size = existing_applet->size();
Gfx::IntRect new_applet_rect(right_edge_x - applet_size.width(), 0, applet_size.width(), applet_size.height());
Gfx::IntRect dummy_container_rect(0, 0, 0, applet_window_height);
new_applet_rect.center_vertically_within(dummy_container_rect);
existing_applet->set_rect_in_applet_area(new_applet_rect);
right_edge_x = existing_applet->rect_in_applet_area().x() - applet_spacing;
}
if (!m_window) {
m_window = Window::construct(*this, WindowType::AppletArea);
m_window->set_visible(false);
}
Gfx::IntRect rect { m_window->position(), Gfx::IntSize { total_width, applet_window_height } };
if (m_window->rect() == rect)
return;
m_window->set_rect(rect);
repaint();
WindowManager::the().tell_wm_listeners_applet_area_size_changed(rect.size());
}
void AppletManager::repaint()
{
if (!m_window) {
return;
}
auto rect = Gfx::IntRect { { 0, 0 }, m_window->size() };
if (!rect.is_empty()) {
Gfx::Painter painter(*m_window->backing_store());
painter.fill_rect(rect, WindowManager::the().palette().button());
}
}
void AppletManager::did_change_theme()
{
repaint();
}
void AppletManager::remove_applet(Window& applet)
{
m_applets.remove_first_matching([&](auto& entry) {
return &applet == entry.ptr();
});
relayout();
}
void AppletManager::draw()
{
for (auto& applet : m_applets) {
if (!applet)
continue;
draw_applet(*applet);
}
}
void AppletManager::draw_applet(const Window& applet)
{
if (!applet.backing_store())
return;
Gfx::Painter painter(*m_window->backing_store());
Gfx::PainterStateSaver saver(painter);
painter.add_clip_rect(applet.rect_in_applet_area());
painter.fill_rect(applet.rect_in_applet_area(), WindowManager::the().palette().button());
painter.blit(applet.rect_in_applet_area().location(), *applet.backing_store(), applet.backing_store()->rect());
}
void AppletManager::invalidate_applet(const Window& applet, const Gfx::IntRect&)
{
draw_applet(applet);
draw();
// FIXME: Invalidate only the exact rect we've been given.
if (m_window)
m_window->invalidate();
}
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/macie2/model/SensitiveDataItem.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Macie2
{
namespace Model
{
SensitiveDataItem::SensitiveDataItem() :
m_category(SensitiveDataItemCategory::NOT_SET),
m_categoryHasBeenSet(false),
m_detectionsHasBeenSet(false),
m_totalCount(0),
m_totalCountHasBeenSet(false)
{
}
SensitiveDataItem::SensitiveDataItem(JsonView jsonValue) :
m_category(SensitiveDataItemCategory::NOT_SET),
m_categoryHasBeenSet(false),
m_detectionsHasBeenSet(false),
m_totalCount(0),
m_totalCountHasBeenSet(false)
{
*this = jsonValue;
}
SensitiveDataItem& SensitiveDataItem::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("category"))
{
m_category = SensitiveDataItemCategoryMapper::GetSensitiveDataItemCategoryForName(jsonValue.GetString("category"));
m_categoryHasBeenSet = true;
}
if(jsonValue.ValueExists("detections"))
{
Array<JsonView> detectionsJsonList = jsonValue.GetArray("detections");
for(unsigned detectionsIndex = 0; detectionsIndex < detectionsJsonList.GetLength(); ++detectionsIndex)
{
m_detections.push_back(detectionsJsonList[detectionsIndex].AsObject());
}
m_detectionsHasBeenSet = true;
}
if(jsonValue.ValueExists("totalCount"))
{
m_totalCount = jsonValue.GetInt64("totalCount");
m_totalCountHasBeenSet = true;
}
return *this;
}
JsonValue SensitiveDataItem::Jsonize() const
{
JsonValue payload;
if(m_categoryHasBeenSet)
{
payload.WithString("category", SensitiveDataItemCategoryMapper::GetNameForSensitiveDataItemCategory(m_category));
}
if(m_detectionsHasBeenSet)
{
Array<JsonValue> detectionsJsonList(m_detections.size());
for(unsigned detectionsIndex = 0; detectionsIndex < detectionsJsonList.GetLength(); ++detectionsIndex)
{
detectionsJsonList[detectionsIndex].AsObject(m_detections[detectionsIndex].Jsonize());
}
payload.WithArray("detections", std::move(detectionsJsonList));
}
if(m_totalCountHasBeenSet)
{
payload.WithInt64("totalCount", m_totalCount);
}
return payload;
}
} // namespace Model
} // namespace Macie2
} // namespace Aws
|
/*
* SHA-3
* (C) 2010,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/sha3.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
#include <botan/internal/sha3_round.h>
#include <botan/exceptn.h>
#include <botan/cpuid.h>
namespace Botan {
void SHA_3::permute(uint64_t A[25])
{
#if defined(BOTAN_HAS_SHA3_BMI2)
if(CPUID::has_bmi2())
{
return permute_bmi2(A);
}
#endif
static const uint64_t RC[24] = {
0x0000000000000001, 0x0000000000008082, 0x800000000000808A,
0x8000000080008000, 0x000000000000808B, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008A,
0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
0x000000008000808B, 0x800000000000008B, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800A, 0x800000008000000A, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008
};
uint64_t T[25];
for(size_t i = 0; i != 24; i += 2)
{
SHA3_round(T, A, RC[i+0]);
SHA3_round(A, T, RC[i+1]);
}
}
//static
size_t SHA_3::absorb(size_t bitrate,
secure_vector<uint64_t>& S, size_t S_pos,
const uint8_t input[], size_t length)
{
while(length > 0)
{
size_t to_take = std::min(length, bitrate / 8 - S_pos);
length -= to_take;
while(to_take && S_pos % 8)
{
S[S_pos / 8] ^= static_cast<uint64_t>(input[0]) << (8 * (S_pos % 8));
++S_pos;
++input;
--to_take;
}
while(to_take && to_take % 8 == 0)
{
S[S_pos / 8] ^= load_le<uint64_t>(input, 0);
S_pos += 8;
input += 8;
to_take -= 8;
}
while(to_take)
{
S[S_pos / 8] ^= static_cast<uint64_t>(input[0]) << (8 * (S_pos % 8));
++S_pos;
++input;
--to_take;
}
if(S_pos == bitrate / 8)
{
SHA_3::permute(S.data());
S_pos = 0;
}
}
return S_pos;
}
//static
void SHA_3::finish(size_t bitrate,
secure_vector<uint64_t>& S, size_t S_pos,
uint8_t init_pad, uint8_t fini_pad)
{
BOTAN_ARG_CHECK(bitrate % 64 == 0, "SHA-3 bitrate must be multiple of 64");
S[S_pos / 8] ^= static_cast<uint64_t>(init_pad) << (8 * (S_pos % 8));
S[(bitrate / 64) - 1] ^= static_cast<uint64_t>(fini_pad) << 56;
SHA_3::permute(S.data());
}
//static
void SHA_3::expand(size_t bitrate,
secure_vector<uint64_t>& S,
uint8_t output[], size_t output_length)
{
BOTAN_ARG_CHECK(bitrate % 64 == 0, "SHA-3 bitrate must be multiple of 64");
const size_t byterate = bitrate / 8;
while(output_length > 0)
{
const size_t copying = std::min(byterate, output_length);
copy_out_vec_le(output, copying, S);
output += copying;
output_length -= copying;
if(output_length > 0)
{
SHA_3::permute(S.data());
}
}
}
SHA_3::SHA_3(size_t output_bits) :
m_output_bits(output_bits),
m_bitrate(1600 - 2*output_bits),
m_S(25),
m_S_pos(0)
{
// We only support the parameters for SHA-3 in this constructor
if(output_bits != 224 && output_bits != 256 &&
output_bits != 384 && output_bits != 512)
throw Invalid_Argument("SHA_3: Invalid output length " +
std::to_string(output_bits));
}
std::string SHA_3::name() const
{
return "SHA-3(" + std::to_string(m_output_bits) + ")";
}
std::string SHA_3::provider() const
{
#if defined(BOTAN_HAS_SHA3_BMI2)
if(CPUID::has_bmi2())
{
return "bmi2";
}
#endif
return "base";
}
std::unique_ptr<HashFunction> SHA_3::copy_state() const
{
return std::unique_ptr<HashFunction>(new SHA_3(*this));
}
HashFunction* SHA_3::clone() const
{
return new SHA_3(m_output_bits);
}
void SHA_3::clear()
{
zeroise(m_S);
m_S_pos = 0;
}
void SHA_3::add_data(const uint8_t input[], size_t length)
{
m_S_pos = SHA_3::absorb(m_bitrate, m_S, m_S_pos, input, length);
}
void SHA_3::final_result(uint8_t output[])
{
SHA_3::finish(m_bitrate, m_S, m_S_pos, 0x06, 0x80);
/*
* We never have to run the permutation again because we only support
* limited output lengths
*/
copy_out_vec_le(output, m_output_bits/8, m_S);
clear();
}
}
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <stdio.h>
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include "SingleImplDefs.h"
#include "SingleImpl.h"
#include "SingleImplUtil.h"
#include "Debug.h"
#include "DexLoader.h"
#include "DexOutput.h"
#include "DexUtil.h"
#include "ReachableClasses.h"
#include "Resolver.h"
#include "Trace.h"
#include "Walkers.h"
struct AnalysisImpl : SingleImplAnalysis {
AnalysisImpl(const Scope& scope, DexClasses& primary_dex)
: SingleImplAnalysis(), scope(scope) {
for (const auto& cls : primary_dex) {
primary.insert(cls->get_type());
}
}
void create_single_impl(const TypeMap& single_impl,
const TypeSet& intfs,
const SingleImplConfig& config);
void collect_field_defs();
void collect_method_defs();
void analyze_opcodes();
void escape_not_in_primary();
void remove_escaped();
private:
DexType* get_and_check_single_impl(DexType* type);
void collect_children(const TypeSet& intfs);
void check_impl_hierarchy();
void escape_with_clinit();
void escape_with_sfields();
void filter_single_impl(const SingleImplConfig& config);
void filter_do_not_strip();
void filter_list(const std::vector<std::string>& list, bool keep_match);
private:
const Scope& scope;
std::unordered_set<DexType*> primary;
};
/**
* Get the single impl if the type is a single impl or an array of it.
* When an array mark the single impl as having an array type.
* Return nullptr otherwise.
*/
DexType* AnalysisImpl::get_and_check_single_impl(DexType* type) {
if (exists(single_impls, type)) return type;
if (is_array(type)) {
auto array_type = get_array_type(type);
assert(array_type);
const auto sit = single_impls.find(array_type);
if (sit != single_impls.end()) {
escape_interface(sit->first, HAS_ARRAY_TYPE);
return sit->first;
}
}
return nullptr;
}
/**
* Find all single implemented interfaces.
*/
void AnalysisImpl::create_single_impl(const TypeMap& single_impl,
const TypeSet& intfs,
const SingleImplConfig& config) {
for (const auto intf_it : single_impl) {
auto intf = intf_it.first;
auto intf_cls = type_class(intf);
always_assert(intf_cls && !intf_cls->is_external());
if (is_annotation(intf_cls)) continue;
auto impl = intf_it.second;
auto impl_cls = type_class(impl);
always_assert(impl_cls && !impl_cls->is_external());
if (is_annotation(impl_cls)) continue;
single_impls[intf].cls = impl;
}
collect_children(intfs);
check_impl_hierarchy();
escape_with_clinit();
escape_with_sfields();
filter_single_impl(config);
filter_do_not_strip();
}
/**
* Filter common function for both white and black list.
*/
void AnalysisImpl::filter_list(
const std::vector<std::string>& list,
bool keep_match
) {
if (list.empty()) return;
auto find_in_list = [&](const char* name) {
for (auto& el_str : list) {
auto const el_name = el_str.c_str();
if (strncmp(name, el_name, strlen(el_name)) == 0) {
return true;
}
}
return false;
};
for (const auto intf_it : single_impls) {
const auto intf = intf_it.first;
const auto intf_name = intf->get_name()->c_str();
bool match = find_in_list(intf_name);
if (match && keep_match) continue;
if (!match && !keep_match) continue;
escape_interface(intf, FILTERED);
}
}
/**
* Apply filters to the set of single impl found.
* White lists come first, then black lists.
*/
void AnalysisImpl::filter_single_impl(const SingleImplConfig& config) {
filter_list(config.white_list, true);
filter_list(config.package_white_list, true);
filter_list(config.black_list, false);
filter_list(config.package_black_list, false);
}
/**
* Do not optimize DoNotStrip interfaces.
*/
void AnalysisImpl::filter_do_not_strip() {
for (const auto intf_it : single_impls) {
if (!can_delete(type_class(intf_it.first))) {
escape_interface(intf_it.first, DO_NOT_STRIP);
}
}
}
/**
* Collect direct children of interfaces.
*/
void AnalysisImpl::collect_children(const TypeSet& intfs) {
for (auto& intf : intfs) {
auto supers = type_class(intf)->get_interfaces();
for (auto super : supers->get_type_list()) {
auto super_it = single_impls.find(super);
if (super_it != single_impls.end()) {
super_it->second.children.insert(intf);
}
}
}
}
/**
* Escape if any parent is not known to redex.
*/
void AnalysisImpl::check_impl_hierarchy() {
for (auto& intf_it : single_impls) {
if (!has_hierarchy_in_scope(type_class(intf_it.second.cls))) {
escape_interface(intf_it.first, IMPL_PARENT_ESCAPED);
}
}
}
/**
* Escape interfaces with static initializer.
*/
void AnalysisImpl::escape_with_clinit() {
for (auto& intf_it : single_impls) {
// strictly speaking this is not checking for a clinit but it's all the
// same. Interfaces should not have static methods and even if so we
// just escape them. From our analysis it turns out there are few with
// clinit only and as expected none with static methods.
if (type_class(intf_it.first)->get_dmethods().size() > 0) {
escape_interface(intf_it.first, CLINIT);
}
}
}
/**
* Escape interfaces with static fields. Also escape the type of the field
* if it is a single impl.
* Interface fields may not be scoped to the interface itself and resolved
* at runtime. So until we have an analysis that can spot those cases we
* give up on interfaces with fields and the type of the field if it is
* a single impl.
*/
void AnalysisImpl::escape_with_sfields() {
for (auto const& intf_it : single_impls) {
auto intf_cls = type_class(intf_it.first);
assert(intf_cls->get_ifields().size() == 0);
always_assert(!intf_cls->is_external());
const auto& sfields = intf_cls->get_sfields();
if (sfields.size() == 0) continue;
escape_interface(intf_it.first, HAS_SFIELDS);
for (auto sfield : sfields) {
auto ftype = sfield->get_class();
auto simpl = get_and_check_single_impl(ftype);
if (simpl) {
escape_interface(simpl, HAS_SFIELDS);
}
}
}
}
/**
* If an interface in primary brings a class not in primary drop the
* optimization.
*/
void AnalysisImpl::escape_not_in_primary() {
for (auto const& intf_it : single_impls) {
if (primary.count(intf_it.first) == 0) continue;
if (primary.count(intf_it.second.cls) == 0) {
escape_interface(intf_it.first, NOT_IN_PRIMARY);
}
}
}
/**
* Clean up the single impl map.
*/
void AnalysisImpl::remove_escaped() {
auto it = single_impls.begin();
while (it != single_impls.end()) {
if (it->second.is_escaped()) {
it = single_impls.erase(it);
} else {
++it;
}
}
}
/**
* Find all fields typed with the single impl interface.
*/
void AnalysisImpl::collect_field_defs() {
walk_fields(scope,
[&](DexField* field) {
auto type = field->get_type();
auto intf = get_and_check_single_impl(type);
if (intf) {
single_impls[intf].fielddefs.push_back(field);
}
});
}
/**
* Find all methods with a single impl interface in their signature.
* Also if a method with the interface in the signature is native mark the
* interface as "escaped".
*/
void AnalysisImpl::collect_method_defs() {
auto check_method_arg = [&](DexType* type, DexMethod* method, bool native) {
auto intf = get_and_check_single_impl(type);
if (!intf) return;
if (native) {
escape_interface(intf, NATIVE_METHOD);
}
if (method->get_class() == intf) {
escape_interface(intf, SELF_REFERENCE);
}
single_impls[intf].methoddefs.insert(method);
};
walk_methods(scope,
[&](DexMethod* method) {
auto proto = method->get_proto();
bool native = is_native(method);
check_method_arg(proto->get_rtype(), method, native);
auto args = proto->get_args();
for (const auto it : args->get_type_list()) {
check_method_arg(it, method, native);
}
});
}
/**
* Find all opcodes that reference a single implemented interface in a typeref,
* fieldref or methodref.
*/
void AnalysisImpl::analyze_opcodes() {
auto check_arg = [&](DexType* type, DexMethod* meth, IRInstruction* insn) {
auto intf = get_and_check_single_impl(type);
if (intf) {
single_impls[intf].methodrefs[meth].insert(insn);
}
};
auto check_sig = [&](DexMethod* meth, IRInstruction* insn) {
// check the sig for single implemented interface
const auto proto = meth->get_proto();
check_arg(proto->get_rtype(), meth, insn);
const auto args = proto->get_args();
for (const auto arg : args->get_type_list()) {
check_arg(arg, meth, insn);
}
};
auto check_field = [&](DexField* field, IRInstruction* insn) {
auto cls = field->get_class();
cls = get_and_check_single_impl(cls);
if (cls) {
escape_interface(cls, HAS_FIELD_REF);
}
const auto type = field->get_type();
auto intf = get_and_check_single_impl(type);
if (intf) {
single_impls[intf].fieldrefs[field].push_back(insn);
}
};
walk_opcodes(scope,
[](DexMethod* method) { return true; },
[&](DexMethod* method, IRInstruction* insn) {
auto op = insn->opcode();
switch (op) {
// type ref
case OPCODE_CONST_CLASS: {
// const_class is problematic because DI can use it as a key
// to mark
// different instances to retrieve, so we simply drop all
// single impl
// that are used with const_class
const auto typeref = insn->get_type();
auto intf = get_and_check_single_impl(typeref);
if (intf) {
escape_interface(intf, CONST_CLASS);
}
return;
}
case OPCODE_CHECK_CAST:
case OPCODE_INSTANCE_OF:
case OPCODE_NEW_INSTANCE:
case OPCODE_NEW_ARRAY:
case OPCODE_FILLED_NEW_ARRAY:
case OPCODE_FILLED_NEW_ARRAY_RANGE: {
auto intf = get_and_check_single_impl(insn->get_type());
if (intf) {
single_impls[intf].typerefs.push_back(insn);
}
return;
}
// field ref
case OPCODE_IGET:
case OPCODE_IGET_WIDE:
case OPCODE_IGET_OBJECT:
case OPCODE_IPUT:
case OPCODE_IPUT_WIDE:
case OPCODE_IPUT_OBJECT: {
auto field =
resolve_field(insn->get_field(), FieldSearch::Instance);
if (field == nullptr) {
field = insn->get_field();
}
check_field(field, insn);
return;
}
case OPCODE_SGET:
case OPCODE_SGET_WIDE:
case OPCODE_SGET_OBJECT:
case OPCODE_SPUT:
case OPCODE_SPUT_WIDE:
case OPCODE_SPUT_OBJECT: {
auto field =
resolve_field(insn->get_field(), FieldSearch::Static);
if (field == nullptr) {
field = insn->get_field();
}
check_field(field, insn);
return;
}
// method ref
case OPCODE_INVOKE_INTERFACE:
case OPCODE_INVOKE_INTERFACE_RANGE: {
// if it is an invoke on the interface method, collect it as
// such
const auto meth = insn->get_method();
const auto owner = meth->get_class();
const auto intf = get_and_check_single_impl(owner);
if (intf) {
// if the method ref is not defined on the interface itself
// drop the optimization
const auto& meths = type_class(intf)->get_vmethods();
if (std::find(meths.begin(), meths.end(), meth) ==
meths.end()) {
escape_interface(intf, UNKNOWN_MREF);
} else {
single_impls[intf].intf_methodrefs[meth].insert(insn);
}
}
check_sig(meth, insn);
return;
}
case OPCODE_INVOKE_DIRECT:
case OPCODE_INVOKE_DIRECT_RANGE:
case OPCODE_INVOKE_STATIC:
case OPCODE_INVOKE_STATIC_RANGE:
case OPCODE_INVOKE_VIRTUAL:
case OPCODE_INVOKE_VIRTUAL_RANGE:
case OPCODE_INVOKE_SUPER:
case OPCODE_INVOKE_SUPER_RANGE: {
const auto meth = insn->get_method();
check_sig(meth, insn);
return;
}
default:
return;
}
});
}
/**
* Main analysis method
*/
std::unique_ptr<SingleImplAnalysis> SingleImplAnalysis::analyze(
const Scope& scope, DexClasses& primary_dex, const TypeMap& single_impl,
const TypeSet& intfs, const SingleImplConfig& config) {
std::unique_ptr<AnalysisImpl> single_impls(
new AnalysisImpl(scope, primary_dex));
single_impls->create_single_impl(single_impl, intfs, config);
single_impls->collect_field_defs();
single_impls->collect_method_defs();
single_impls->analyze_opcodes();
single_impls->escape_not_in_primary();
single_impls->remove_escaped();
return std::move(single_impls);
}
void SingleImplAnalysis::escape_interface(DexType* intf, EscapeReason reason) {
auto sit = single_impls.find(intf);
if (sit == single_impls.end()) return;
sit->second.escape |= reason;
TRACE(INTF, 5, "(ESC) Escape %s => 0x%X\n", SHOW(intf), reason);
const auto intf_cls = type_class(intf);
if (intf_cls) {
const auto super_intfs = intf_cls->get_interfaces();
for (auto super_intf : super_intfs->get_type_list()) {
escape_interface(super_intf, reason);
}
}
}
/**
* Collect the interfaces to optimize for an optimization step.
*/
void SingleImplAnalysis::get_interfaces(TypeList& to_optimize) const {
for (const auto& sit : single_impls) {
auto& data = sit.second;
assert(!data.is_escaped());
if (data.children.empty()) {
to_optimize.push_back(sit.first);
}
}
// make the optimizable list stable. It's extremely useful for debugging
// and also avoids to get different optimizations on different runs on the
// same apk.
// Sort by vtable size and name
std::sort(to_optimize.begin(),
to_optimize.end(),
[](const DexType* type1, const DexType* type2) {
auto size1 = type_class(type1)->get_vmethods().size();
auto size2 = type_class(type2)->get_vmethods().size();
return size1 == size2
? strcmp(type1->get_name()->c_str(),
type2->get_name()->c_str()) < 0
: size1 < size2;
});
}
|
#include"Equalizer.h"
#include"EffectTask.h"
#include"Synth/Synther/Synther.h"
namespace tauFX
{
void Equalizer::SetFreqBandGainTask(int bandIdx, float gainDB)
{
if (synther == nullptr)
return;
EffectTask* task = new EffectTask(this);
task->processCallBack = _SetFreqBandGainTask;
task->valuei[0] = bandIdx;
task->valuef[0] = gainDB;
synther->PostTask(task);
}
void Equalizer::_SetFreqBandGainTask(Task* task)
{
EffectTask* effectTask = (EffectTask*)task;
Equalizer& eq = *(Equalizer*)(effectTask->effect);
eq.SetFreqBandGain(effectTask->valuei[0], effectTask->valuef[0]);
}
}
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/mariadb/v20170312/model/OpenDBExtranetAccessResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Mariadb::V20170312::Model;
using namespace rapidjson;
using namespace std;
OpenDBExtranetAccessResponse::OpenDBExtranetAccessResponse() :
m_flowIdHasBeenSet(false)
{
}
CoreInternalOutcome OpenDBExtranetAccessResponse::Deserialize(const string &payload)
{
Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Error("response `Response` is null or not object"));
}
Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("FlowId") && !rsp["FlowId"].IsNull())
{
if (!rsp["FlowId"].IsInt64())
{
return CoreInternalOutcome(Error("response `FlowId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_flowId = rsp["FlowId"].GetInt64();
m_flowIdHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
int64_t OpenDBExtranetAccessResponse::GetFlowId() const
{
return m_flowId;
}
bool OpenDBExtranetAccessResponse::FlowIdHasBeenSet() const
{
return m_flowIdHasBeenSet;
}
|
#pragma once
#include <stdio.h>
#include <time.h>
#include "decode/common.hpp"
/**
* Wrapper around a CSV file, containing PTU data as well as time and location data
*/
class PTUWriter {
public:
PTUWriter() { m_fd = NULL; };
~PTUWriter() { deinit(); };
bool init(const char *fname);
void deinit();
/**
* Log a new point to file.
*
* @param data data to log
*/
void addPoint(SondeFullData *data);
private:
FILE *m_fd;
};
|
//==============================================================================
// 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
//==============================================================================
//////////////////////////////////////////////////////////////////////////////
// cover test behavior of arithmetic components in simd mode
//////////////////////////////////////////////////////////////////////////////
#include <nt2/boolean/include/functions/seladd.hpp>
#include <vector>
#include <nt2/include/constants/valmin.hpp>
#include <nt2/include/constants/valmax.hpp>
#include <nt2/sdk/meta/as_logical.hpp>
#include <nt2/sdk/unit/tests/cover.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/sdk/simd/io.hpp>
NT2_TEST_CASE_TPL ( seladd_all_types, NT2_SIMD_TYPES)
{
using nt2::seladd;
using nt2::tag::seladd_;
using boost::simd::native;
typedef NT2_SIMD_DEFAULT_EXTENSION ext_t;
typedef native<T,ext_t> nT;
typedef typename nt2::meta::as_logical<T>::type lT;
typedef typename nt2::meta::call<seladd_(lT, T, T)>::type r_t;
// random verifications
nt2::uint32_t NR = NT2_NB_RANDOM_TEST;
std::vector<lT> in0(NR);
std::vector<T> in1(NR), in2(NR);
nt2::roll(in1, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2);
nt2::roll(in2, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2);
std::vector<r_t> ref(NR);
for(nt2::uint32_t i=0; i < NR ; ++i)
{
in0[i] = in1[i] > in2[i];
ref[i] = seladd(in0[i] , in2[i], in1[i]);
}
NT2_COVER_ULP_EQUAL(seladd_, ((nT, in0))((nT, in2))((nT, in1)), ref, 0);
}
|
// Copyright 2020 The Pigweed Authors
//
// 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
//
// https://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 "pw_allocator/block.h"
#include <cstring>
#include <span>
#include "gtest/gtest.h"
using std::byte;
namespace pw::allocator {
TEST(Block, CanCreateSingleBlock) {
constexpr size_t kN = 200;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
auto status = Block::Init(std::span(bytes, kN), &block);
ASSERT_EQ(status, OkStatus());
EXPECT_EQ(block->OuterSize(), kN);
EXPECT_EQ(block->InnerSize(),
kN - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(block->Prev(), nullptr);
EXPECT_EQ(block->Next(), (Block*)((uintptr_t)block + kN));
EXPECT_EQ(block->Used(), false);
EXPECT_EQ(block->Last(), true);
}
TEST(Block, CannotCreateUnalignedSingleBlock) {
constexpr size_t kN = 1024;
// Force alignment, so we can un-force it below
alignas(Block*) byte bytes[kN];
byte* byte_ptr = bytes;
Block* block = nullptr;
auto status = Block::Init(std::span(byte_ptr + 1, kN - 1), &block);
EXPECT_EQ(status, Status::InvalidArgument());
}
TEST(Block, CannotCreateTooSmallBlock) {
constexpr size_t kN = 2;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
auto status = Block::Init(std::span(bytes, kN), &block);
EXPECT_EQ(status, Status::InvalidArgument());
}
TEST(Block, CanSplitBlock) {
constexpr size_t kN = 1024;
constexpr size_t kSplitN = 512;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(kSplitN, &next_block);
ASSERT_EQ(status, OkStatus());
EXPECT_EQ(block->InnerSize(), kSplitN);
EXPECT_EQ(block->OuterSize(),
kSplitN + sizeof(Block) + 2 * PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(block->Last(), false);
EXPECT_EQ(next_block->OuterSize(),
kN - kSplitN - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(next_block->Used(), false);
EXPECT_EQ(next_block->Last(), true);
EXPECT_EQ(block->Next(), next_block);
EXPECT_EQ(next_block->Prev(), block);
}
TEST(Block, CanSplitBlockUnaligned) {
constexpr size_t kN = 1024;
constexpr size_t kSplitN = 513;
alignas(Block*) byte bytes[kN];
// We should split at sizeof(Block) + kSplitN bytes. Then
// we need to round that up to an alignof(Block*) boundary.
uintptr_t split_addr = ((uintptr_t)&bytes) + kSplitN;
split_addr += alignof(Block*) - (split_addr % alignof(Block*));
uintptr_t split_len = split_addr - (uintptr_t)&bytes;
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(kSplitN, &next_block);
ASSERT_EQ(status, OkStatus());
EXPECT_EQ(block->InnerSize(), split_len);
EXPECT_EQ(block->OuterSize(),
split_len + sizeof(Block) + 2 * PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(next_block->OuterSize(),
kN - split_len - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(next_block->Used(), false);
EXPECT_EQ(block->Next(), next_block);
EXPECT_EQ(next_block->Prev(), block);
}
TEST(Block, CanSplitMidBlock) {
// Split once, then split the original block again to ensure that the
// pointers get rewired properly.
// I.e.
// [[ BLOCK 1 ]]
// block1->Split()
// [[ BLOCK1 ]][[ BLOCK2 ]]
// block1->Split()
// [[ BLOCK1 ]][[ BLOCK3 ]][[ BLOCK2 ]]
constexpr size_t kN = 1024;
constexpr size_t kSplit1 = 512;
constexpr size_t kSplit2 = 256;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* block2 = nullptr;
block->Split(kSplit1, &block2);
Block* block3 = nullptr;
block->Split(kSplit2, &block3);
EXPECT_EQ(block->Next(), block3);
EXPECT_EQ(block3->Next(), block2);
EXPECT_EQ(block2->Prev(), block3);
EXPECT_EQ(block3->Prev(), block);
}
TEST(Block, CannotSplitBlockWithoutHeaderSpace) {
constexpr size_t kN = 1024;
constexpr size_t kSplitN =
kN - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET - 1;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(kSplitN, &next_block);
EXPECT_EQ(status, Status::ResourceExhausted());
EXPECT_EQ(next_block, nullptr);
}
TEST(Block, MustProvideNextBlockPointer) {
constexpr size_t kN = 1024;
constexpr size_t kSplitN = kN - sizeof(Block) - 1;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
auto status = block->Split(kSplitN, nullptr);
EXPECT_EQ(status, Status::InvalidArgument());
}
TEST(Block, CannotMakeBlockLargerInSplit) {
// Ensure that we can't ask for more space than the block actually has...
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(block->InnerSize() + 1, &next_block);
EXPECT_EQ(status, Status::OutOfRange());
}
TEST(Block, CannotMakeSecondBlockLargerInSplit) {
// Ensure that the second block in split is at least of the size of header.
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(
block->InnerSize() - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET + 1,
&next_block);
ASSERT_EQ(status, Status::ResourceExhausted());
EXPECT_EQ(next_block, nullptr);
}
TEST(Block, CanMakeZeroSizeFirstBlock) {
// This block does support splitting with zero payload size.
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(0, &next_block);
ASSERT_EQ(status, OkStatus());
EXPECT_EQ(block->InnerSize(), static_cast<size_t>(0));
}
TEST(Block, CanMakeZeroSizeSecondBlock) {
// Likewise, the split block can be zero-width.
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
auto status = block->Split(
block->InnerSize() - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET,
&next_block);
ASSERT_EQ(status, OkStatus());
EXPECT_EQ(next_block->InnerSize(), static_cast<size_t>(0));
}
TEST(Block, CanMarkBlockUsed) {
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
block->MarkUsed();
EXPECT_EQ(block->Used(), true);
// Mark used packs that data into the next pointer. Check that it's still
// valid
EXPECT_EQ(block->Next(), (Block*)((uintptr_t)block + kN));
block->MarkFree();
EXPECT_EQ(block->Used(), false);
}
TEST(Block, CannotSplitUsedBlock) {
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
block->MarkUsed();
Block* next_block = nullptr;
auto status = block->Split(512, &next_block);
EXPECT_EQ(status, Status::FailedPrecondition());
}
TEST(Block, CanMergeWithNextBlock) {
// Do the three way merge from "CanSplitMidBlock", and let's
// merge block 3 and 2
constexpr size_t kN = 1024;
constexpr size_t kSplit1 = 512;
constexpr size_t kSplit2 = 256;
alignas(Block*) byte bytes[kN];
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* block2 = nullptr;
block->Split(kSplit1, &block2);
Block* block3 = nullptr;
block->Split(kSplit2, &block3);
EXPECT_EQ(block3->MergeNext(), OkStatus());
EXPECT_EQ(block->Next(), block3);
EXPECT_EQ(block3->Prev(), block);
EXPECT_EQ(block->InnerSize(), kSplit2);
// The resulting "right hand" block should have an outer size of 1024 - 256 -
// sizeof(Block) - 2*PW_ALLOCATOR_POISON_OFFSET, which accounts for the first
// block.
EXPECT_EQ(block3->OuterSize(),
kN - kSplit2 - sizeof(Block) - 2 * PW_ALLOCATOR_POISON_OFFSET);
}
TEST(Block, CannotMergeWithFirstOrLastBlock) {
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
// Do a split, just to sanity check that the checks on Next/Prev are
// different...
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
block->Split(512, &next_block);
EXPECT_EQ(next_block->MergeNext(), Status::OutOfRange());
EXPECT_EQ(block->MergePrev(), Status::OutOfRange());
}
TEST(Block, CannotMergeUsedBlock) {
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
// Do a split, just to sanity check that the checks on Next/Prev are
// different...
Block* block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &block), OkStatus());
Block* next_block = nullptr;
block->Split(512, &next_block);
block->MarkUsed();
EXPECT_EQ(block->MergeNext(), Status::FailedPrecondition());
EXPECT_EQ(next_block->MergePrev(), Status::FailedPrecondition());
}
TEST(Block, CanCheckValidBlock) {
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* first_block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &first_block), OkStatus());
Block* second_block = nullptr;
first_block->Split(512, &second_block);
Block* third_block = nullptr;
second_block->Split(256, &third_block);
EXPECT_EQ(first_block->IsValid(), true);
EXPECT_EQ(second_block->IsValid(), true);
EXPECT_EQ(third_block->IsValid(), true);
}
TEST(Block, CanCheckInalidBlock) {
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* first_block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &first_block), OkStatus());
Block* second_block = nullptr;
first_block->Split(512, &second_block);
Block* third_block = nullptr;
second_block->Split(256, &third_block);
Block* fourth_block = nullptr;
third_block->Split(128, &fourth_block);
std::byte* next_ptr = reinterpret_cast<std::byte*>(first_block);
memcpy(next_ptr, second_block, sizeof(void*));
EXPECT_EQ(first_block->IsValid(), false);
EXPECT_EQ(second_block->IsValid(), false);
EXPECT_EQ(third_block->IsValid(), true);
EXPECT_EQ(fourth_block->IsValid(), true);
#if defined(PW_ALLOCATOR_POISON_ENABLE) && PW_ALLOCATOR_POISON_ENABLE
std::byte fault_poison[PW_ALLOCATOR_POISON_OFFSET] = {std::byte(0)};
std::byte* front_poison =
reinterpret_cast<std::byte*>(third_block) + sizeof(*third_block);
memcpy(front_poison, fault_poison, PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(third_block->IsValid(), false);
std::byte* end_poison =
reinterpret_cast<std::byte*>(fourth_block) + sizeof(*fourth_block);
memcpy(end_poison, fault_poison, PW_ALLOCATOR_POISON_OFFSET);
EXPECT_EQ(fourth_block->IsValid(), false);
#endif // PW_ALLOCATOR_POISON_ENABLE
}
TEST(Block, CanPoisonBlock) {
#if defined(PW_ALLOCATOR_POISON_ENABLE) && PW_ALLOCATOR_POISON_ENABLE
constexpr size_t kN = 1024;
alignas(Block*) byte bytes[kN];
Block* first_block = nullptr;
EXPECT_EQ(Block::Init(std::span(bytes, kN), &first_block), OkStatus());
Block* second_block = nullptr;
first_block->Split(512, &second_block);
Block* third_block = nullptr;
second_block->Split(256, &third_block);
EXPECT_EQ(first_block->IsValid(), true);
EXPECT_EQ(second_block->IsValid(), true);
EXPECT_EQ(third_block->IsValid(), true);
#endif // PW_ALLOCATOR_POISON_ENABLE
}
} // namespace pw::allocator
|
#pragma once
#include <cassert>
template <typename T>
class MComPtr
{
public:
T* m_p;
MComPtr() : m_p(NULL)
{
}
MComPtr(T *p)
{
m_p = p;
if (m_p)
m_p->AddRef();
}
MComPtr(const MComPtr<T>& p)
{
m_p = p.m_p;
if (m_p)
m_p->AddRef();
}
~MComPtr()
{
if (m_p)
m_p->Release();
}
bool operator==(const MComPtr<T>& p) const
{
return m_p == p.m_p;
}
bool operator!=(const MComPtr<T>& p) const
{
return m_p != p.m_p;
}
bool operator<(const MComPtr<T>& p) const
{
return m_p < p.m_p;
}
bool operator>(const MComPtr<T>& p) const
{
return m_p > p.m_p;
}
bool operator<=(const MComPtr<T>& p) const
{
return m_p <= p.m_p;
}
bool operator>=(const MComPtr<T>& p) const
{
return m_p >= p.m_p;
}
T** operator&()
{
assert(m_p == NULL);
return &m_p;
}
operator T*()
{
return m_p;
}
T* operator->()
{
assert(m_p);
return m_p;
}
T* operator=(T* p)
{
T* old = m_p;
m_p = p;
if (m_p)
m_p->AddRef();
if (old)
old->Release();
return *this;
}
T* operator=(const MComPtr<T>& p)
{
T* old = m_p;
m_p = p.m_p;
if (m_p)
m_p->AddRef();
if (old)
old->Release();
return *this;
}
void Attach(T* p)
{
if (m_p)
m_p->Release();
m_p = p;
}
T* Detach()
{
T* old = m_p;
m_p = NULL;
return old;
}
void Release()
{
if (m_p)
{
m_p->Release();
m_p = NULL;
}
}
};
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.ScriptableObject
#include "UnityEngine/ScriptableObject.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: AutomaticSFXVolumeParamsSO
class AutomaticSFXVolumeParamsSO;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(GlobalNamespace::AutomaticSFXVolumeParamsSO);
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::AutomaticSFXVolumeParamsSO*, "", "AutomaticSFXVolumeParamsSO");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x38
#pragma pack(push, 1)
// Autogenerated type: AutomaticSFXVolumeParamsSO
// [TokenAttribute] Offset: FFFFFFFF
class AutomaticSFXVolumeParamsSO : public UnityEngine::ScriptableObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private System.Single _musicVolumeMultiplier
// Size: 0x4
// Offset: 0x18
float musicVolumeMultiplier;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _threshold
// Size: 0x4
// Offset: 0x1C
float threshold;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _impact
// Size: 0x4
// Offset: 0x20
float impact;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _attackTime
// Size: 0x4
// Offset: 0x24
float attackTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _releaseTime
// Size: 0x4
// Offset: 0x28
float releaseTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _minVolume
// Size: 0x4
// Offset: 0x2C
float minVolume;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _maxVolume
// Size: 0x4
// Offset: 0x30
float maxVolume;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _volumeSmooth
// Size: 0x4
// Offset: 0x34
float volumeSmooth;
// Field size check
static_assert(sizeof(float) == 0x4);
public:
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field reference: private System.Single _musicVolumeMultiplier
float& dyn__musicVolumeMultiplier();
// Get instance field reference: private System.Single _threshold
float& dyn__threshold();
// Get instance field reference: private System.Single _impact
float& dyn__impact();
// Get instance field reference: private System.Single _attackTime
float& dyn__attackTime();
// Get instance field reference: private System.Single _releaseTime
float& dyn__releaseTime();
// Get instance field reference: private System.Single _minVolume
float& dyn__minVolume();
// Get instance field reference: private System.Single _maxVolume
float& dyn__maxVolume();
// Get instance field reference: private System.Single _volumeSmooth
float& dyn__volumeSmooth();
// public System.Single get_musicVolumeMultiplier()
// Offset: 0x261E324
float get_musicVolumeMultiplier();
// public System.Single get_threshold()
// Offset: 0x261E32C
float get_threshold();
// public System.Single get_impact()
// Offset: 0x261E334
float get_impact();
// public System.Single get_attackTime()
// Offset: 0x261E33C
float get_attackTime();
// public System.Single get_releaseTime()
// Offset: 0x261E344
float get_releaseTime();
// public System.Single get_minVolume()
// Offset: 0x261E34C
float get_minVolume();
// public System.Single get_maxVolume()
// Offset: 0x261E354
float get_maxVolume();
// public System.Single get_volumeSmooth()
// Offset: 0x261E35C
float get_volumeSmooth();
// public System.Void .ctor()
// Offset: 0x261E364
// Implemented from: UnityEngine.ScriptableObject
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AutomaticSFXVolumeParamsSO* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::AutomaticSFXVolumeParamsSO::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AutomaticSFXVolumeParamsSO*, creationType>()));
}
}; // AutomaticSFXVolumeParamsSO
#pragma pack(pop)
static check_size<sizeof(AutomaticSFXVolumeParamsSO), 52 + sizeof(float)> __GlobalNamespace_AutomaticSFXVolumeParamsSOSizeCheck;
static_assert(sizeof(AutomaticSFXVolumeParamsSO) == 0x38);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_musicVolumeMultiplier
// Il2CppName: get_musicVolumeMultiplier
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_musicVolumeMultiplier)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_musicVolumeMultiplier", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_threshold
// Il2CppName: get_threshold
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_threshold)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_threshold", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_impact
// Il2CppName: get_impact
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_impact)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_impact", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_attackTime
// Il2CppName: get_attackTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_attackTime)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_attackTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_releaseTime
// Il2CppName: get_releaseTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_releaseTime)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_releaseTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_minVolume
// Il2CppName: get_minVolume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_minVolume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_minVolume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_maxVolume
// Il2CppName: get_maxVolume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_maxVolume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_maxVolume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::get_volumeSmooth
// Il2CppName: get_volumeSmooth
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AutomaticSFXVolumeParamsSO::*)()>(&GlobalNamespace::AutomaticSFXVolumeParamsSO::get_volumeSmooth)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AutomaticSFXVolumeParamsSO*), "get_volumeSmooth", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AutomaticSFXVolumeParamsSO::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
/*
Copyright 2005-2012 Intel Corporation. All Rights Reserved.
The source code contained or described herein and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel
Corporation or its suppliers and licensors. The Material is protected
by worldwide copyright laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded,
posted, transmitted, distributed, or disclosed in any way without
Intel's prior express written permission.
No license under any patent, copyright, trade secret or other
intellectual property right is granted to or conferred upon you by
disclosure or delivery of the Materials, either expressly, by
implication, inducement, estoppel or otherwise. Any license under such
intellectual property rights must be express and approved by Intel in
writing.
*/
#include "proxy.h"
#if !defined(__EXCEPTIONS) && !defined(_CPPUNWIND) && !defined(__SUNPRO_CC) || defined(_XBOX)
#if TBB_USE_EXCEPTIONS
#error Compilation settings do not support exception handling. Please do not set TBB_USE_EXCEPTIONS macro or set it to 0.
#elif !defined(TBB_USE_EXCEPTIONS)
#define TBB_USE_EXCEPTIONS 0
#endif
#elif !defined(TBB_USE_EXCEPTIONS)
#define TBB_USE_EXCEPTIONS 1
#endif
#if MALLOC_LD_PRELOAD
/*** service functions and variables ***/
#include <unistd.h> // for sysconf
#include <dlfcn.h>
static long memoryPageSize;
static inline void initPageSize()
{
memoryPageSize = sysconf(_SC_PAGESIZE);
}
/* For the expected behaviour (i.e., finding malloc/free/etc from libc.so,
not from ld-linux.so) dlsym(RTLD_NEXT) should be called from
a LD_PRELOADed library, not another dynamic library.
So we have to put find_original_malloc here.
*/
extern "C" bool __TBB_internal_find_original_malloc(int num, const char *names[],
void *ptrs[])
{
for (int i=0; i<num; i++)
if (NULL == (ptrs[i] = dlsym (RTLD_NEXT, names[i])))
return false;
return true;
}
/* __TBB_malloc_proxy used as a weak symbol by libtbbmalloc for:
1) detection that the proxy library is loaded
2) check that dlsym("malloc") found something different from our replacement malloc
*/
extern "C" void *__TBB_malloc_proxy() __attribute__ ((alias ("malloc")));
#ifndef __THROW
#define __THROW
#endif
/*** replacements for malloc and the family ***/
extern "C" {
void *malloc(size_t size) __THROW
{
return __TBB_internal_malloc(size);
}
void * calloc(size_t num, size_t size) __THROW
{
return __TBB_internal_calloc(num, size);
}
void free(void *object) __THROW
{
__TBB_internal_free(object);
}
void * realloc(void* ptr, size_t sz) __THROW
{
return __TBB_internal_realloc(ptr, sz);
}
int posix_memalign(void **memptr, size_t alignment, size_t size) __THROW
{
return __TBB_internal_posix_memalign(memptr, alignment, size);
}
/* The older *NIX interface for aligned allocations;
it's formally substituted by posix_memalign and deprecated,
so we do not expect it to cause cyclic dependency with C RTL. */
void * memalign(size_t alignment, size_t size) __THROW
{
return scalable_aligned_malloc(size, alignment);
}
/* valloc allocates memory aligned on a page boundary */
void * valloc(size_t size) __THROW
{
if (! memoryPageSize) initPageSize();
return scalable_aligned_malloc(size, memoryPageSize);
}
/* pvalloc allocates smallest set of complete pages which can hold
the requested number of bytes. Result is aligned on page boundary. */
void * pvalloc(size_t size) __THROW
{
if (! memoryPageSize) initPageSize();
// align size up to the page size
size = ((size-1) | (memoryPageSize-1)) + 1;
return scalable_aligned_malloc(size, memoryPageSize);
}
int mallopt(int /*param*/, int /*value*/) __THROW
{
return 1;
}
} /* extern "C" */
#if __linux__
#include <malloc.h>
#include <string.h> // for memset
extern "C" struct mallinfo mallinfo() __THROW
{
struct mallinfo m;
memset(&m, 0, sizeof(struct mallinfo));
return m;
}
#endif /* __linux__ */
/*** replacements for global operators new and delete ***/
#include <new>
void * operator new(size_t sz) throw (std::bad_alloc) {
void *res = scalable_malloc(sz);
#if TBB_USE_EXCEPTIONS
if (NULL == res)
throw std::bad_alloc();
#endif /* TBB_USE_EXCEPTIONS */
return res;
}
void* operator new[](size_t sz) throw (std::bad_alloc) {
void *res = scalable_malloc(sz);
#if TBB_USE_EXCEPTIONS
if (NULL == res)
throw std::bad_alloc();
#endif /* TBB_USE_EXCEPTIONS */
return res;
}
void operator delete(void* ptr) throw() {
scalable_free(ptr);
}
void operator delete[](void* ptr) throw() {
scalable_free(ptr);
}
void* operator new(size_t sz, const std::nothrow_t&) throw() {
return scalable_malloc(sz);
}
void* operator new[](std::size_t sz, const std::nothrow_t&) throw() {
return scalable_malloc(sz);
}
void operator delete(void* ptr, const std::nothrow_t&) throw() {
scalable_free(ptr);
}
void operator delete[](void* ptr, const std::nothrow_t&) throw() {
scalable_free(ptr);
}
#endif /* MALLOC_LD_PRELOAD */
#ifdef _WIN32
#include <windows.h>
#include <stdio.h>
#include "tbb_function_replacement.h"
void safer_scalable_free2( void *ptr)
{
safer_scalable_free( ptr, NULL );
}
// we do not support _expand();
void* safer_expand( void *, size_t )
{
return NULL;
}
#define __TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(CRTLIB)\
void (*orig_free_##CRTLIB)(void*); \
void safer_scalable_free_##CRTLIB( void *ptr) \
{ \
safer_scalable_free( ptr, orig_free_##CRTLIB ); \
} \
\
size_t (*orig_msize_##CRTLIB)(void*); \
size_t safer_scalable_msize_##CRTLIB( void *ptr) \
{ \
return safer_scalable_msize( ptr, orig_msize_##CRTLIB ); \
} \
\
void* safer_scalable_realloc_##CRTLIB( void *ptr, size_t size ) \
{ \
orig_ptrs func_ptrs = {orig_free_##CRTLIB, orig_msize_##CRTLIB}; \
return safer_scalable_realloc( ptr, size, &func_ptrs ); \
} \
\
void* safer_scalable_aligned_realloc_##CRTLIB( void *ptr, size_t size, size_t aligment ) \
{ \
orig_ptrs func_ptrs = {orig_free_##CRTLIB, orig_msize_##CRTLIB}; \
return safer_scalable_aligned_realloc( ptr, size, aligment, &func_ptrs ); \
}
// limit is 30 bytes/60 symbols per line
const char* known_bytecodes[] = {
#if _WIN64
"4883EC284885C974", //release free() win64
"4883EC384885C975", //release msize() win64
"4885C974375348", //release free() 8.0.50727.42 win64
"48894C24084883EC28BA", //debug prologue for win64
"4C8BC1488B0DA6E4040033", //win64 SDK
"4883EC284885C975", //release msize() 10.0.21003.1 win64
#else
"558BEC6A018B", //debug free() & _msize() 8.0.50727.4053 win32
"6A1868********E8", //release free() 8.0.50727.4053 win32
"6A1C68********E8", //release _msize() 8.0.50727.4053 win32
"8BFF558BEC6A", //debug free() & _msize() 9.0.21022.8 win32
"8BFF558BEC83", //debug free() & _msize() 10.0.21003.1 win32
#endif
NULL
};
#if _WIN64
#define __TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(CRT_VER)\
ReplaceFunctionWithStore( #CRT_VER "d.dll", "free", (FUNCPTR)safer_scalable_free_ ## CRT_VER ## d, known_bytecodes, (FUNCPTR*)&orig_free_ ## CRT_VER ## d ); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "free", (FUNCPTR)safer_scalable_free_ ## CRT_VER, known_bytecodes, (FUNCPTR*)&orig_free_ ## CRT_VER ); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "_msize",(FUNCPTR)safer_scalable_msize_ ## CRT_VER ## d, known_bytecodes, (FUNCPTR*)&orig_msize_ ## CRT_VER ## d ); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "_msize",(FUNCPTR)safer_scalable_msize_ ## CRT_VER, known_bytecodes, (FUNCPTR*)&orig_msize_ ## CRT_VER ); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "realloc", (FUNCPTR)safer_scalable_realloc_ ## CRT_VER ## d, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "realloc", (FUNCPTR)safer_scalable_realloc_ ## CRT_VER, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "_aligned_free", (FUNCPTR)safer_scalable_free_ ## CRT_VER ## d, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "_aligned_free", (FUNCPTR)safer_scalable_free_ ## CRT_VER, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "_aligned_realloc",(FUNCPTR)safer_scalable_aligned_realloc_ ## CRT_VER ## d, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "_aligned_realloc",(FUNCPTR)safer_scalable_aligned_realloc_ ## CRT_VER, 0, NULL);
#else
#define __TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(CRT_VER)\
ReplaceFunctionWithStore( #CRT_VER "d.dll", "free", (FUNCPTR)safer_scalable_free_ ## CRT_VER ## d, known_bytecodes, (FUNCPTR*)&orig_free_ ## CRT_VER ## d ); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "free", (FUNCPTR)safer_scalable_free_ ## CRT_VER, known_bytecodes, (FUNCPTR*)&orig_free_ ## CRT_VER ); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "_msize",(FUNCPTR)safer_scalable_msize_ ## CRT_VER ## d, known_bytecodes, (FUNCPTR*)&orig_msize_ ## CRT_VER ## d ); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "_msize",(FUNCPTR)safer_scalable_msize_ ## CRT_VER, known_bytecodes, (FUNCPTR*)&orig_msize_ ## CRT_VER ); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "realloc", (FUNCPTR)safer_scalable_realloc_ ## CRT_VER ## d, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "realloc", (FUNCPTR)safer_scalable_realloc_ ## CRT_VER, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "_aligned_free", (FUNCPTR)safer_scalable_free_ ## CRT_VER ## d, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "_aligned_free", (FUNCPTR)safer_scalable_free_ ## CRT_VER, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER "d.dll", "_aligned_realloc",(FUNCPTR)safer_scalable_aligned_realloc_ ## CRT_VER ## d, 0, NULL); \
ReplaceFunctionWithStore( #CRT_VER ".dll", "_aligned_realloc",(FUNCPTR)safer_scalable_aligned_realloc_ ## CRT_VER, 0, NULL);
#endif
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr70d);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr70);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr71d);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr71);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr80d);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr80);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr90d);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr90);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr100d);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr100);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr110d);
__TBB_ORIG_ALLOCATOR_REPLACEMENT_WRAPPER(msvcr110);
/*** replacements for global operators new and delete ***/
#include <new>
#if _MSC_VER && !defined(__INTEL_COMPILER)
#pragma warning( push )
#pragma warning( disable : 4290 )
#endif
void * operator_new(size_t sz) throw (std::bad_alloc) {
void *res = scalable_malloc(sz);
if (NULL == res) throw std::bad_alloc();
return res;
}
void* operator_new_arr(size_t sz) throw (std::bad_alloc) {
void *res = scalable_malloc(sz);
if (NULL == res) throw std::bad_alloc();
return res;
}
void operator_delete(void* ptr) throw() {
safer_scalable_free2(ptr);
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
#pragma warning( pop )
#endif
void operator_delete_arr(void* ptr) throw() {
safer_scalable_free2(ptr);
}
void* operator_new_t(size_t sz, const std::nothrow_t&) throw() {
return scalable_malloc(sz);
}
void* operator_new_arr_t(std::size_t sz, const std::nothrow_t&) throw() {
return scalable_malloc(sz);
}
void operator_delete_t(void* ptr, const std::nothrow_t&) throw() {
safer_scalable_free2(ptr);
}
void operator_delete_arr_t(void* ptr, const std::nothrow_t&) throw() {
safer_scalable_free2(ptr);
}
const char* modules_to_replace[] = {
"msvcr80d.dll",
"msvcr80.dll",
"msvcr90d.dll",
"msvcr90.dll",
"msvcr100d.dll",
"msvcr100.dll",
"msvcr110d.dll",
"msvcr110.dll",
"msvcr70d.dll",
"msvcr70.dll",
"msvcr71d.dll",
"msvcr71.dll",
};
/*
We need to replace following functions:
malloc
calloc
_aligned_malloc
_expand (by dummy implementation)
??2@YAPAXI@Z operator new (ia32)
??_U@YAPAXI@Z void * operator new[] (size_t size) (ia32)
??3@YAXPAX@Z operator delete (ia32)
??_V@YAXPAX@Z operator delete[] (ia32)
??2@YAPEAX_K@Z void * operator new(unsigned __int64) (intel64)
??_V@YAXPEAX@Z void * operator new[](unsigned __int64) (intel64)
??3@YAXPEAX@Z operator delete (intel64)
??_V@YAXPEAX@Z operator delete[] (intel64)
??2@YAPAXIABUnothrow_t@std@@@Z void * operator new (size_t sz, const std::nothrow_t&) throw() (optional)
??_U@YAPAXIABUnothrow_t@std@@@Z void * operator new[] (size_t sz, const std::nothrow_t&) throw() (optional)
and these functions have runtime-specific replacement:
realloc
free
_msize
_aligned_realloc
_aligned_free
*/
typedef struct FRData_t {
//char *_module;
const char *_func;
FUNCPTR _fptr;
FRR_ON_ERROR _on_error;
} FRDATA;
FRDATA routines_to_replace[] = {
{ "malloc", (FUNCPTR)scalable_malloc, FRR_FAIL },
{ "calloc", (FUNCPTR)scalable_calloc, FRR_FAIL },
{ "_aligned_malloc", (FUNCPTR)scalable_aligned_malloc, FRR_FAIL },
{ "_expand", (FUNCPTR)safer_expand, FRR_IGNORE },
#if _WIN64
{ "??2@YAPEAX_K@Z", (FUNCPTR)operator_new, FRR_FAIL },
{ "??_U@YAPEAX_K@Z", (FUNCPTR)operator_new_arr, FRR_FAIL },
{ "??3@YAXPEAX@Z", (FUNCPTR)operator_delete, FRR_FAIL },
{ "??_V@YAXPEAX@Z", (FUNCPTR)operator_delete_arr, FRR_FAIL },
#else
{ "??2@YAPAXI@Z", (FUNCPTR)operator_new, FRR_FAIL },
{ "??_U@YAPAXI@Z", (FUNCPTR)operator_new_arr, FRR_FAIL },
{ "??3@YAXPAX@Z", (FUNCPTR)operator_delete, FRR_FAIL },
{ "??_V@YAXPAX@Z", (FUNCPTR)operator_delete_arr, FRR_FAIL },
#endif
{ "??2@YAPAXIABUnothrow_t@std@@@Z", (FUNCPTR)operator_new_t, FRR_IGNORE },
{ "??_U@YAPAXIABUnothrow_t@std@@@Z", (FUNCPTR)operator_new_arr_t, FRR_IGNORE }
};
#ifndef UNICODE
void ReplaceFunctionWithStore( const char*dllName, const char *funcName, FUNCPTR newFunc, const char ** opcodes, FUNCPTR* origFunc )
#else
void ReplaceFunctionWithStore( const wchar_t *dllName, const char *funcName, FUNCPTR newFunc, const char ** opcodes, FUNCPTR* origFunc )
#endif
{
FRR_TYPE type = ReplaceFunction( dllName, funcName, newFunc, opcodes, origFunc );
if (type == FRR_NODLL) return;
if ( type != FRR_OK )
{
fprintf(stderr, "Failed to replace function %s in module %s\n",
funcName, dllName);
exit(1);
}
}
void doMallocReplacement()
{
int i,j;
// Replace functions and keep backup of original code (separate for each runtime)
__TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(msvcr70)
__TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(msvcr71)
__TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(msvcr80)
__TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(msvcr90)
__TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(msvcr100)
__TBB_ORIG_ALLOCATOR_REPLACEMENT_CALL(msvcr110)
// Replace functions without storing original code
int modules_to_replace_count = sizeof(modules_to_replace) / sizeof(modules_to_replace[0]);
int routines_to_replace_count = sizeof(routines_to_replace) / sizeof(routines_to_replace[0]);
for ( j=0; j<modules_to_replace_count; j++ )
for (i = 0; i < routines_to_replace_count; i++)
{
#if !_WIN64
// in Microsoft* Visual Studio* 11 Beta 32-bit operator delete consists of 2 bytes only: short jump to free(ptr);
// replacement should be skipped for this particular case.
if ( (strcmp(modules_to_replace[j],"msvcr110.dll")==0) && (strcmp(routines_to_replace[i]._func,"??3@YAXPAX@Z")==0) ) continue;
#endif
FRR_TYPE type = ReplaceFunction( modules_to_replace[j], routines_to_replace[i]._func, routines_to_replace[i]._fptr, NULL, NULL );
if (type == FRR_NODLL) break;
if (type != FRR_OK && routines_to_replace[i]._on_error==FRR_FAIL)
{
fprintf(stderr, "Failed to replace function %s in module %s\n",
routines_to_replace[i]._func, modules_to_replace[j]);
exit(1);
}
}
}
extern "C" BOOL WINAPI DllMain( HINSTANCE hInst, DWORD callReason, LPVOID reserved )
{
if ( callReason==DLL_PROCESS_ATTACH && reserved && hInst ) {
#if TBBMALLOC_USE_TBB_FOR_ALLOCATOR_ENV_CONTROLLED
char pinEnvVariable[50];
if( GetEnvironmentVariable("TBBMALLOC_USE_TBB_FOR_ALLOCATOR", pinEnvVariable, 50))
{
doMallocReplacement();
}
#else
doMallocReplacement();
#endif
}
return TRUE;
}
// Just to make the linker happy and link the DLL to the application
extern "C" __declspec(dllexport) void __TBB_malloc_proxy()
{
}
#endif //_WIN32
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "RGameMode.h"
#include "RPlayerController.h"
#include "RCharacter.h"
ARGameMode::ARGameMode()
{
PlayerControllerClass = ARPlayerController::StaticClass();
DefaultPawnClass = ARCharacter::StaticClass();
}
|
/*
* (C) Copyright 2009-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include "model/ObsWSpeedTLAD.h"
#include <vector>
#include "eckit/config/Configuration.h"
#include "model/GomQG.h"
#include "model/ObsBias.h"
#include "model/ObsBiasIncrement.h"
#include "model/ObsSpaceQG.h"
#include "model/ObsVecQG.h"
#include "model/QgFortran.h"
#include "oops/base/Variables.h"
#include "oops/util/Logger.h"
// -----------------------------------------------------------------------------
namespace qg {
// -----------------------------------------------------------------------------
static ObsOpTLADMaker<ObsWSpeedTLAD> makerWSpeedTL_("WSpeed");
// -----------------------------------------------------------------------------
ObsWSpeedTLAD::ObsWSpeedTLAD(const ObsSpaceQG & odb, const eckit::Configuration & config)
: traj_(), varin_(std::vector<std::string>{"u", "v"})
{
qg_wspeed_gettraj_f90(odb.nobs(), varin_, traj_.toFortran());
oops::Log::trace() << "ObsWSpeedTLAD created" << std::endl;
}
// -----------------------------------------------------------------------------
void ObsWSpeedTLAD::setTrajectory(const GomQG & gom, const ObsBias &) {
qg_wspeed_settraj_f90(gom.toFortran(), traj_.toFortran());
oops::Log::trace() << "ObsWSpeedTLAD trajectory was set " << traj_ << std::endl;
}
// -----------------------------------------------------------------------------
void ObsWSpeedTLAD::simulateObsTL(const GomQG & gom, ObsVecQG & ovec,
const ObsBiasIncrement & bias) const {
qg_wspeed_equiv_tl_f90(gom.toFortran(), ovec.toFortran(),
traj_.toFortran(), bias.wspd());
}
// -----------------------------------------------------------------------------
void ObsWSpeedTLAD::simulateObsAD(GomQG & gom, const ObsVecQG & ovec,
ObsBiasIncrement & bias) const {
qg_wspeed_equiv_ad_f90(gom.toFortran(), ovec.toFortran(),
traj_.toFortran(), bias.wspd());
}
// -----------------------------------------------------------------------------
void ObsWSpeedTLAD::print(std::ostream & os) const {
os << "QG wind speed observation operator TL/AD";
}
// -----------------------------------------------------------------------------
} // namespace qg
|
#include "InsertSymbolDialog.h"
#include "../util/Button.h"
#include "../util/Label.h"
#include "../util/ScrollBar.h"
#include "../util/ViewPtr.h"
#include "RowLayout.h"
#include "events.h"
#include "symbols.h"
// derived from tvision's tvdemo example app
/*
* Turbo Vision - Version 2.0
*
* Copyright (c) 1994 by Borland International
* All Rights Reserved.
*
*/
using util::Button;
using util::Label;
using util::ScrollBar;
using util::ViewPtr;
namespace tmbasic {
static constexpr std::array<const char*, 256> _cp437toUtf8 = {
"", "☺", "☻", "♥", "♦", "♣", "♠", "•", "◘", "○", "◙", "♂", "♀", "♪", "♫", "☼", "►", "◄", "↕", "‼", "¶", "§",
"▬", "↨", "↑", "↓", "→", "←", "∟", "↔", "▲", "▼", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+",
",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A",
"B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
"X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "⌂", "Ç", "ü", "é", "â",
"ä", "à", "å", "ç", "ê", "ë", "è", "ï", "î", "ì", "Ä", "Å", "É", "æ", "Æ", "ô", "ö", "ò", "û", "ù", "ÿ", "Ö",
"Ü", "¢", "£", "¥", "₧", "ƒ", "á", "í", "ó", "ú", "ñ", "Ñ", "ª", "º", "¿", "⌐", "¬", "½", "¼", "¡", "«", "»",
"░", "▒", "▓", "│", "┤", "╡", "╢", "╖", "╕", "╣", "║", "╗", "╝", "╜", "╛", "┐", "└", "┴", "┬", "├", "─", "┼",
"╞", "╟", "╚", "╔", "╩", "╦", "╠", "═", "╬", "╧", "╨", "╤", "╥", "╙", "╘", "╒", "╓", "╫", "╪", "┘", "┌", "█",
"▄", "▌", "▐", "▀", "α", "ß", "Γ", "π", "Σ", "σ", "µ", "τ", "Φ", "Θ", "Ω", "δ", "∞", "φ", "ε", "∩", "≡", "±",
"≥", "≤", "⌠", "⌡", "÷", "≈", "°", "∙", "·", "√", "ⁿ", "²", "■", ""
};
static int _unicodeTableScrollTop = 0;
class Cp437Table : public TView {
public:
std::function<void(std::string)> setCharFunc;
explicit Cp437Table(const TRect& r) : TView(r) { eventMask |= evKeyboard; }
void draw() override {
TDrawBuffer buf;
TColorAttr color{ 0x30 };
for (ushort y = 0; y <= size.y - 1; y++) {
buf.moveChar(0, ' ', color, static_cast<int16_t>(size.x));
for (ushort x = 0; x <= size.x - 1; x++) {
buf.moveChar(x, static_cast<ushort>(32 * y + x), color, static_cast<ushort>(1));
}
writeLine(0, y, static_cast<int16_t>(size.x), static_cast<ushort>(1), buf);
}
showCursor();
}
void handleEvent(TEvent& event) override {
TView::handleEvent(event);
if (event.what == evMouseDown) {
do {
if (mouseInView(event.mouse.where)) {
TPoint spot = makeLocal(event.mouse.where);
auto i = spot.x + 32 * spot.y;
if (i >= 1 && i <= 254) {
setCharFunc(_cp437toUtf8.at(i));
} else {
setCharFunc(" ");
}
if ((event.mouse.eventFlags & meDoubleClick) != 0) {
TEvent okEvent = { 0 };
okEvent.what = evCommand;
okEvent.message.command = cmOK;
putEvent(okEvent);
clearEvent(event);
return;
}
}
} while (mouseEvent(event, evMouseMove));
clearEvent(event);
}
}
};
class UnicodeTable : public TView {
public:
std::function<void(std::string)> setCharFunc;
explicit UnicodeTable(const TRect& r) : TView(r) { eventMask |= evKeyboard; }
void draw() override {
TDrawBuffer buf;
TColorAttr color{ 0x30 };
for (ushort y = 0; y <= size.y - 1; y++) {
buf.moveChar(0, ' ', color, static_cast<int16_t>(size.x));
for (ushort x = 0; x <= size.x - 1; x++) {
size_t i = 32 * (y + _unicodeTableScrollTop) + x;
if (i < getSymbolCount()) {
buf.moveStr(x, getSymbol(i), color, static_cast<ushort>(1));
}
}
writeLine(0, y, static_cast<int16_t>(size.x), static_cast<ushort>(1), buf);
}
showCursor();
}
void handleEvent(TEvent& event) override {
TView::handleEvent(event);
if (event.what == evMouseDown) {
do {
if (mouseInView(event.mouse.where)) {
TPoint spot = makeLocal(event.mouse.where);
size_t i = spot.x + 32 * (_unicodeTableScrollTop + spot.y);
if (i < getSymbolCount()) {
setCharFunc(getSymbol(i));
} else {
setCharFunc(" ");
}
if ((event.mouse.eventFlags & meDoubleClick) != 0) {
TEvent okEvent = { 0 };
okEvent.what = evCommand;
okEvent.message.command = cmOK;
putEvent(okEvent);
clearEvent(event);
return;
}
}
} while (mouseEvent(event, evMouseMove));
clearEvent(event);
}
}
};
class InsertSymbolDialogPrivate {
public:
std::string selection;
ViewPtr<Label> selectionLabel{ TRect(2, 11, 33, 12) };
ViewPtr<Cp437Table> cp437Table{ TRect(3, 2, 36, 10) };
ViewPtr<UnicodeTable> unicodeTable{ TRect(37, 2, 69, 10) };
ViewPtr<ScrollBar> vScrollBar{ TRect(69, 2, 70, 10) };
};
static void updateSelectionLabel(InsertSymbolDialogPrivate* p) {
if (p->selection.empty()) {
p->selectionLabel->setTitle("No selection");
} else {
p->selectionLabel->setTitle(std::string("Selected: ") + p->selection);
}
p->selectionLabel->drawView();
}
InsertSymbolDialog::InsertSymbolDialog(const std::string& title, const std::string& insertButtonText)
: TDialog(TRect(0, 0, 73, 14), title), TWindowInit(&TDialog::initFrame), _private(new InsertSymbolDialogPrivate()) {
options |= ofCentered;
_private->selectionLabel.addTo(this);
updateSelectionLabel(_private);
_private->cp437Table->setCharFunc = [this](auto str) {
_private->selection = str;
updateSelectionLabel(_private);
};
_private->cp437Table->blockCursor();
_private->cp437Table.addTo(this);
_private->vScrollBar->useBlueColorScheme();
auto symbolCount = static_cast<int>(getSymbolCount());
auto numRows = symbolCount / 32 - _private->vScrollBar->size.y;
if ((symbolCount % 32) != 0) {
numRows++;
}
_private->vScrollBar->setParams(_unicodeTableScrollTop, 0, numRows, _private->vScrollBar->size.y - 1, 1);
_private->vScrollBar.addTo(this);
_private->unicodeTable->setCharFunc = [this](auto str) {
_private->selection = str;
updateSelectionLabel(_private);
};
_private->unicodeTable->blockCursor();
_private->unicodeTable.addTo(this);
ViewPtr<Button> insertButton{ insertButtonText, cmOK, bfDefault };
auto r = getExtent();
RowLayout(
true,
{
insertButton.take(),
new Button("Cancel", cmCancel, bfNormal),
})
.addTo(this, 1, r.b.x - 3, r.b.y - 3);
insertButton->focus();
}
InsertSymbolDialog::~InsertSymbolDialog() {
delete _private;
}
void InsertSymbolDialog::handleEvent(TEvent& event) {
if (event.what == evCommand && event.message.command == cmOK) {
if (_private->selection.empty()) {
messageBox("Please choose a symbol.", mfError | mfOKButton);
clearEvent(event);
}
}
TDialog::handleEvent(event);
if (event.what == evBroadcast) {
if (event.message.command == cmScrollBarChanged) {
_unicodeTableScrollTop = _private->vScrollBar->value;
_private->unicodeTable->drawView();
}
}
}
std::string InsertSymbolDialog::getSelection() const {
return _private->selection;
}
} // namespace tmbasic
|
/**
* \file
*/
#ifndef MOOVE_BUILTIN_REGISTRY_HPP
#define MOOVE_BUITLIN_REGISTRY_HPP
#include "listvar.hpp"
#include "reply.hpp"
#include "string_utils.hpp"
#include <map>
#include <string>
namespace Moove {
class ExecutionState;
class BuiltinRegistry {
public:
typedef Reply (*Function)(ExecutionState& execState, std::unique_ptr<ListVar> args);
private:
typedef std::map<std::string, Function, iless> BuiltinMap;
BuiltinMap m_biMap;
public:
Function findFunction(const std::string& name)const;
void registerFunction(const std::string& name, Function func, bool replace = false);
void unregisterFunction(const std::string& name);
};
} // namespace Moove
#endif
|
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include "platform/platform.h"
#include "T3D/physics/physX/pxMultiActor.h"
#include "console/consoleTypes.h"
#include "core/stream/fileStream.h"
#include "core/stream/bitStream.h"
#include "core/resourceManager.h"
#include "core/strings/stringUnit.h"
#include "sim/netConnection.h"
#include "math/mathIO.h"
#include "math/mathUtils.h"
#include "gfx/gfxTransformSaver.h"
#include "gfx/gfxDrawUtil.h"
#include "gfx/primBuilder.h"
#include "collision/collision.h"
#include "collision/abstractPolyList.h"
#include "ts/tsShapeInstance.h"
#include "ts/tsPartInstance.h"
#include "lighting/lightManager.h"
#include "scene/sceneManager.h"
#include "scene/sceneRenderState.h"
#include "scene/sceneObjectLightingPlugin.h"
#include "T3D/objectTypes.h"
#include "T3D/containerQuery.h"
#include "T3D/fx/particleEmitter.h"
#include "T3D/debris.h"
#include "renderInstance/renderPassManager.h"
#include "gui/worldEditor/editor.h" // For gEditingMission
#include "T3D/physics/physX/px.h"
#include "T3D/physics/physX/pxWorld.h"
#include "T3D/physics/physX/pxMaterial.h"
#include "T3D/physics/physX/pxCasts.h"
#include "T3D/physics/physx/pxUtils.h"
#include "sfx/sfxSystem.h"
#include <NXU_helper.h>
#include <nxu_schema.h>
#include <NXU_customcopy.h>
class PxMultiActor_Notify : public NXU_userNotify
{
protected:
Vector<NxActor*> mActors;
Vector<NxShape*> mShapes;
Vector<NxJoint*> mJoints;
const NxMat34 mTransform;
const Point3F mScale;
F32 mMassScale;
NxCompartment *mCompartment;
PxMaterial *mMaterial;
Vector<String> *mActorUserProperties;
Vector<String> *mJointUserProperties;
public:
void NXU_notifyJoint( NxJoint *joint, const char *userProperties )
{
if ( mJointUserProperties )
mJointUserProperties->push_back( userProperties );
mJoints.push_back( joint );
}
bool NXU_preNotifyJoint( NxJointDesc &joint, const char *userProperties )
{
joint.localAnchor[0].x *= mScale.x;
joint.localAnchor[0].y *= mScale.y;
joint.localAnchor[0].z *= mScale.z;
joint.localAnchor[1].x *= mScale.x;
joint.localAnchor[1].y *= mScale.y;
joint.localAnchor[1].z *= mScale.z;
// The PhysX exporter from 3dsMax doesn't allow creation
// of fixed joints. It also doesn't seem to export the
// joint names! So look for joints which all all the
// motion axes are locked... make those fixed joints.
if ( joint.getType() == NX_JOINT_D6 )
{
NxD6JointDesc *d6Joint = static_cast<NxD6JointDesc*>( &joint );
if ( d6Joint->xMotion == NX_D6JOINT_MOTION_LOCKED &&
d6Joint->yMotion == NX_D6JOINT_MOTION_LOCKED &&
d6Joint->zMotion == NX_D6JOINT_MOTION_LOCKED &&
d6Joint->swing1Motion == NX_D6JOINT_MOTION_LOCKED &&
d6Joint->swing2Motion == NX_D6JOINT_MOTION_LOCKED &&
d6Joint->twistMotion == NX_D6JOINT_MOTION_LOCKED )
{
// Ok... build a new fixed joint.
NxFixedJointDesc fixed;
fixed.actor[0] = joint.actor[0];
fixed.actor[1] = joint.actor[1];
fixed.localNormal[0] = joint.localNormal[0];
fixed.localNormal[1] = joint.localNormal[1];
fixed.localAxis[0] = joint.localAxis[0];
fixed.localAxis[1] = joint.localAxis[1];
fixed.localAnchor[0] = joint.localAnchor[0];
fixed.localAnchor[1] = joint.localAnchor[1];
fixed.maxForce = joint.maxForce;
fixed.maxTorque = joint.maxTorque;
fixed.name = joint.name;
fixed.userData = joint.userData;
fixed.jointFlags = joint.jointFlags;
// What scene are we adding this to?
NxActor *actor = fixed.actor[0] ? fixed.actor[0] : fixed.actor[1];
NxScene &scene = actor->getScene();
NxJoint* theJoint = scene.createJoint( fixed );
mJoints.push_back( theJoint );
if ( mJointUserProperties )
mJointUserProperties->push_back( userProperties );
// Don't generate this joint.
return false;
}
}
return true;
}
void NXU_notifyActor( NxActor *actor, const char *userProperties )
{
mActors.push_back( actor );
// Save the shapes.
for ( U32 i=0; i < actor->getNbShapes(); i++ )
mShapes.push_back( actor->getShapes()[i] );
mActorUserProperties->push_back( userProperties );
};
bool NXU_preNotifyMaterial( NxMaterialDesc &t, const char *userProperties )
{
// Don't generate materials if we have one defined!
return !mMaterial;
}
bool NXU_preNotifyActor( NxActorDesc &actor, const char *userProperties )
{
// Set the right compartment.
actor.compartment = mCompartment;
if ( actor.shapes.size() == 0 )
Con::warnf( "PxMultiActor_Notify::NXU_preNotifyActor, got an actor (%s) with no shapes, was this intentional?", actor.name );
// For every shape, cast to its particular type
// and apply the scale to size, mass and localPosition.
for( S32 i = 0; i < actor.shapes.size(); i++ )
{
// If we have material then set it.
if ( mMaterial )
actor.shapes[i]->materialIndex = mMaterial->getMaterialId();
switch( actor.shapes[i]->getType() )
{
case NX_SHAPE_BOX:
{
NxBoxShapeDesc *boxDesc = (NxBoxShapeDesc*)actor.shapes[i];
boxDesc->mass *= mMassScale;
boxDesc->dimensions.x *= mScale.x;
boxDesc->dimensions.y *= mScale.y;
boxDesc->dimensions.z *= mScale.z;
boxDesc->localPose.t.x *= mScale.x;
boxDesc->localPose.t.y *= mScale.y;
boxDesc->localPose.t.z *= mScale.z;
break;
}
case NX_SHAPE_SPHERE:
{
NxSphereShapeDesc *sphereDesc = (NxSphereShapeDesc*)actor.shapes[i];
sphereDesc->mass *= mMassScale;
// TODO: Spheres do not work with non-uniform
// scales very well... how do we fix this?
sphereDesc->radius *= mScale.x;
sphereDesc->localPose.t.x *= mScale.x;
sphereDesc->localPose.t.y *= mScale.y;
sphereDesc->localPose.t.z *= mScale.z;
break;
}
case NX_SHAPE_CAPSULE:
{
NxCapsuleShapeDesc *capsuleDesc = (NxCapsuleShapeDesc*)actor.shapes[i];
capsuleDesc->mass *= mMassScale;
// TODO: Capsules do not work with non-uniform
// scales very well... how do we fix this?
capsuleDesc->radius *= mScale.x;
capsuleDesc->height *= mScale.y;
capsuleDesc->localPose.t.x *= mScale.x;
capsuleDesc->localPose.t.y *= mScale.y;
capsuleDesc->localPose.t.z *= mScale.z;
break;
}
default:
{
static String lookup[] =
{
"PLANE",
"SPHERE",
"BOX",
"CAPSULE",
"WHEEL",
"CONVEX",
"MESH",
"HEIGHTFIELD"
};
Con::warnf( "PxMultiActor_Notify::NXU_preNotifyActor, unsupported shape type (%s), on Actor (%s)", lookup[actor.shapes[i]->getType()].c_str(), actor.name );
delete actor.shapes[i];
actor.shapes.erase( actor.shapes.begin() + i );
--i;
break;
}
}
}
NxBodyDesc *body = const_cast<NxBodyDesc*>( actor.body );
if ( body )
{
// Must scale all of these parameters, else there will be odd results!
body->mass *= mMassScale;
body->massLocalPose.t.multiply( mMassScale, body->massLocalPose.t );
body->massSpaceInertia.multiply( mMassScale, body->massSpaceInertia );
// Ragdoll damping!
//body->sleepDamping = 1.7f;
//body->linearDamping = 0.4f;
//body->angularDamping = 0.08f;
//body->wakeUpCounter = 0.3f;
}
return true;
};
public:
PxMultiActor_Notify( NxCompartment *compartment,
PxMaterial *material,
const NxMat34& mat,
const Point3F& scale,
Vector<String> *actorProps = NULL,
Vector<String> *jointProps = NULL )
: mCompartment( compartment ),
mMaterial( material ),
mScale( scale ),
mTransform( mat ),
mActorUserProperties( actorProps ),
mJointUserProperties( jointProps )
{
const F32 unit = VectorF( 1.0f, 1.0f, 1.0f ).len();
mMassScale = mScale.len() / unit;
}
virtual ~PxMultiActor_Notify()
{
}
const Vector<NxActor*>& getActors() { return mActors; }
const Vector<NxShape*>& getShapes() { return mShapes; }
const Vector<NxJoint*>& getJoints() { return mJoints; }
};
ConsoleDocClass( PxMultiActorData,
"@brief Defines the properties of a type of PxMultiActor.\n\n"
"Usually it is prefered to use PhysicsShape rather than PxMultiActor because "
"a PhysicsShape is not PhysX specific and can be much easier to setup.\n\n"
"For more information, refer to Nvidia's PhysX docs.\n\n"
"@ingroup Physics"
);
IMPLEMENT_CO_DATABLOCK_V1(PxMultiActorData);
PxMultiActorData::PxMultiActorData()
: material( NULL ),
collection( NULL ),
waterDragScale( 1.0f ),
buoyancyDensity( 1.0f ),
angularDrag( 0.0f ),
linearDrag( 0.0f ),
clientOnly( false ),
singlePlayerOnly( false ),
shapeName( StringTable->insert( "" ) ),
physXStream( StringTable->insert( "" ) ),
breakForce( 0.0f )
{
for ( S32 i = 0; i < MaxCorrectionNodes; i++ )
correctionNodeNames[i] = StringTable->insert( "" );
for ( S32 i = 0; i < MaxCorrectionNodes; i++ )
correctionNodes[i] = -1;
for ( S32 i = 0; i < NumMountPoints; i++ )
{
mountNodeNames[i] = StringTable->insert( "" );
mountPointNode[i] = -1;
}
}
PxMultiActorData::~PxMultiActorData()
{
if ( collection )
NXU::releaseCollection( collection );
}
void PxMultiActorData::initPersistFields()
{
Parent::initPersistFields();
addGroup("Media");
addField( "shapeName", TypeFilename, Offset( shapeName, PxMultiActorData ),
"@brief Path to the .DAE or .DTS file to render.\n\n");
endGroup("Media");
// PhysX collision properties.
addGroup( "Physics" );
addField( "physXStream", TypeFilename, Offset( physXStream, PxMultiActorData ),
"@brief .XML file containing data such as actors, shapes, and joints.\n\n"
"These files can be created using a free PhysX plugin for 3DS Max.\n\n");
addField( "material", TYPEID< PxMaterial >(), Offset( material, PxMultiActorData ),
"@brief An optional PxMaterial to be used for the PxMultiActor.\n\n"
"Defines properties such as friction and restitution. "
"Unrelated to the material used for rendering. The physXStream will contain "
"defined materials that can be customized in 3DS Max. "
"To override the material for all physics shapes in the physXStream, specify a material here.\n\n");
addField( "noCorrection", TypeBool, Offset( noCorrection, PxMultiActorData ),
"@hide" );
UTF8 buff[256];
for ( S32 i=0; i < MaxCorrectionNodes; i++ )
{
//dSprintf( buff, sizeof(buff), "correctionNode%d", i );
addField( buff, TypeString, Offset( correctionNodeNames[i], PxMultiActorData ), "@hide" );
}
for ( S32 i=0; i < NumMountPoints; i++ )
{
//dSprintf( buff, sizeof(buff), "mountNode%d", i );
addField( buff, TypeString, Offset( mountNodeNames[i], PxMultiActorData ), "@hide" );
}
addField( "angularDrag", TypeF32, Offset( angularDrag, PxMultiActorData ),
"@brief Value used to help calculate rotational drag force while submerged in water.\n\n");
addField( "linearDrag", TypeF32, Offset( linearDrag, PxMultiActorData ),
"@brief Value used to help calculate linear drag force while submerged in water.\n\n");
addField( "waterDragScale", TypeF32, Offset( waterDragScale, PxMultiActorData ),
"@brief Scale to apply to linear and angular dampening while submerged in water.\n\n ");
addField( "buoyancyDensity", TypeF32, Offset( buoyancyDensity, PxMultiActorData ),
"@brief The density used to calculate buoyant forces.\n\n"
"The result of the calculated buoyancy is relative to the density of the WaterObject the PxMultiActor is within.\n\n"
"@note This value is necessary because Torque 3D does its own buoyancy simulation. It is not handled by PhysX."
"@see WaterObject::density");
endGroup( "Physics" );
addField( "clientOnly", TypeBool, Offset( clientOnly, PxMultiActorData ),
"@hide");
addField( "singlePlayerOnly", TypeBool, Offset( singlePlayerOnly, PxMultiActorData ),
"@hide");
addField( "breakForce", TypeF32, Offset( breakForce, PxMultiActorData ),
"@brief Force required to break an actor.\n\n"
"This value does not apply to joints. "
"If an actor is associated with a joint it will break whenever the joint does. "
"This allows an actor \"not\" associated with a joint to also be breakable.\n\n");
}
void PxMultiActorData::packData(BitStream* stream)
{
Parent::packData(stream);
stream->writeString( shapeName );
stream->writeString( physXStream );
if( stream->writeFlag( material ) )
stream->writeRangedU32( packed ? SimObjectId( material ) : material->getId(),
DataBlockObjectIdFirst, DataBlockObjectIdLast );
if ( !stream->writeFlag( noCorrection ) )
{
// Write the correction node indices for the client.
for ( S32 i = 0; i < MaxCorrectionNodes; i++ )
stream->write( correctionNodes[i] );
}
for ( S32 i = 0; i < NumMountPoints; i++ )
stream->write( mountPointNode[i] );
stream->write( waterDragScale );
stream->write( buoyancyDensity );
stream->write( angularDrag );
stream->write( linearDrag );
stream->writeFlag( clientOnly );
stream->writeFlag( singlePlayerOnly );
stream->write( breakForce );
}
void PxMultiActorData::unpackData(BitStream* stream)
{
Parent::unpackData(stream);
shapeName = stream->readSTString();
physXStream = stream->readSTString();
if( stream->readFlag() )
material = (PxMaterial*)stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
noCorrection = stream->readFlag();
if ( !noCorrection )
{
for ( S32 i = 0; i < MaxCorrectionNodes; i++ )
stream->read( &correctionNodes[i] );
}
for ( S32 i = 0; i < NumMountPoints; i++ )
stream->read( &mountPointNode[i] );
stream->read( &waterDragScale );
stream->read( &buoyancyDensity );
stream->read( &angularDrag );
stream->read( &linearDrag );
clientOnly = stream->readFlag();
singlePlayerOnly = stream->readFlag();
stream->read( &breakForce );
}
bool PxMultiActorData::preload( bool server, String &errorBuffer )
{
if ( !Parent::preload( server, errorBuffer ) )
return false;
// If the stream is null, exit.
if ( !physXStream || !physXStream[0] )
{
errorBuffer = "PxMultiActorData::preload: physXStream is unset!";
return false;
}
// Set up our buffer for the binary stream filename path.
UTF8 binPhysXStream[260] = { 0 };
const UTF8* ext = dStrrchr( physXStream, '.' );
// Copy the xml stream path except for the extension.
if ( ext )
dStrncpy( binPhysXStream, physXStream, getMin( 260, ext - physXStream ) );
else
dStrncpy( binPhysXStream, physXStream, 260 );
// Concatenate the binary extension.
dStrcat( binPhysXStream, ".nxb" );
// Get the modified times of the two files.
FileTime xmlTime = {0}, binTime = {0};
Platform::getFileTimes( physXStream, NULL, &xmlTime );
Platform::getFileTimes( binPhysXStream, NULL, &binTime );
// If the binary is newer... load that.
if ( Platform::compareFileTimes( binTime, xmlTime ) >= 0 )
_loadCollection( binPhysXStream, true );
// If the binary failed... then load the xml.
if ( !collection )
{
_loadCollection( physXStream, false );
// If loaded... resave the xml in binary format
// for quicker subsequent loads.
if ( collection )
NXU::saveCollection( collection, binPhysXStream, NXU::FT_BINARY );
}
// If it still isn't loaded then we've failed!
if ( !collection )
{
errorBuffer = String::ToString( "PxMultiActorDatas::preload: could not load '%s'!", physXStream );
return false;
}
if (!shapeName || shapeName == '\0')
{
errorBuffer = "PxMultiActorDatas::preload: no shape name!";
return false;
}
shape = ResourceManager::get().load( shapeName );
if (bool(shape) == false)
{
errorBuffer = String::ToString( "PxMultiActorData::preload: unable to load shape: %s", shapeName );
return false;
}
// Find the client side material.
if ( !server && material )
Sim::findObject( SimObjectId(material), material );
// Get the ignore node indexes from the names.
for ( S32 i = 0; i < MaxCorrectionNodes; i++ )
{
if( !correctionNodeNames[i] || !correctionNodeNames[i][0] )
continue;
correctionNodes[i] = shape->findNode( correctionNodeNames[i] );
}
// Resolve mount point node indexes
for ( S32 i = 0; i < NumMountPoints; i++)
{
char fullName[256];
if ( !mountNodeNames[i] || !mountNodeNames[i][0] )
{
dSprintf(fullName,sizeof(fullName),"mount%d",i);
mountPointNode[i] = shape->findNode(fullName);
}
else
mountPointNode[i] = shape->findNode(mountNodeNames[i]);
}
// Register for file change notification to reload the collection
if ( server )
FS::AddChangeNotification( physXStream, this, &PxMultiActorData::_onFileChanged );
return true;
}
void PxMultiActorData::_onFileChanged( const Torque::Path &path )
{
reload();
}
void PxMultiActorData::reload()
{
bool result = _loadCollection( physXStream, false );
if ( !result )
Con::errorf( "PxMultiActorData::reload(), _loadCollection failed..." );
// Inform MultiActors who use this datablock to reload.
mReloadSignal.trigger();
}
bool PxMultiActorData::_loadCollection( const UTF8 *path, bool isBinary )
{
if ( collection )
{
NXU::releaseCollection( collection );
collection = NULL;
}
FileStream fs;
if ( !fs.open( path, Torque::FS::File::Read ) )
return false;
// Load the data into memory.
U32 size = fs.getStreamSize();
FrameTemp<U8> buff( size );
fs.read( size, buff );
// If the stream didn't read anything, there's a problem.
if ( size <= 0 )
return false;
// Ok... try to load it.
collection = NXU::loadCollection( path,
isBinary ? NXU::FT_BINARY : NXU::FT_XML,
buff,
size );
return collection != NULL;
}
bool PxMultiActorData::createActors( NxScene *scene,
NxCompartment *compartment,
const NxMat34 *nxMat,
const Point3F& scale,
Vector<NxActor*> *outActors,
Vector<NxShape*> *outShapes,
Vector<NxJoint*> *outJoints,
Vector<String> *outActorUserProperties,
Vector<String> *outJointUserProperties )
{
if ( !scene )
{
Con::errorf( "PxMultiActorData::createActor() - returned null NxScene" );
return NULL;
}
PxMultiActor_Notify pxNotify( compartment, material, *nxMat, scale, outActorUserProperties, outJointUserProperties );
NXU::instantiateCollection( collection, *gPhysicsSDK, scene, nxMat, &pxNotify );
*outActors = pxNotify.getActors();
*outJoints = pxNotify.getJoints();
if ( outShapes )
*outShapes = pxNotify.getShapes();
if ( outActors->empty() )
{
Con::errorf( "PxMultiActorData::createActors() - NXUStream notifier returned empty actors or joints!" );
return false;
}
return true;
}
ConsoleDocClass( PxMultiActor,
"@brief Represents a destructible physical object simulated using PhysX.\n\n"
"Usually it is prefered to use PhysicsShape and not PxMultiActor because "
"it is not PhysX specific and much easier to setup.\n"
"@see PxMultiActorData.\n"
"@ingroup Physics"
);
IMPLEMENT_CO_NETOBJECT_V1(PxMultiActor);
PxMultiActor::PxMultiActor()
: mShapeInstance( NULL ),
mRootActor( NULL ),
mWorld( NULL ),
mStartImpulse( 0, 0, 0 ),
mResetXfm( true ),
mActorScale( 0, 0, 0 ),
mDebugRender( false ),
mIsDummy( false ),
mBroken( false ),
mDataBlock( NULL )
{
mNetFlags.set( Ghostable | ScopeAlways );
mTypeMask |= StaticObjectType | StaticShapeObjectType;
//mUserData.setObject( this );
}
void PxMultiActor::initPersistFields()
{
Parent::initPersistFields();
/*
// We're overloading these fields from SceneObject
// in order to force it to go thru setTransform!
removeField( "position" );
removeField( "rotation" );
removeField( "scale" );
addGroup( "Transform" );
addProtectedField( "position", TypeMatrixPosition, 0,
&PxMultiActor::_setPositionField,
&PxMultiActor::_getPositionField,
"" );
addProtectedField( "rotation", TypeMatrixRotation, 0,
&PxMultiActor::_setRotationField,
&PxMultiActor::_getRotationField,
"" );
addField( "scale", TypePoint3F, Offset( mObjScale, PxMultiActor ) );
endGroup( "Transform" );
*/
//addGroup("Physics");
// addField( "AngularDrag", TypeF32, )
//endGroup("Physics");
addGroup( "Debug" );
addField( "debugRender", TypeBool, Offset( mDebugRender, PxMultiActor ), "@hide");
addField( "broken", TypeBool, Offset( mBroken, PxMultiActor ), "@hide");
endGroup( "Debug" );
//addGroup("Collision");
//endGroup("Collision");
}
bool PxMultiActor::onAdd()
{
PROFILE_SCOPE( PxMultiActor_OnAdd );
if (!Parent::onAdd() || !mDataBlock )
return false;
mIsDummy = isClientObject() && PHYSICSMGR->isSinglePlayer(); //&& mDataBlock->singlePlayerOnly;
mShapeInstance = new TSShapeInstance( mDataBlock->shape, isClientObject() );
mObjBox = mDataBlock->shape->bounds;
resetWorldBox();
addToScene();
String worldName = isServerObject() ? "server" : "client";
// SinglePlayer objects only have server-side physics representations.
if ( mIsDummy )
worldName = "server";
mWorld = dynamic_cast<PxWorld*>( PHYSICSMGR->getWorld( worldName ) );
if ( !mWorld || !mWorld->getScene() )
{
Con::errorf( "PxMultiActor::onAdd() - PhysXWorld not initialized!" );
return false;
}
applyWarp( getTransform(), true, false );
mResetXfm = getTransform();
if ( !_createActors( getTransform() ) )
{
Con::errorf( "PxMultiActor::onAdd(), _createActors failed" );
return false;
}
if ( !mIsDummy )
mDataBlock->mReloadSignal.notify( this, &PxMultiActor::onFileNotify );
// If the editor is on... let it know!
//if ( gEditingMission )
//onEditorEnable(); // TODO: Fix this up.
PhysicsPlugin::getPhysicsResetSignal().notify( this, &PxMultiActor::onPhysicsReset, 1050.0f );
setAllBroken( false );
if ( isServerObject() )
scriptOnAdd();
return true;
}
void PxMultiActor::onRemove()
{
removeFromScene();
_destroyActors();
mWorld = NULL;
SAFE_DELETE( mShapeInstance );
PhysicsPlugin::getPhysicsResetSignal().remove( this, &PxMultiActor::onPhysicsReset );
if ( !mIsDummy && mDataBlock )
mDataBlock->mReloadSignal.remove( this, &PxMultiActor::onFileNotify );
Parent::onRemove();
}
void PxMultiActor::_destroyActors()
{
// Dummies don't have physics objects.
if ( mIsDummy || !mWorld )
return;
mWorld->releaseWriteLock();
// Clear the root actor.
mRootActor = NULL;
// Clear the relative transforms.
//mRelXfms.clear();
// The shapes are owned by the actors, so
// we just need to clear them.
mShapes.clear();
// Release the joints first.
for( S32 i = 0; i < mJoints.size(); i++ )
{
NxJoint *joint = mJoints[i];
if ( !joint )
continue;
// We allocate per joint userData and we must free it.
PxUserData *jointData = PxUserData::getData( *joint );
if ( jointData )
delete jointData;
mWorld->releaseJoint( *joint );
}
mJoints.clear();
// Now release the actors.
for( S32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
PxUserData *actorData = PxUserData::getData( *actor );
if ( actorData )
delete actorData;
if ( actor )
mWorld->releaseActor( *actor );
}
mActors.clear();
}
bool PxMultiActor::_createActors( const MatrixF &xfm )
{
if ( mIsDummy )
{
// Dummies don't have physics objects, but
// they do handle actor deltas.
PxMultiActor *serverObj = static_cast<PxMultiActor*>( mServerObject.getObject() );
mActorDeltas.setSize( serverObj->mActors.size() );
dMemset( mActorDeltas.address(), 0, mActorDeltas.memSize() );
return true;
}
NxMat34 nxMat;
nxMat.setRowMajor44( xfm );
// Store the scale for comparison in setScale().
mActorScale = getScale();
// Release the write lock so we can create actors.
mWorld->releaseWriteLock();
Vector<String> actorUserProperties;
Vector<String> jointUserProperties;
bool created = mDataBlock->createActors( mWorld->getScene(),
NULL,
&nxMat,
mActorScale,
&mActors,
&mShapes,
&mJoints,
&actorUserProperties,
&jointUserProperties );
// Debug output...
//for ( U32 i = 0; i < mJoints.size(); i++ )
// Con::printf( "Joint0 name: '%s'", mJoints[i]->getName() );
//for ( U32 i = 0; i < actorUserProperties.size(); i++ )
//Con::printf( "actor%i UserProperties: '%s'", i, actorUserProperties[i].c_str() );
//for ( U32 i = 0; i < jointUserProperties.size(); i++ )
// Con::printf( "joint%i UserProperties: '%s'", i, jointUserProperties[i].c_str() );
if ( !created )
{
Con::errorf( "PxMultiActor::_createActors() - failed!" );
return false;
}
// Make the first actor the root actor by default, but
// if we have a kinematic actor then use that.
mRootActor = mActors[0];
for ( S32 i = 0; i < mActors.size(); i++ )
{
if ( mActors[i]->readBodyFlag( NX_BF_KINEMATIC ) )
{
mRootActor = mActors[i];
break;
}
}
mDelta.pos = mDelta.lastPos = getPosition();
mDelta.rot = mDelta.lastRot = getTransform();
bool *usedActors = new bool[mActors.size()];
dMemset( usedActors, 0, sizeof(bool) * mActors.size() );
TSShape *shape = mShapeInstance->getShape();
// Should already be done when actors are destroyed.
mMappedActors.clear();
Vector<String> mappedActorProperties;
// Remap the actors to the shape instance's bone indices.
for( S32 i = 0; i < mShapeInstance->mNodeTransforms.size(); i++ )
{
if ( !shape )
break;
UTF8 comparisonName[260] = { 0 };
NxActor *actor = NULL;
NxActor *pushActor = NULL;
String actorProperties;
S32 nodeNameIdx = shape->nodes[i].nameIndex;
const UTF8 *nodeName = shape->getName( nodeNameIdx );
S32 dl = -1;
dStrcpy( comparisonName, String::GetTrailingNumber( nodeName, dl ) ); //, ext - nodeName );
dSprintf( comparisonName, sizeof( comparisonName ), "%s_pxactor", comparisonName );
//String test( nodeName );
//AssertFatal( test.find("gableone",0,String::NoCase) == String::NPos, "found it" );
// If we find an actor that corresponds to this node we will
// push it back into the remappedActors vector, otherwise
// we will push back NULL.
for ( S32 j = 0; j < mActors.size(); j++ )
{
actor = mActors[j];
const UTF8 *actorName = actor->getName();
if ( dStricmp( comparisonName, actorName ) == 0 )
{
pushActor = actor;
actorProperties = actorUserProperties[j];
usedActors[j] = true;
break;
}
}
mMappedActors.push_back( pushActor );
mappedActorProperties.push_back( actorProperties );
if ( !pushActor )
dl = -1;
mMappedActorDL.push_back( dl );
// Increase the sleep tolerance.
if ( pushActor )
{
//pushActor->raiseBodyFlag( NX_BF_ENERGY_SLEEP_TEST );
//pushActor->setSleepEnergyThreshold( 2 );
//pushActor->userData = NULL;
}
}
// Delete any unused/orphaned actors.
for ( S32 i = 0; i < mActors.size(); i++ )
{
if ( usedActors[i] )
continue;
NxActor *actor = mActors[i];
Con::errorf( "PxMultiActor::_createActors() - Orphan NxActor - '%s'!", actor->getName() );
if ( actor == mRootActor )
{
Con::errorf( "PxMultiActor::_createActors() - root actor (%s) was orphan, cannot continue.", actor->getName() );
return false;
}
// Remove references to shapes of the deleted actor.
for ( S32 i = 0; i < mShapes.size(); i++ )
{
if ( &(mShapes[i]->getActor()) == actor )
{
mShapes.erase_fast(i);
i--;
}
}
mWorld->releaseActor( *actor );
}
// Done with this helper.
delete [] usedActors;
// Repopulate mActors with one entry per real actor we own.
mActors.clear();
mMappedToActorIndex.clear();
actorUserProperties.clear();
for ( S32 i = 0; i < mMappedActors.size(); i++ )
{
S32 index = -1;
if ( mMappedActors[i] )
{
index = mActors.push_back_unique( mMappedActors[i] );
while ( index >= actorUserProperties.size() )
actorUserProperties.push_back( String::EmptyString );
actorUserProperties[index] = mappedActorProperties[i];
}
mMappedToActorIndex.push_back( index );
}
if ( mActors.size() == 0 )
{
Con::errorf( "PxMultiActor::_createActors, got zero actors! Were all actors orphans?" );
return false;
}
// Initialize the actor deltas.
mActorDeltas.setSize( mActors.size() );
dMemset( mActorDeltas.address(), 0, mActorDeltas.memSize() );
// Assign user data for actors.
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
if ( !actor )
continue;
actor->userData = _createActorUserData( actor, actorUserProperties[i] );
}
//NxActor *actor1;
//NxActor *actor2;
//PxUserData *pUserData;
// Allocate user data for joints.
for ( U32 i = 0; i < mJoints.size(); i++ )
{
NxJoint *joint = mJoints[i];
if ( !joint )
continue;
joint->userData = _createJointUserData( joint, jointUserProperties[i] );
/*
// Set actors attached to joints as not-pushable (by the player).
joint->getActors( &actor1, &actor2 );
if ( actor1 )
{
pUserData = PxUserData::getData( *actor1 );
if ( pUserData )
pUserData->mCanPush = false;
}
if ( actor2 )
{
pUserData = PxUserData::getData( *actor2 );
if ( pUserData )
pUserData->mCanPush = false;
}
*/
}
// Set actors and meshes to the unbroken state.
setAllBroken( false );
return true;
}
PxUserData* PxMultiActor::_createActorUserData( NxActor *actor, String &userProperties )
{
PxUserData *actorData = new PxUserData();
actorData->setObject( this );
// We use this for saving relative xfms for 'broken' actors.
NxMat34 actorPose = actor->getGlobalPose();
NxMat34 actorSpaceXfm;
actorPose.getInverse( actorSpaceXfm );
const String actorName( actor->getName() );
static const String showStr( "PxBrokenShow" );
static const String hideStr( "PxBrokenHide" );
// 3DSMax saves out double newlines, replace them with one.
userProperties.replace( "\r\n", "\n" );
U32 propertyCount = StringUnit::getUnitCount( userProperties, "\n" );
for ( U32 i = 0; i < propertyCount; i++ )
{
String propertyStr = StringUnit::getUnit( userProperties, i, "\n" );
U32 wordCount = StringUnit::getUnitCount( propertyStr, "=" );
if ( wordCount == 0 )
{
// We sometimes get empty lines between properties,
// which doesn't break anything.
continue;
}
if ( wordCount != 2 )
{
Con::warnf( "PxMultiActor::_createActorUserData, malformed UserProperty string (%s) for actor (%s)", propertyStr.c_str(), actorName.c_str() );
continue;
}
String propertyName = StringUnit::getUnit( propertyStr, 0, "=" );
String propertyValue = StringUnit::getUnit( propertyStr, 1, "=" );
Vector<NxActor*> *dstVector = NULL;
if ( propertyName.equal( showStr, String::NoCase ) )
dstVector = &actorData->mBrokenActors;
else if ( propertyName.equal( hideStr, String::NoCase ) )
dstVector = &actorData->mUnbrokenActors;
if ( !dstVector )
continue;
U32 valueCount = StringUnit::getUnitCount( propertyValue, "," );
for ( U32 j = 0; j < valueCount; j++ )
{
String val = StringUnit::getUnit( propertyValue, j, "," );
NxActor *pActor = _findActor( val );
if ( !pActor )
Con::warnf( "PxMultiActor::_createActorUserData, actor (%s) was not found when parsing UserProperties for actor (%s)", val.c_str(), actorName.c_str() );
else
{
dstVector->push_back( pActor );
if ( dstVector == &actorData->mBrokenActors )
{
NxMat34 relXfm = pActor->getGlobalPose();
relXfm.multiply( relXfm, actorSpaceXfm );
actorData->mRelXfm.push_back( relXfm );
}
}
}
}
// Only add a contact signal to this actor if
// we have objects we can break.
if ( actorData->mBrokenActors.size() > 0 &&
mDataBlock->breakForce > 0.0f )
{
actor->setContactReportFlags( NX_NOTIFY_ON_START_TOUCH_FORCE_THRESHOLD | NX_NOTIFY_FORCES );
actor->setContactReportThreshold( mDataBlock->breakForce );
actorData->getContactSignal().notify( this, &PxMultiActor::_onContact );
}
return actorData;
}
PxUserData* PxMultiActor::_createJointUserData( NxJoint *joint, String &userProperties )
{
PxUserData *jointData = new PxUserData();
jointData->setObject( this );
// We use this for saving relative xfms for 'broken' actors.
NxActor *actor0;
NxActor *actor1;
joint->getActors( &actor0, &actor1 );
NxMat34 actorPose = actor0->getGlobalPose();
NxMat34 actorSpaceXfm;
actorPose.getInverse( actorSpaceXfm );
// The PxMultiActor will live longer than the joint
// so this notify shouldn't ever need to be removed. Although if someone
// other than this multiactor were to register for this notify and their
// lifetime could be shorter, then 'they' might have to.
jointData->getOnJointBreakSignal().notify( this, &PxMultiActor::_onJointBreak );
// JCFHACK: put this in userProperties too.
Sim::findObject( "JointBreakEmitter", jointData->mParticleEmitterData );
String showStr( "PxBrokenShow" );
String hideStr( "PxBrokenHide" );
// Max saves out double newlines, replace them with one.
userProperties.replace( "\r\n", "\n" );
U32 propertyCount = StringUnit::getUnitCount( userProperties, "\n" );
for ( U32 i = 0; i < propertyCount; i++ )
{
String propertyStr = StringUnit::getUnit( userProperties, i, "\n" );
U32 wordCount = StringUnit::getUnitCount( propertyStr, "=" );
if ( wordCount == 0 )
{
// We sometimes get empty lines between properties,
// which doesn't break anything.
continue;
}
if ( wordCount != 2 )
{
Con::warnf( "PxMultiActor::_createJointUserData, malformed UserProperty string (%s) for joint (%s)", propertyStr.c_str(), joint->getName() );
continue;
}
String propertyName = StringUnit::getUnit( propertyStr, 0, "=" );
String propertyValue = StringUnit::getUnit( propertyStr, 1, "=" );
Vector<NxActor*> *dstVector = NULL;
if ( propertyName.equal( showStr, String::NoCase ) )
dstVector = &jointData->mBrokenActors;
else if ( propertyName.equal( hideStr, String::NoCase ) )
dstVector = &jointData->mUnbrokenActors;
if ( !dstVector )
continue;
U32 valueCount = StringUnit::getUnitCount( propertyValue, "," );
for ( U32 j = 0; j < valueCount; j++ )
{
String val = StringUnit::getUnit( propertyValue, j, "," );
NxActor *pActor = _findActor( val );
if ( !pActor )
Con::warnf( "PxMultiActor::_createJointUserData, actor (%s) was not found when parsing UserProperties for joint (%s)", val.c_str(), joint->getName() );
else
{
dstVector->push_back( pActor );
if ( dstVector == &jointData->mBrokenActors )
{
NxMat34 relXfm = pActor->getGlobalPose();
relXfm.multiply( relXfm, actorSpaceXfm );
jointData->mRelXfm.push_back( relXfm );
}
}
}
}
return jointData;
}
NxActor* PxMultiActor::_findActor( const String &actorName ) const
{
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
if ( !actor )
continue;
if ( dStricmp( actor->getName(), actorName ) == 0 )
return actor;
}
return NULL;
}
String PxMultiActor::_getMeshName( const NxActor *actor ) const
{
String meshName = actor->getName();
meshName.replace( "_pxactor", "" );
//meshName = StringUnit::getUnit( meshName, 0, "_" );
return meshName;
}
bool PxMultiActor::onNewDataBlock( GameBaseData *dptr, bool reload )
{
mDataBlock = dynamic_cast<PxMultiActorData*>(dptr);
if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
return false;
// JCF: if we supported it, we would recalculate the value of mIsDummy now,
// but that would really hose everything since an object that was a dummy
// wouldn't have any actors and would need to create them, etc...
scriptOnNewDataBlock();
return true;
}
void PxMultiActor::inspectPostApply()
{
// Make sure we call the parent... else
// we won't get transform and scale updates!
Parent::inspectPostApply();
//setMaskBits( LightMask );
setMaskBits( UpdateMask );
}
void PxMultiActor::onStaticModified( const char *slotName, const char *newValue )
{
if ( isProperlyAdded() && dStricmp( slotName, "broken" ) == 0 )
setAllBroken( dAtob(newValue) );
}
void PxMultiActor::onDeleteNotify( SimObject *obj )
{
Parent::onDeleteNotify(obj);
if ( obj == mMount.object )
unmount();
}
void PxMultiActor::onFileNotify()
{
// Destroy the existing actors and recreate them...
mWorld->getPhysicsResults();
_destroyActors();
_createActors( mResetXfm );
}
void PxMultiActor::onPhysicsReset( PhysicsResetEvent reset )
{
// Dummies don't create or destroy actors, they just reuse the
// server object's ones.
if ( mIsDummy )
return;
// Store the reset transform for later use.
if ( reset == PhysicsResetEvent_Store )
{
mRootActor->getGlobalPose().getRowMajor44( mResetXfm );
}
else if ( reset == PhysicsResetEvent_Restore )
{
// Destroy the existing actors and recreate them to
// ensure they are in the proper mission startup state.
mWorld->getPhysicsResults();
_destroyActors();
_createActors( mResetXfm );
}
for ( U32 i = 0; i < mActors.size(); i++ )
{
if ( !mActors[i] )
continue;
mActors[i]->wakeUp();
}
}
void PxMultiActor::prepRenderImage( SceneRenderState *state )
{
PROFILE_SCOPE( PxMultiActor_PrepRenderImage );
if ( !mShapeInstance )
return;
Point3F cameraOffset;
getTransform().getColumn(3,&cameraOffset);
cameraOffset -= state->getDiffuseCameraPosition();
F32 dist = cameraOffset.len();
if ( dist < 0.01f )
dist = 0.01f;
F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));
S32 dl = mShapeInstance->setDetailFromDistance( state, dist * invScale );
if ( dl < 0 )
return;
GFXTransformSaver saver;
// Set up our TS render state here.
TSRenderState rdata;
rdata.setSceneState( state );
// We might have some forward lit materials
// so pass down a query to gather lights.
LightQuery query;
query.init( getWorldSphere() );
rdata.setLightQuery( &query );
MatrixF mat = getRenderTransform();
mat.scale( getScale() );
GFX->setWorldMatrix( mat );
if ( mDebugRender || Con::getBoolVariable( "$PxDebug::render", false ) )
{
ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
ri->renderDelegate.bind( this, &PxMultiActor::_debugRender );
ri->type = RenderPassManager::RIT_Object;
state->getRenderPass()->addInst( ri );
}
else
mShapeInstance->render( rdata );
}
void PxMultiActor::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
{
if ( mShapeInstance )
{
GFXTransformSaver saver;
MatrixF mat = getRenderTransform();
mat.scale( mObjScale );
GFX->multWorld( mat );
//mShapeInstance->renderDebugNodes();
}
Vector<NxActor*> *actors = &mActors;
if ( mIsDummy )
{
PxMultiActor *serverObj = static_cast<PxMultiActor*>( mServerObject.getObject() );
if ( serverObj )
actors = &serverObj->mActors;
}
if ( !actors )
return;
for ( U32 i = 0; i < actors->size(); i++ )
{
NxActor *pActor = (*actors)[i];
if ( !pActor )
continue;
PxUtils::drawActor( pActor );
}
}
void PxMultiActor::_onJointBreak( NxReal breakForce, NxJoint &brokenJoint )
{
// Dummies do not have physics objects
// and shouldn't receive this callback.
if ( mIsDummy )
return;
NxActor *actor0 = NULL;
NxActor *actor1 = NULL;
brokenJoint.getActors( &actor0, &actor1 );
NxMat34 parentPose = actor0->getGlobalPose();
Point3F jointPos = pxCast<Point3F>( brokenJoint.getGlobalAnchor() );
PxUserData *jointData = PxUserData::getData( brokenJoint );
setBroken( parentPose, NxVec3( 0.0f ), jointData, true );
// NOTE: We do not NULL the joint in the list,
// or release it here, as we allow it to be released
// by the _destroyActors function on a reset or destruction
// of the PxMultiActor.
}
void PxMultiActor::_onContact( PhysicsUserData *us,
PhysicsUserData *them,
const Point3F &hitPoint,
const Point3F &hitForce )
{
PxUserData *data = (PxUserData*)us;
if ( data &&
!data->mIsBroken &&
hitForce.len() > mDataBlock->breakForce )
setAllBroken( true );
}
U32 PxMultiActor::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
stream->writeFlag( mDebugRender );
stream->writeFlag( mask & SleepMask );
if ( stream->writeFlag( mask & WarpMask ) )
{
stream->writeAffineTransform( getTransform() );
}
else if ( stream->writeFlag( mask & MoveMask ) )
{
/*
stream->writeAffineTransform( getTransform() );
NxActor *actor = mActors[ mDataBlock->correctionNodes[0] ];
const NxVec3& linVel = actor->getLinearVelocity();
stream->write( linVel.x );
stream->write( linVel.y );
stream->write( linVel.z );
*/
}
// This internally uses the mask passed to it.
if ( mLightPlugin )
retMask |= mLightPlugin->packUpdate( this, LightMask, con, mask, stream );
return retMask;
}
void PxMultiActor::unpackUpdate(NetConnection *con, BitStream *stream)
{
Parent::unpackUpdate(con, stream);
mDebugRender = stream->readFlag();
if ( stream->readFlag() ) // SleepMask
{
for ( S32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
if ( !actor )
continue;
if ( actor )
actor->putToSleep();
}
}
if ( stream->readFlag() ) // WarpMask
{
// If we set a warp mask,
// we need to instantly move
// the actor to the new position
// without applying any corrections.
MatrixF mat;
stream->readAffineTransform( &mat );
applyWarp( mat, true, false );
}
else if ( stream->readFlag() ) // MoveMask
{
/*
MatrixF mat;
stream->readAffineTransform( &mat );
NxVec3 linVel, angVel;
stream->read( &linVel.x );
stream->read( &linVel.y );
stream->read( &linVel.z );
applyCorrection( mat, linVel, angVel );
*/
}
/*
if ( stream->readFlag() ) // ImpulseMask
{
// TODO : Set up correction nodes.
NxVec3 linVel;
stream->read( &linVel.x );
stream->read( &linVel.y );
stream->read( &linVel.z );
NxActor *actor = mActors[ mDataBlock->correctionNodes[0] ];
if ( actor )
{
mWorld->releaseWriteLock();
actor->setLinearVelocity( linVel );
mStartImpulse.zero();
}
else
mStartImpulse.set( linVel.x, linVel.y, linVel.z );
}
*/
if ( mLightPlugin )
mLightPlugin->unpackUpdate( this, con, stream );
}
void PxMultiActor::setScale( const VectorF& scale )
{
if ( scale == getScale() )
return;
// This is so that the level
// designer can change the scale
// of a PhysXSingleActor in the editor
// and have the PhysX representation updated properly.
// First we call the parent's setScale
// so that the ScaleMask can be set.
Parent::setScale( scale );
// Check to see if the scale has really changed.
if ( !isProperlyAdded() || mActorScale.equal( scale ) )
return;
// Recreate the physics actors.
_destroyActors();
_createActors( getTransform() );
}
void PxMultiActor::applyWarp( const MatrixF& newMat, bool interpRender, bool sweep )
{
// Do we have actors to move?
if ( mRootActor )
{
// Get ready to change the physics state.
mWorld->releaseWriteLock();
/// Convert the new transform to nx.
NxMat34 destXfm;
destXfm.setRowMajor44( newMat );
// Get the inverse of the root actor transform
// so we can move all the actors relative to it.
NxMat34 rootInverseXfm;
mRootActor->getGlobalPose().getInverse( rootInverseXfm );
// Offset all the actors.
MatrixF tMat;
NxMat34 newXfm, relXfm;
for ( S32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
if ( !actor )
continue;
const bool isKinematic = actor->readBodyFlag( NX_BF_KINEMATIC );
// Stop any velocity on it.
if ( !isKinematic )
{
actor->setAngularVelocity( NxVec3( 0.0f ) );
actor->setLinearVelocity( NxVec3( 0.0f ) );
}
// Get the transform relative to the current root.
relXfm.multiply( actor->getGlobalPose(), rootInverseXfm );
/*
if ( sweep )
{
actor->getGl obalPose().getRowMajor44( mResetPos[i] );
sweepTest( &newMat );
}
*/
//
newXfm.multiply( relXfm, destXfm );
//if ( isKinematic )
//actor->moveGlobalPose( newXfm );
//else
actor->setGlobalPose( newXfm );
// Reset the delta.
Delta &delta = mActorDeltas[i];
delta.pos = pxCast<Point3F>( newXfm.t );
newXfm.getRowMajor44( tMat );
delta.rot.set( tMat );
if ( !interpRender )
{
mActorDeltas[i].lastPos = mActorDeltas[i].pos;
mActorDeltas[i].lastRot = mActorDeltas[i].rot;
}
}
}
Parent::setTransform( newMat );
mDelta.pos = newMat.getPosition();
mDelta.rot = newMat;
if ( !interpRender )
{
mDelta.lastPos = mDelta.pos;
mDelta.lastRot = mDelta.rot;
}
}
/*
bool PxMultiActor::_setPositionField( void *obj, const char *data )
{
PxMultiActor *object = reinterpret_cast<PxMultiActor*>( obj );
MatrixF transform( object->getTransform() );
Con::setData( TypeMatrixPosition, &transform, 0, 1, &data );
object->setTransform( transform );
return false;
}
const char* PxMultiActor::_getPositionField( void *obj, const char *data )
{
PxMultiActor *object = reinterpret_cast<PxMultiActor*>( obj );
return Con::getData( TypeMatrixPosition,
&object->mObjToWorld,
0 );
}
bool PxMultiActor::_setRotationField( void *obj, const char *data )
{
PxMultiActor *object = reinterpret_cast<PxMultiActor*>( obj );
MatrixF transform( object->getTransform() );
Con::setData( TypeMatrixRotation, &transform, 0, 1, &data );
object->setTransform( transform );
return false;
}
const char* PxMultiActor::_getRotationField( void *obj, const char *data )
{
PxMultiActor *object = reinterpret_cast<PxMultiActor*>( obj );
return Con::getData( TypeMatrixRotation,
&object->mObjToWorld,
0 );
}
*/
void PxMultiActor::setTransform( const MatrixF& mat )
{
applyWarp( mat, false, true );
setMaskBits( WarpMask );
}
void PxMultiActor::mountObject( SceneObject *obj, U32 node )
{
if (obj->getObjectMount())
obj->unmount();
obj->mountObject( this, (node >= 0 && node < PxMultiActorData::NumMountPoints) ? node: 0 );
}
void PxMultiActor::unmountObject( SceneObject *obj )
{
obj->unmountObject( this );
}
bool PxMultiActor::_getNodeTransform( U32 nodeIdx, MatrixF *outXfm )
{
if ( !mShapeInstance )
return false;
PxMultiActor *actorOwner = this;
if ( mIsDummy )
{
actorOwner = static_cast<PxMultiActor*>( mServerObject.getObject() );
if ( !actorOwner )
return false;
}
TSShape *shape = mShapeInstance->getShape();
String nodeName = shape->getNodeName( nodeIdx );
NxActor *pActor = NULL;
UTF8 comparisonName[260] = { 0 };
S32 dummy = -1;
// Convert the passed node name to a valid actor name.
dStrcpy( comparisonName, String::GetTrailingNumber( nodeName, dummy ) );
dSprintf( comparisonName, sizeof( comparisonName ), "%s_pxactor", comparisonName );
// If we have an actor with that name, we are done.
pActor = actorOwner->_findActor( comparisonName );
if ( pActor )
{
pActor->getGlobalPose().getRowMajor44( *outXfm );
return true;
}
// Check if the parent node has an actor...
S32 parentIdx = shape->nodes[nodeIdx].parentIndex;
if ( parentIdx == -1 )
return false;
const String &parentName = shape->getNodeName( parentIdx );
dStrcpy( comparisonName, String::GetTrailingNumber( parentName, dummy ) );
dSprintf( comparisonName, sizeof( comparisonName ), "%s_pxactor", comparisonName );
pActor = actorOwner->_findActor( comparisonName );
if ( !pActor )
return false;
MatrixF actorMat;
pActor->getGlobalPose().getRowMajor44( actorMat );
MatrixF nmat;
QuatF q;
TSTransform::setMatrix( shape->defaultRotations[nodeIdx].getQuatF(&q),shape->defaultTranslations[nodeIdx],&nmat);
*outXfm->mul( actorMat, nmat );
return true;
}
void PxMultiActor::getMountTransform(U32 mountPoint,MatrixF* mat)
{
// Returns mount point to world space transform
if (mountPoint < PxMultiActorData::NumMountPoints) {
S32 ni = mDataBlock->mountPointNode[mountPoint];
if (ni != -1) {
if ( _getNodeTransform( ni, mat ) )
return;
}
}
*mat = mObjToWorld;
}
void PxMultiActor::getRenderMountTransform(U32 mountPoint,MatrixF* mat)
{
// Returns mount point to world space transform
if (mountPoint < PxMultiActorData::NumMountPoints) {
S32 ni = mDataBlock->mountPointNode[mountPoint];
if (ni != -1) {
if ( _getNodeTransform( ni, mat ) )
return;
}
}
*mat = getRenderTransform();
}
void PxMultiActor::processTick( const Move *move )
{
PROFILE_SCOPE( PxMultiActor_ProcessTick );
// Set the last pos/rot to the
// values of the previous tick for interpolateTick.
mDelta.lastPos = mDelta.pos;
mDelta.lastRot = mDelta.rot;
/*
NxActor *corrActor = mActors[ mDataBlock->correctionNodes[0] ];
if ( corrActor->isSleeping() || corrActor->readBodyFlag( NX_BF_FROZEN ) )
{
if ( !mSleepingLastTick )
setMaskBits( WarpMask | SleepMask );
mSleepingLastTick = true;
// HACK! Refactor sleeping so that we don't
// sleep when only one correction actor does.
_updateBounds();
return;
}
mSleepingLastTick = false;
*/
MatrixF mat;
Vector<NxActor*> *actors;
if ( mIsDummy )
{
PxMultiActor *serverObj = static_cast<PxMultiActor*>( mServerObject.getObject() );
if ( !serverObj )
return;
mat = serverObj->getTransform();
actors = &serverObj->mActors;
}
else
{
// Container buoyancy & drag
_updateContainerForces();
// Save the transform from the root actor.
mRootActor->getGlobalPose().getRowMajor44( mat );
actors = &mActors;
}
// Update the transform and the root delta.
Parent::setTransform( mat );
mDelta.pos = mat.getPosition();
mDelta.rot.set( mat );
// On the client we update the individual
// actor deltas as well for interpolation.
if ( isClientObject() )
{
PROFILE_SCOPE( PxMultiActor_ProcessTick_UpdateDeltas );
for ( U32 i = 0; i < mActorDeltas.size(); i++ )
{
if ( !(*actors)[i] )
continue;
Delta &delta = mActorDeltas[i];
// Store the last position.
delta.lastPos = delta.pos;
delta.lastRot = delta.rot;
// Get the new position.
(*actors)[i]->getGlobalPose().getRowMajor44( (NxF32*)mat );
// Calculate the delta between the current
// global pose and the last global pose.
delta.pos = mat.getPosition();
delta.rot.set( mat );
}
}
// Update the bounding box to match the physics.
_updateBounds();
// Set the MoveMask so this will be updated to the client.
//setMaskBits( MoveMask );
}
void PxMultiActor::interpolateTick( F32 delta )
{
PROFILE_SCOPE( PxMultiActor_InterpolateTick );
Point3F interpPos;
QuatF interpRot;
{
// Interpolate the position based on the delta.
interpPos.interpolate( mDelta.pos, mDelta.lastPos, delta );
// Interpolate the rotation based on the delta.
interpRot.interpolate( mDelta.rot, mDelta.lastRot, delta );
// Set up the interpolated transform.
MatrixF interpMat;
interpRot.setMatrix( &interpMat );
interpMat.setPosition( interpPos );
Parent::setRenderTransform( interpMat );
}
PxMultiActor *srcObj = NULL;
if ( mIsDummy )
srcObj = static_cast<PxMultiActor*>( mServerObject.getObject() );
else
srcObj = this;
// JCF: to disable applying NxActor positions to the renderable mesh
// you can uncomment this line.
//srcObj = NULL;
if ( mShapeInstance && srcObj != NULL )
{
mShapeInstance->animate();
getDynamicXfms( srcObj, delta );
}
}
/*
void PxMultiActor::sweepTest( MatrixF *mat )
{
NxVec3 nxCurrPos = getPosition();
// If the position is zero,
// the parent hasn't been updated yet
// and we don't even need to do the sweep test.
// This is a fix for a problem that was happening
// where on the add of the PhysXSingleActor, it would
// set the position to a very small value because it would be getting a hit
// even though the current position was 0.
if ( nxCurrPos.isZero() )
return;
// Set up the flags and the query structure.
NxU32 flags = NX_SF_STATICS | NX_SF_DYNAMICS;
NxSweepQueryHit sweepResult;
dMemset( &sweepResult, 0, sizeof( sweepResult ) );
NxVec3 nxNewPos = mat->getPosition();
// Get the velocity which will be our sweep direction and distance.
NxVec3 nxDir = nxNewPos - nxCurrPos;
if ( nxDir.isZero() )
return;
NxActor *corrActor = mActors[ mDataBlock->correctionNodes[0] ];
// Get the scene and do the sweep.
corrActor->wakeUp();
corrActor->linearSweep( nxDir, flags, NULL, 1, &sweepResult, NULL );
if ( sweepResult.hitShape && sweepResult.t < nxDir.magnitude() )
{
nxDir.normalize();
nxDir *= sweepResult.t;
nxCurrPos += nxDir;
mat->setPosition( Point3F( nxCurrPos.x, nxCurrPos.y, nxCurrPos.z ) );
}
}
*/
/*
void PxMultiActor::applyCorrection( const MatrixF& mat, const NxVec3& linVel, const NxVec3& angVel )
{
// Sometimes the actor hasn't been
// created yet during the call from unpackUpdate.
NxActor *corrActor = mActors[ mDataBlock->correctionNodes[0] ];
if ( !corrActor || mForceSleep )
return;
NxVec3 newPos = mat.getPosition();
NxVec3 currPos = getPosition();
NxVec3 offset = newPos - currPos;
// If the difference isn't large enough,
// just set the new transform, no correction.
if ( offset.magnitude() > 0.3f )
{
// If we're going to set the linear or angular velocity,
// we do it before we add a corrective force, since it would be overwritten otherwise.
NxVec3 currLinVel, currAngVel;
currLinVel = corrActor->getLinearVelocity();
currAngVel = corrActor->getAngularVelocity();
// Scale the corrective force by half,
// otherwise it will over correct and oscillate.
NxVec3 massCent = corrActor->getCMassGlobalPosition();
corrActor->addForceAtPos( offset, massCent, NX_SMOOTH_VELOCITY_CHANGE );
// If the linear velocity is divergent enough, change to server linear velocity.
if ( (linVel - currLinVel).magnitude() > 0.3f )
corrActor->setLinearVelocity( linVel );
// Same for angular.
if ( (angVel - currAngVel).magnitude() > 0.3f )
corrActor->setAngularVelocity( angVel );
}
Parent::setTransform( mat );
}
*/
void PxMultiActor::_updateBounds()
{
PROFILE_SCOPE( PxMultiActor_UpdateBounds );
if ( mIsDummy )
{
PxMultiActor *serverObj = static_cast<PxMultiActor*>( mServerObject.getObject() );
if ( !serverObj )
return;
mWorldBox = serverObj->getWorldBox();
mWorldSphere = serverObj->getWorldSphere();
mObjBox = serverObj->getObjBox();
mRenderWorldBox = serverObj->getRenderWorldBox();
mRenderWorldSphere = mWorldSphere;
return;
}
NxBounds3 bounds;
bounds.setEmpty();
NxBounds3 shapeBounds;
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *pActor = mActors[i];
if ( !pActor || pActor->readActorFlag( NX_AF_DISABLE_COLLISION ) )
continue;
NxShape *const* pShapeArray = pActor->getShapes();
U32 shapeCount = pActor->getNbShapes();
for ( U32 i = 0; i < shapeCount; i++ )
{
// Get the shape's bounds.
pShapeArray[i]->getWorldBounds( shapeBounds );
// Combine them into the total bounds.
bounds.combine( shapeBounds );
}
}
mWorldBox = pxCast<Box3F>( bounds );
mWorldBox.getCenter(&mWorldSphere.center);
mWorldSphere.radius = (mWorldBox.maxExtents - mWorldSphere.center).len();
mObjBox = mWorldBox;
mWorldToObj.mul(mObjBox);
mRenderWorldBox = mWorldBox;
mRenderWorldSphere = mWorldSphere;
}
void PxMultiActor::getDynamicXfms( PxMultiActor *srcObj, F32 dt )
{
PROFILE_SCOPE( PxMultiActor_getDynamicXfms );
Vector<MatrixF> *torqueXfms = &mShapeInstance->mNodeTransforms;
const MatrixF &objectXfm = getRenderWorldTransform();
AssertFatal( torqueXfms->size() == srcObj->mMappedActors.size(), "The two skeletons are different!" );
TSShape *shape = mShapeInstance->getShape();
// TODO: We're currently preparing deltas and getting
// dynamic xforms even if the object isn't visible.
// we should probably try to delay all this until
// we're about to render.
//
/*
// TODO: Set up deltas!
if ( mCurrPos.empty() || mCurrRot.empty() )
_prepareDeltas();
*/
MatrixF globalXfm;
MatrixF mat, tmp;
QuatF newRot;
Point3F newPos;
S32 dl = mShapeInstance->getCurrentDetail();
if ( dl < 0 )
return;
const String &detailName = shape->getName( shape->details[dl].nameIndex );
S32 detailSize = -1;
String::GetTrailingNumber( detailName, detailSize );
for( S32 i = 0; i < srcObj->mMappedActors.size(); i++ )
{
NxActor *actor = srcObj->mMappedActors[i];
if ( !actor || actor->readBodyFlag( NX_BF_KINEMATIC ) )
continue;
// see if the node at this index is part of the
// currently visible detail level.
if ( srcObj->mMappedActorDL[i] != detailSize )
continue;
// Get the right actor delta structure.
U32 index = srcObj->mMappedToActorIndex[i];
const Delta &delta = mActorDeltas[index];
// Do the interpolation.
newRot.interpolate( delta.rot, delta.lastRot, dt );
newRot.setMatrix( &globalXfm );
newPos.interpolate( delta.pos, delta.lastPos, dt );
globalXfm.setPosition( newPos );
(*torqueXfms)[i].mul( objectXfm, globalXfm );
}
}
void PxMultiActor::applyImpulse( const Point3F &pos, const VectorF &vec )
{
// TODO : Implement this based on correction nodes.
/*
if ( !mWorld || !mActor )
return;
mWorld->releaseWriteLock();
NxVec3 linVel = mActor->getLinearVelocity();
NxVec3 nxVel( vel.x, vel.y, vel.z );
mActor->setLinearVelocity(linVel + nxVel);
*/
// JCF: something more complex is required to apply forces / breakage
// on only individual actors, and we don't have enough data to do that
// within this method.
if ( vec.len() > mDataBlock->breakForce )
setAllBroken( true );
NxVec3 nxvec = pxCast<NxVec3>( vec );
NxVec3 nxpos = pxCast<NxVec3>( pos );
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
if ( actor->isDynamic() &&
!actor->readBodyFlag( NX_BF_KINEMATIC ) &&
!actor->readActorFlag( NX_AF_DISABLE_COLLISION ) )
{
actor->addForceAtPos( nxvec, nxpos, NX_IMPULSE );
}
}
//setMaskBits( ImpulseMask );
}
void PxMultiActor::applyRadialImpulse( const Point3F &origin, F32 radius, F32 magnitude )
{
mWorld->releaseWriteLock();
// Find all currently enabled actors hit by the impulse radius...
Vector<NxActor*> hitActors;
NxVec3 nxorigin = pxCast<NxVec3>(origin);
NxSphere impulseSphere( nxorigin, radius );
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *pActor = mActors[i];
if ( pActor->readActorFlag( NX_AF_DISABLE_COLLISION ) ||
!pActor->isDynamic() ||
pActor->readBodyFlag( NX_BF_KINEMATIC ) )
continue;
U32 numShapes = pActor->getNbShapes();
NxShape *const* pShapeArray = pActor->getShapes();
for ( U32 j = 0; j < numShapes; j++ )
{
const NxShape *pShape = pShapeArray[j];
if ( pShape->checkOverlapSphere( impulseSphere ) )
{
hitActors.push_back( pActor );
break;
}
}
}
// Apply forces to hit actors, but swap out for broken
// actors first if appropriate...
for ( U32 i = 0; i < hitActors.size(); i++ )
{
NxActor *pActor = hitActors[i];
PxUserData *pUserData = PxUserData::getData( *pActor );
// TODO: We should calculate the real force accounting
// for falloff before we break things with it.
// If we have enough force, and this is an actor that
// can be 'broken' by impacts, break it now.
if ( pUserData &&
//pUserData->mCanPush &&
pUserData->mBrokenActors.size() > 0 &&
magnitude > mDataBlock->breakForce )
{
setBroken( pActor->getGlobalPose(),
pActor->getLinearVelocity(),
pUserData,
true );
// apply force that would have been applied to this actor
// to the broken actors we just enabled.
for ( U32 j = 0; j < pUserData->mBrokenActors.size(); j++ )
{
NxActor *pBrokenActor = pUserData->mBrokenActors[j];
_applyActorRadialForce( pBrokenActor, nxorigin, radius, magnitude );
}
}
else
{
// Apply force to the actor.
_applyActorRadialForce( pActor, nxorigin, radius, magnitude );
}
}
}
void PxMultiActor::_applyActorRadialForce( NxActor *inActor, const NxVec3 &origin, F32 radius, F32 magnitude )
{
// TODO: We're not getting a good torque force
// out of explosions because we're not picking
// the nearest point on the actor to the origin
// of the radial force.
NxVec3 force = inActor->getCMassGlobalPosition() - origin;
NxF32 dist = force.magnitude();
force.normalize();
if ( dist == 0.0f )
force *= magnitude;
else
force *= mClampF( radius / dist, 0.0f, 1.0f ) * magnitude;
// HACK: Make the position we push the force thru between the
// actor pos and its center of mass. This gives us some
// rotational force as well as make the covered structure
// explode better.
NxVec3 forcePos = ( inActor->getGlobalPosition() + inActor->getCMassGlobalPosition() ) / 2.0f;
inActor->addForceAtPos( force, forcePos, NX_VELOCITY_CHANGE );
}
void PxMultiActor::_updateContainerForces()
{
if ( !mWorld->getEnabled() )
return;
PROFILE_SCOPE( PxMultiActor_updateContainerForces );
// Update container drag and buoyancy properties ( for each Actor )
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *pActor = mActors[i];
if ( !pActor ||
pActor->readBodyFlag(NX_BF_KINEMATIC) ||
pActor->readActorFlag(NX_AF_DISABLE_COLLISION) )
continue;
// Get world bounds of this actor ( the combination of all shape bounds )
NxShape *const* shapes = pActor->getShapes();
NxBounds3 bounds;
bounds.setEmpty();
NxBounds3 shapeBounds;
for ( U32 i = 0; i < pActor->getNbShapes(); i++ )
{
NxShape *pShape = shapes[i];
pShape->getWorldBounds(shapeBounds);
bounds.combine( shapeBounds );
}
Box3F boundsBox = pxCast<Box3F>(bounds);
ContainerQueryInfo info;
info.box = boundsBox;
info.mass = pActor->getMass();
// Find and retreive physics info from intersecting WaterObject(s)
mContainer->findObjects( boundsBox, WaterObjectType|PhysicalZoneObjectType, findRouter, &info );
// Calculate buoyancy and drag
F32 angDrag = mDataBlock->angularDrag;
F32 linDrag = mDataBlock->linearDrag;
F32 buoyancy = 0.0f;
if ( true ) //info.waterCoverage >= 0.1f)
{
F32 waterDragScale = info.waterViscosity * mDataBlock->waterDragScale;
F32 powCoverage = mPow( info.waterCoverage, 0.25f );
if ( info.waterCoverage > 0.0f )
{
//angDrag = mBuildAngDrag * waterDragScale;
//linDrag = mBuildLinDrag * waterDragScale;
angDrag = mLerp( angDrag, angDrag * waterDragScale, powCoverage );
linDrag = mLerp( linDrag, linDrag * waterDragScale, powCoverage );
}
buoyancy = ( info.waterDensity / mDataBlock->buoyancyDensity ) * mPow( info.waterCoverage, 2.0f );
}
// Apply drag (dampening)
pActor->setLinearDamping( linDrag );
pActor->setAngularDamping( angDrag );
// Apply buoyancy force
if ( buoyancy != 0 )
{
// A little hackery to prevent oscillation
// Based on this blog post:
// (http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html)
// JCF: disabled!
NxVec3 gravity;
mWorld->getScene()->getGravity(gravity);
//NxVec3 velocity = pActor->getLinearVelocity();
NxVec3 buoyancyForce = buoyancy * -gravity * TickSec * pActor->getMass();
//F32 currHeight = getPosition().z;
//const F32 C = 2.0f;
//const F32 M = 0.1f;
//if ( currHeight + velocity.z * TickSec * C > info.waterHeight )
// buoyancyForce *= M;
pActor->addForceAtPos( buoyancyForce, pActor->getCMassGlobalPosition(), NX_IMPULSE );
}
// Apply physical zone forces
if ( info.appliedForce.len() > 0.001f )
pActor->addForceAtPos( pxCast<NxVec3>(info.appliedForce), pActor->getCMassGlobalPosition(), NX_IMPULSE );
}
}
/*
ConsoleMethod( PxMultiActor, applyImpulse, void, 3, 3, "applyImpulse - takes a velocity vector to apply")
{
VectorF vec;
dSscanf( argv[2],"%g %g %g",
&vec.x,&vec.y,&vec.z );
object->applyImpulse( vec );
}
*/
void PxMultiActor::setAllBroken( bool isBroken )
{
PROFILE_SCOPE( PxMultiActor_SetAllBroken );
if ( mIsDummy )
{
PxMultiActor *serverObj = static_cast<PxMultiActor*>( mServerObject.getObject() );
serverObj->setAllBroken( isBroken );
return;
}
mWorld->releaseWriteLock();
NxActor *actor0 = NULL;
NxActor *actor1 = NULL;
NxMat34 parentPose;
for ( U32 i = 0; i < mJoints.size(); i++ )
{
NxJoint *joint = mJoints[i];
if ( !joint )
continue;
PxUserData *jointData = PxUserData::getData( *joint );
if ( !jointData )
continue;
joint->getActors( &actor0, &actor1 );
parentPose = actor0->getGlobalPose();
setBroken( parentPose, NxVec3(0.0f), jointData, isBroken );
}
for ( U32 i = 0; i < mActors.size(); i++ )
{
NxActor *actor = mActors[i];
if ( !actor )
continue;
PxUserData *actorData = PxUserData::getData( *actor );
if ( !actorData )
continue;
setBroken( actor->getGlobalPose(),
actor->getLinearVelocity(),
actorData,
isBroken );
}
}
void PxMultiActor::setBroken( const NxMat34 &parentPose,
const NxVec3 &parentVel,
PxUserData *userData,
bool isBroken )
{
PROFILE_SCOPE( PxMultiActor_SetBroken );
// TODO: This function is highly inefficent and
// way too complex to follow... the hacked single
// player mode doesn't help.
// Be careful not to set something broken twice.
if ( isBroken &&
userData->mIsBroken == isBroken )
return;
userData->mIsBroken = isBroken;
Vector<NxActor*> *hideActors = NULL;
Vector<NxActor*> *showActors = NULL;
if ( isBroken )
{
hideActors = &userData->mUnbrokenActors;
showActors = &userData->mBrokenActors;
}
else
{
hideActors = &userData->mBrokenActors;
showActors = &userData->mUnbrokenActors;
}
NxActor *pActor = NULL;
MatrixF tMat;
for ( U32 i = 0; i < hideActors->size(); i++ )
{
pActor = (*hideActors)[i];
pActor->raiseActorFlag( NX_AF_DISABLE_COLLISION );
pActor->raiseBodyFlag( NX_BF_KINEMATIC );
pActor->putToSleep();
NxShape *const* pShapeArray = pActor->getShapes();
U32 shapeCount = pActor->getNbShapes();
for ( U32 i = 0; i < shapeCount; i++ )
pShapeArray[i]->setFlag( NX_SF_DISABLE_RAYCASTING, true );
setMeshHidden( _getMeshName( pActor ), true );
}
// Get the client side delta array.
Vector<Delta> *actorDeltas = NULL;
if ( isClientObject() )
actorDeltas = &mActorDeltas;
else if ( isServerObject() && PHYSICSMGR->isSinglePlayer() )
{
PxMultiActor *clientObj = static_cast<PxMultiActor*>( getClientObject() );
if ( clientObj )
actorDeltas = &clientObj->mActorDeltas;
}
U32 index;
for ( U32 i = 0; i < showActors->size(); i++ )
{
pActor = (*showActors)[i];
if ( showActors == &userData->mBrokenActors )
{
NxMat34 pose;
pose.multiply( parentPose, userData->mRelXfm[i] );
pActor->setGlobalPose( pose );
if ( actorDeltas )
{
for ( U32 j=0; j < mMappedActors.size(); j++ )
{
if ( mMappedActors[j] == pActor )
{
index = mMappedToActorIndex[j];
// Reset the delta.
Delta &delta = (*actorDeltas)[index];
delta.pos = pxCast<Point3F>( pose.t );
pose.getRowMajor44( tMat );
delta.rot.set( tMat );
delta.lastPos = delta.pos;
delta.lastRot = delta.rot;
break;
}
}
}
}
pActor->clearActorFlag( NX_AF_DISABLE_COLLISION );
pActor->clearBodyFlag( NX_BF_KINEMATIC );
pActor->setLinearVelocity( parentVel );
pActor->wakeUp();
NxShape *const* pShapeArray = pActor->getShapes();
U32 shapeCount = pActor->getNbShapes();
for ( U32 i = 0; i < shapeCount; i++ )
pShapeArray[i]->setFlag( NX_SF_DISABLE_RAYCASTING, false );
setMeshHidden( _getMeshName(pActor), false );
}
}
void PxMultiActor::setAllHidden( bool hide )
{
for ( U32 i = 0; i < mShapeInstance->mMeshObjects.size(); i++ )
mShapeInstance->setMeshForceHidden( i, hide );
}
ConsoleMethod( PxMultiActor, setAllHidden, void, 3, 3, "( bool )"
"@brief Hides or unhides all meshes contained in the PxMultiActor.\n\n"
"Hidden meshes will not be rendered.")
{
object->setAllHidden( dAtob(argv[2]) );
}
void PxMultiActor::setMeshHidden( String namePrefix, bool hidden )
{
if ( isServerObject() && PHYSICSMGR->isSinglePlayer() )
{
PxMultiActor *clientObj = static_cast<PxMultiActor*>( getClientObject() );
if ( clientObj )
clientObj->setMeshHidden( namePrefix, hidden );
}
for ( U32 i = 0; i < mShapeInstance->mMeshObjects.size(); i++ )
{
String meshName = mShapeInstance->getShape()->getMeshName( i );
if ( meshName.find( namePrefix ) != String::NPos )
{
mShapeInstance->setMeshForceHidden( i, hidden );
return;
}
}
Con::warnf( "PxMultiActor::setMeshHidden - could not find mesh containing substring (%s)", namePrefix.c_str() );
}
ConsoleMethod( PxMultiActor, setBroken, void, 3, 3, "( bool )"
"@brief Sets the PxMultiActor to a broken or unbroken state.\n\n")
{
object->setAllBroken( dAtob( argv[2] ) );
}
void PxMultiActorData::dumpModel()
{
TSShapeInstance *inst = new TSShapeInstance( shape, true );
String path = Platform::getMainDotCsDir();
path += "/model.dump";
FileStream *st;
if((st = FileStream::createAndOpen( path, Torque::FS::File::Write )) != NULL)
{
if ( inst )
inst->dump( *st );
else
Con::errorf( "PxMultiActor::dumpModel, no ShapeInstance." );
delete st;
}
else
Con::errorf( "PxMultiActor::dumpModel, error opening dump file." );
}
ConsoleMethod( PxMultiActorData, dumpModel, void, 2, 2,
"@brief Dumps model hierarchy and details to a file.\n\n"
"The file will be created as \'model.dump\' in the game folder. "
"If model.dump already exists, it will be overwritten.\n\n")
{
object->dumpModel();
}
ConsoleMethod( PxMultiActor, setMeshHidden, void, 4, 4, "(string meshName, bool isHidden)"
"@brief Prevents the provided mesh from being rendered.\n\n")
{
object->setMeshHidden( argv[2], dAtob( argv[3] ) );
}
void PxMultiActor::listMeshes( const String &state ) const
{
if ( mShapeInstance )
mShapeInstance->listMeshes( state );
}
ConsoleMethod( PxMultiActor, listMeshes, void, 3, 3, "(enum Hidden/Shown/All)"
"@brief Lists all meshes of the provided type in the console window.\n\n"
"@param All Lists all of the %PxMultiActor's meshes.\n"
"@param Hidden Lists all of the %PxMultiActor's hidden meshes.\n"
"@param Shown Lists all of the %PxMultiActor's visible meshes.\n")
{
object->listMeshes( argv[2] );
};
ConsoleMethod( PxMultiActorData, reload, void, 2, 2, ""
"@brief Reloads all data used for the PxMultiActorData.\n\n"
"If the reload sucessfully completes, all PxMultiActor's will be notified.\n\n")
{
object->reload();
}
|
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include "lite/backends/opencl/cl_half.h"
#include "lite/backends/opencl/cl_image_converter.h"
#include "lite/backends/opencl/cl_include.h"
#include "lite/core/kernel.h"
#include "lite/core/op_registry.h"
#include "lite/kernels/opencl/image_helper.h"
#include "lite/operators/op_params.h"
#include "lite/utils/logging.h"
#include "lite/utils/replace_stl/stream.h"
#ifdef LITE_WITH_PROFILE
#include "lite/core/profile/profiler.h"
#endif
#include "lite/backends/opencl/cl_utility.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace opencl {
class InstanceNormImageCompute : public KernelLite<TARGET(kOpenCL),
PRECISION(kFP16),
DATALAYOUT(kImageDefault)> {
public:
using param_t = operators::InstanceNormParam;
std::string doc() const override {
return "InstanceNorm using cl::Image2D(ImageDefault/RGBA), kFP16";
}
#if 1 // onnx/pytorch version
void PrepareForRun() override {
instance_norm_param_ = param_.get_mutable<param_t>();
auto out_h = instance_norm_param_->out->dims()[2];
// TODO(ysh329): add instance_norm + relu pass
// std::string build_options_ += "-DRELU";
if (out_h == 128) {
build_options_ += " -DLOCAL_MEM_128";
} else if (out_h == 64) {
build_options_ += " -DLOCAL_MEM_64";
}
auto& context = ctx_->As<OpenCLContext>();
CHECK(context.cl_context() != nullptr);
context.cl_context()->AddKernel(kernel_func_name_,
"image/instance_norm_kernel.cl",
build_options_,
time_stamp_);
VLOG(1) << "kernel_func_name_:" << kernel_func_name_;
STL::stringstream kernel_key;
kernel_key << kernel_func_name_ << build_options_ << time_stamp_;
kernel_ = context.cl_context()->GetKernel(kernel_key.str());
auto& out_dims = instance_norm_param_->out->dims();
int batch = out_dims[0];
int channel = out_dims[1];
int cgroup = (channel + 3) / 4;
int cround = cgroup * 4;
std::vector<half_t> scale_img(cround * batch);
std::vector<half_t> bias_img(cround * batch);
const float* scale_data = instance_norm_param_->scale->data<float>();
const float* bias_data = instance_norm_param_->bias->data<float>();
for (int i = 0; i < channel; ++i) {
scale_img[i] = Float2Half(scale_data[i]);
bias_img[i] = Float2Half(bias_data[i]);
}
for (int i = 1; i < batch; ++i) {
memcpy(scale_img.data() + i * cround,
scale_img.data(),
cround * sizeof(half_t));
memcpy(bias_img.data() + i * cround,
bias_img.data(),
cround * sizeof(half_t));
}
DDim scale_img_size{{ cgroup, batch }};
scale_image_.mutable_data<half_t, cl::Image2D>(
scale_img_size[0], scale_img_size[1], scale_img.data());
bias_image_.mutable_data<half_t, cl::Image2D>(
scale_img_size[0], scale_img_size[1], bias_img.data());
}
void ReInitWhenNeeded() override {
instance_norm_param_ = param_.get_mutable<param_t>();
auto x_dims = instance_norm_param_->x->dims();
if ((!first_epoch_for_reinit_ && x_dims != last_x_dims_) ||
first_epoch_for_reinit_) {
last_x_dims_ = x_dims;
first_epoch_for_reinit_ = false;
// compute global/local work size
auto device_info = CLRuntime::Global()->GetDeviceInfo();
int max_work_item_size1 = device_info["CL_DEVICE_MAX_WORK_ITEM_SIZES_1"];
int lws0 = 1;
int lws1 = std::min(max_work_item_size1,
std::min(256, static_cast<int>(x_dims[3])));
int lws2 = 1;
gws_ = cl::NDRange{
static_cast<cl::size_type>(x_dims[0] * ((x_dims[1] + 3) / 4)),
static_cast<cl::size_type>(lws1),
static_cast<cl::size_type>(lws2)};
lws_ = cl::NDRange{static_cast<cl::size_type>(lws0),
static_cast<cl::size_type>(lws1),
static_cast<cl::size_type>(lws2)};
}
}
void Run() override {
auto& context = ctx_->As<OpenCLContext>();
auto* x = instance_norm_param_->x;
auto* out = instance_norm_param_->out;
auto& out_dims = out->dims();
const int out_c_group = (out_dims[1] + 3) / 4;
const int out_h = out_dims[2];
const int out_w = out_dims[3];
float epsilon = instance_norm_param_->epsilon;
#ifdef LITE_WITH_LOG
VLOG(4) << "global_work_size:" << static_cast<int>(gws_[0]) << " "
<< static_cast<int>(gws_[1]) << " " << static_cast<int>(gws_[2]);
VLOG(4) << "local_work_size:" << static_cast<int>(lws_[0]) << " "
<< static_cast<int>(lws_[1]) << " " << static_cast<int>(lws_[2]);
VLOG(4) << "out_w:" << out_w;
VLOG(4) << "out_h:" << out_h;
VLOG(4) << "out_c_group:" << out_c_group;
VLOG(4) << "lws1:" << lws_[1];
VLOG(4) << "lws2:" << lws_[2];
VLOG(4) << "epsilon:" << epsilon;
#endif
auto out_image_shape = InitImageDimInfoWith(out_dims);
auto* x_img = x->data<half_t, cl::Image2D>();
auto* out_img = out->mutable_data<half_t, cl::Image2D>(
out_image_shape["width"], out_image_shape["height"]);
auto* scale_img = scale_image_.data<half_t, cl::Image2D>();
auto* bias_img = bias_image_.data<half_t, cl::Image2D>();
cl_int status = kernel_.setArg(0, out_w);
CL_CHECK_FATAL(status);
status = kernel_.setArg(1, out_h);
CL_CHECK_FATAL(status);
status = kernel_.setArg(2, out_c_group);
CL_CHECK_FATAL(status);
status = kernel_.setArg(3, lws_[1]);
CL_CHECK_FATAL(status);
status = kernel_.setArg(4, lws_[2]);
CL_CHECK_FATAL(status);
status = kernel_.setArg(5, epsilon);
CL_CHECK_FATAL(status);
status = kernel_.setArg(6, *x_img);
CL_CHECK_FATAL(status);
status = kernel_.setArg(7, *out_img);
CL_CHECK_FATAL(status);
status = kernel_.setArg(8, *scale_img);
CL_CHECK_FATAL(status);
status = kernel_.setArg(9, *bias_img);
CL_CHECK_FATAL(status);
status = EnqueueNDRangeKernel(
context, kernel_, cl::NullRange, gws_, lws_, nullptr, event_);
CL_CHECK_FATAL(status);
}
#else // paddle version
void PrepareForRun() override {
instance_norm_param_ = param_.get_mutable<param_t>();
auto channel = instance_norm_param_->scale->dims()[0];
auto batch = instance_norm_param_->x->dims()[0];
int64_t cgroup = (channel + 3) / 4;
int64_t cround = cgroup * 4;
std::vector<half_t> scale_img(cround * batch);
std::vector<half_t> bias_img(cround * batch);
const float* scale_data = instance_norm_param_->scale->data<float>();
const float* bias_data = instance_norm_param_->bias->data<float>();
//! init scale_img bias_img data
for (int i = 0; i < channel; ++i) {
scale_img[i] = Float2Half(scale_data[i]);
bias_img[i] = Float2Half(bias_data[i]);
}
for (int i = channel; i < cround; ++i) {
scale_img[i] = Float2Half(0.f);
bias_img[i] = Float2Half(0.f);
}
for (int i = 1; i < batch; ++i) {
memcpy(scale_img.data() + i * cround,
scale_img.data(),
cround * sizeof(half_t));
memcpy(bias_img.data() + i * cround,
bias_img.data(),
cround * sizeof(half_t));
}
DDim scale_img_size{{cgroup, batch}};
scale_image_.mutable_data<half_t, cl::Image2D>(
scale_img_size[0], scale_img_size[1], scale_img.data());
bias_image_.mutable_data<half_t, cl::Image2D>(
scale_img_size[0], scale_img_size[1], bias_img.data());
auto& context = ctx_->As<OpenCLContext>();
context.cl_context()->AddKernel(kernel_func_name_,
"image/instance_norm_kernel.cl",
build_options_,
time_stamp_);
VLOG(1) << "kernel_func_name_:" << kernel_func_name_;
}
void Run() override {
auto& context = ctx_->As<OpenCLContext>();
CHECK(context.cl_context() != nullptr);
auto* x = instance_norm_param_->x;
auto* out = instance_norm_param_->out;
auto in_dims = x->dims();
int batch = in_dims[0];
int channel = in_dims[1];
int in_h = in_dims[2];
int in_w = in_dims[3];
#ifdef LITE_WITH_LOG
VLOG(4) << "x->target():" << TargetToStr(x->target());
VLOG(4) << "out->target():" << TargetToStr(out->target());
VLOG(4) << "x->dims():" << in_dims;
#endif
auto out_image_shape = InitImageDimInfoWith(in_dims);
auto* x_img = x->data<half_t, cl::Image2D>();
auto* out_img = out->mutable_data<half_t, cl::Image2D>(
out_image_shape["width"], out_image_shape["height"]);
#ifdef LITE_WITH_LOG
VLOG(4) << "out_image_shape[w,h]: " << out_image_shape["width"] << " "
<< out_image_shape["height"];
VLOG(4) << "in_h: " << in_h << ", in_w: " << in_w;
#endif
int threads = 512;
int group_size_x = (channel + 3) / 4;
int group_size_y = batch;
auto local_work_size = cl::NDRange{static_cast<cl::size_type>(threads),
static_cast<cl::size_type>(1),
static_cast<cl::size_type>(1)};
auto global_work_size =
cl::NDRange{static_cast<cl::size_type>(group_size_x * threads),
static_cast<cl::size_type>(group_size_y),
static_cast<cl::size_type>(1)};
#ifdef LITE_WITH_LOG
VLOG(4) << "local_work_size:[2D]:" << local_work_size[0] << " "
<< local_work_size[1] << " " << local_work_size[2];
VLOG(4) << "global_work_size:[2D]:" << global_work_size[0] << " "
<< global_work_size[1] << " " << global_work_size[2];
#endif
STL::stringstream kernel_key;
kernel_key << kernel_func_name_ << build_options_ << time_stamp_;
auto kernel = context.cl_context()->GetKernel(kernel_key.str());
auto* scale_img = scale_image_.data<half_t, cl::Image2D>();
auto* bias_img = bias_image_.data<half_t, cl::Image2D>();
float epsilon = instance_norm_param_->epsilon;
cl_int status = kernel.setArg(arg_idx++, *x_img);
CL_CHECK_FATAL(status);
status = kernel.setArg(arg_idx++, *out_img);
CL_CHECK_FATAL(status);
status = kernel.setArg(arg_idx++, *scale_img);
CL_CHECK_FATAL(status);
status = kernel.setArg(arg_idx++, *bias_img);
CL_CHECK_FATAL(status);
status = kernel.setArg(arg_idx++, epsilon);
CL_CHECK_FATAL(status);
status = kernel.setArg(arg_idx++, in_h);
CL_CHECK_FATAL(status);
status = kernel.setArg(arg_idx++, in_w);
CL_CHECK_FATAL(status);
status = EnqueueNDRangeKernel(context,
kernel,
cl::NullRange,
global_work_size,
local_work_size,
nullptr,
event_);
CL_CHECK_FATAL(status);
}
#endif
#ifdef LITE_WITH_PROFILE
void SetProfileRuntimeKernelInfo(paddle::lite::profile::OpCharacter* ch) {
ch->kernel_func_name = kernel_func_name_;
ch->cl_event =
event_; // `event_` defined in `kernel.h`, valid after kernel::Run
}
#endif
protected:
param_t* instance_norm_param_{nullptr};
bool first_epoch_for_reinit_{true};
DDim last_x_dims_;
std::string kernel_func_name_{"instance_norm_onnx"};
std::string build_options_{"-DCL_DTYPE_half"};
std::string time_stamp_{GetTimeStamp()};
cl::Kernel kernel_;
cl::NDRange gws_, lws_;
Tensor scale_image_;
Tensor bias_image_;
};
} // namespace opencl
} // namespace kernels
} // namespace lite
} // namespace paddle
namespace ocl = paddle::lite::kernels::opencl;
REGISTER_LITE_KERNEL(instance_norm,
kOpenCL,
kFP16,
kImageDefault,
ocl::InstanceNormImageCompute,
ImageDefault)
.BindInput("X",
{LiteType::GetTensorTy(TARGET(kOpenCL),
PRECISION(kFP16),
DATALAYOUT(kImageDefault))})
.BindOutput("Y",
{LiteType::GetTensorTy(TARGET(kOpenCL),
PRECISION(kFP16),
DATALAYOUT(kImageDefault))})
.BindInput("Scale", {LiteType::GetTensorTy(TARGET(kARM))})
.BindInput("Bias", {LiteType::GetTensorTy(TARGET(kARM))})
.BindOutput("SavedMean", {LiteType::GetTensorTy(TARGET(kARM))})
.BindOutput("SavedVariance", {LiteType::GetTensorTy(TARGET(kARM))})
.Finalize();
|
// Copyright (c) 2018 The GleecBTC Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <fs.h>
#include <util/system.h>
#include <wallet/test/init_test_fixture.h>
InitWalletDirTestingSetup::InitWalletDirTestingSetup(const std::string& chainName): BasicTestingSetup(chainName)
{
m_chain_client = MakeWalletClient(*m_chain, {});
std::string sep;
sep += fs::path::preferred_separator;
m_datadir = GetDataDir();
m_cwd = fs::current_path();
m_walletdir_path_cases["default"] = m_datadir / "wallets";
m_walletdir_path_cases["custom"] = m_datadir / "my_wallets";
m_walletdir_path_cases["nonexistent"] = m_datadir / "path_does_not_exist";
m_walletdir_path_cases["file"] = m_datadir / "not_a_directory.dat";
m_walletdir_path_cases["trailing"] = m_datadir / "wallets" / sep;
m_walletdir_path_cases["trailing2"] = m_datadir / "wallets" / sep / sep;
fs::current_path(m_datadir);
m_walletdir_path_cases["relative"] = "wallets";
fs::create_directories(m_walletdir_path_cases["default"]);
fs::create_directories(m_walletdir_path_cases["custom"]);
fs::create_directories(m_walletdir_path_cases["relative"]);
std::ofstream f(m_walletdir_path_cases["file"].BOOST_FILESYSTEM_C_STR);
f.close();
}
InitWalletDirTestingSetup::~InitWalletDirTestingSetup()
{
fs::current_path(m_cwd);
}
void InitWalletDirTestingSetup::SetWalletDir(const fs::path& walletdir_path)
{
gArgs.ForceSetArg("-walletdir", walletdir_path.string());
}
|
// Copyright 2015 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 "services/ui/ws/display_binding.h"
#include "base/memory/ptr_util.h"
#include "services/service_manager/public/interfaces/connector.mojom.h"
#include "services/ui/ws/display.h"
#include "services/ui/ws/window_manager_access_policy.h"
#include "services/ui/ws/window_server.h"
#include "services/ui/ws/window_tree.h"
namespace ui {
namespace ws {
DisplayBindingImpl::DisplayBindingImpl(mojom::WindowTreeHostRequest request,
Display* display,
const UserId& user_id,
mojom::WindowTreeClientPtr client,
WindowServer* window_server)
: window_server_(window_server),
user_id_(user_id),
binding_(display, std::move(request)),
client_(std::move(client)) {}
DisplayBindingImpl::~DisplayBindingImpl() {}
WindowTree* DisplayBindingImpl::CreateWindowTree(ServerWindow* root) {
const uint32_t embed_flags = 0;
WindowTree* tree = window_server_->EmbedAtWindow(
root, user_id_, std::move(client_), embed_flags,
base::WrapUnique(new WindowManagerAccessPolicy));
tree->ConfigureWindowManager();
return tree;
}
} // namespace ws
} // namespace ui
|
// JLed Unit tests (runs on host)
// Copyright 2017 Jan Delgado jdelgado@gmx.net
#include <jled_base.h> // NOLINT
#include <map>
#include <utility>
#include "catch.hpp"
#include "hal_mock.h" // NOLINT
using jled::BlinkBrightnessEvaluator;
using jled::BreatheBrightnessEvaluator;
using jled::BrightnessEvaluator;
using jled::CandleBrightnessEvaluator;
using jled::ConstantBrightnessEvaluator;
using jled::FadeOffBrightnessEvaluator;
using jled::FadeOnBrightnessEvaluator;
using jled::TJLed;
// TestJLed is a JLed class using the HalMock for tests. This allows to
// test the code abstracted from the actual hardware in use.
class TestJLed : public TJLed<HalMock, TestJLed> {
using TJLed<HalMock, TestJLed>::TJLed;
};
// instanciate for test coverage measurement
template class TJLed<HalMock, TestJLed>;
TEST_CASE("jled without effect does nothing", "[jled]") {
auto led = TestJLed(1);
REQUIRE(!led.Update());
}
TEST_CASE("On/Off function configuration", "[jled]") {
// class used to access proteced fields during test
class TestableJLed : public TestJLed {
public:
using TestJLed::TestJLed;
static void test() {
SECTION(
"using On() effect uses a BrightnessEval that turns the LED "
"on") {
TestableJLed jled(1);
jled.On();
REQUIRE(dynamic_cast<ConstantBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
REQUIRE(jled.brightness_eval_->Eval(0) == 255);
}
SECTION(
"using Off() effect uses a BrightnessEval that turns the LED "
"off") {
TestableJLed jled(1);
jled.Off();
REQUIRE(dynamic_cast<ConstantBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
REQUIRE(jled.brightness_eval_->Eval(0) == 0);
}
SECTION("using Set() allows to set custom brightness level") {
TestableJLed jled(1);
jled.Set(123);
REQUIRE(dynamic_cast<ConstantBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
REQUIRE(jled.brightness_eval_->Eval(0) == 123);
}
SECTION("using Set(0) allows to set custom turn LED off") {
TestableJLed jled(1);
jled.Set(0);
REQUIRE(dynamic_cast<ConstantBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
REQUIRE(jled.brightness_eval_->Eval(0) == 0);
}
}
};
TestableJLed::test();
}
TEST_CASE("using Breathe() configures BreatheBrightnessEvaluator", "[jled]") {
class TestableJLed : public TestJLed {
public:
using TestJLed::TestJLed;
static void test() {
TestableJLed jled(1);
jled.Breathe(0);
REQUIRE(dynamic_cast<BreatheBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
}
};
TestableJLed::test();
}
TEST_CASE("using Candle() configures CandleBrightnessEvaluator", "[jled]") {
class TestableJLed : public TestJLed {
public:
using TestJLed::TestJLed;
static void test() {
TestableJLed jled(1);
jled.Candle(1, 2, 3);
REQUIRE(dynamic_cast<CandleBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
}
};
TestableJLed::test();
}
TEST_CASE("using Fadeon(), FadeOff() configures Fade-BrightnessEvaluators",
"[jled]") {
class TestableJLed : public TestJLed {
public:
using TestJLed::TestJLed;
static void test() {
SECTION("FadeOff() initializes with FadeOffBrightnessEvaluator") {
TestableJLed jled(1);
jled.FadeOff(0);
REQUIRE(dynamic_cast<FadeOffBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
}
SECTION("FadeOn() initializes with FadeOnBrightnessEvaluator") {
TestableJLed jled(1);
jled.FadeOn(0);
REQUIRE(dynamic_cast<FadeOnBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
}
}
};
TestableJLed::test();
}
TEST_CASE("UserFunc() allows to use a custom brightness evaluator", "[jled]") {
class CustomBrightnessEvaluator : public BrightnessEvaluator {
public:
uint16_t Period() const { return 0; }
uint8_t Eval(uint32_t) const { return 0; }
};
class TestableJLed : public TestJLed {
public:
using TestJLed::TestJLed;
static void test() {
TestableJLed jled(1);
auto cust = CustomBrightnessEvaluator();
jled.UserFunc(&cust);
REQUIRE(dynamic_cast<CustomBrightnessEvaluator *>(
jled.brightness_eval_) != nullptr);
}
};
TestableJLed::test();
}
TEST_CASE("ConstantBrightnessEvaluator returns constant provided value",
"[jled]") {
auto cbZero = ConstantBrightnessEvaluator(0);
REQUIRE(1 == cbZero.Period());
REQUIRE(0 == cbZero.Eval(0));
REQUIRE(0 == cbZero.Eval(1000));
auto cbFull = ConstantBrightnessEvaluator(255);
REQUIRE(1 == cbFull.Period());
REQUIRE(255 == cbFull.Eval(0));
REQUIRE(255 == cbFull.Eval(1000));
}
TEST_CASE(
"BlinkBrightnessEvaluator calculates switches betwen on and off in given "
"time frames",
"[jled]") {
auto eval = BlinkBrightnessEvaluator(10, 5);
REQUIRE(10 + 5 == eval.Period());
REQUIRE(255 == eval.Eval(0));
REQUIRE(255 == eval.Eval(9));
REQUIRE(0 == eval.Eval(10));
REQUIRE(0 == eval.Eval(14));
}
TEST_CASE("CandleBrightnessEvaluator simulated candle flickering", "[jled]") {
auto eval = CandleBrightnessEvaluator(7, 15, 1000);
REQUIRE(1000 == eval.Period());
// TODO(jd) do further and better tests
REQUIRE(eval.Eval(0) > 0);
REQUIRE(eval.Eval(999) > 0);
}
TEST_CASE("FadeOnEvaluator evaluates to expected brightness curve", "[jled]") {
constexpr auto kPeriod = 2000;
auto evalOn = FadeOnBrightnessEvaluator(kPeriod);
REQUIRE(kPeriod == evalOn.Period());
const std::map<uint32_t, uint8_t> test_values = {
{0, 0}, {500, 13}, {1000, 68}, {1500, 179},
{1999, 255}, {2000, 255}, {10000, 255}};
for (const auto &x : test_values) {
REQUIRE(x.second == evalOn.Eval(x.first));
}
}
TEST_CASE("FadeOffEvaluator evaluates to expected brightness curve", "[jled]") {
constexpr auto kPeriod = 2000;
// note: FadeOff is invervted FadeOn
auto evalOff = FadeOffBrightnessEvaluator(kPeriod);
REQUIRE(kPeriod == evalOff.Period());
const std::map<uint32_t, uint8_t> test_values = {
{0, 0}, {500, 13}, {1000, 68}, {1500, 179},
{1999, 255}, {2000, 255}, {10000, 255}};
for (const auto &x : test_values) {
REQUIRE(x.second == evalOff.Eval(kPeriod - x.first));
}
}
TEST_CASE(
"BreatheEvaluator evaluates to bell curve distributed brightness curve",
"[jled]") {
constexpr auto kPeriod = 2000;
auto eval = BreatheBrightnessEvaluator(kPeriod);
REQUIRE(kPeriod == eval.Period());
const std::map<uint32_t, uint8_t> test_values = {
{0, 0}, {500, 68}, {1000, 255}, {1500, 68}, {1999, 0}, {2000, 0}};
for (const auto &x : test_values) {
REQUIRE((int)x.second == (int)eval.Eval(x.first));
}
}
TEST_CASE("Forever flag is initially set to false", "[jled]") {
TestJLed jled(1);
REQUIRE_FALSE(jled.IsForever());
}
TEST_CASE("Forever flag is set by call to Forever()", "[jled]") {
TestJLed jled(1);
jled.Forever();
REQUIRE(jled.IsForever());
}
TEST_CASE("dont evalute twice during one time tick", "[jled]") {
class CountingCustomBrightnessEvaluator : public BrightnessEvaluator {
mutable uint16_t count_ = 0;
public:
BrightnessEvaluator *clone(void *p) const {
return new (p) CountingCustomBrightnessEvaluator(*this);
}
uint16_t Period() const { return 1000; }
uint16_t Count() const { return count_; }
uint8_t Eval(uint32_t) const {
count_++;
return 0;
}
};
auto eval = CountingCustomBrightnessEvaluator();
TestJLed jled = TestJLed(1).UserFunc(&eval);
jled.Hal().SetMillis(0);
jled.Update();
REQUIRE(eval.Count() == 1);
jled.Update();
REQUIRE(eval.Count() == 1);
jled.Hal().SetMillis(1);
jled.Update();
REQUIRE(eval.Count() == 2);
}
TEST_CASE("Stop() stops the effect", "[jled]") {
constexpr auto kDuration = 100;
// we test that an effect that normally has high ouput for a longer
// time (e.g. FadeOff()) stays off after Stop() was called.
TestJLed jled = TestJLed(10).FadeOff(kDuration);
REQUIRE(jled.IsRunning());
jled.Update();
REQUIRE(jled.Hal().Value() > 0);
jled.Stop();
REQUIRE(!jled.IsRunning());
REQUIRE_FALSE(jled.Update());
REQUIRE(0 == jled.Hal().Value());
// update should not change anything
REQUIRE_FALSE(jled.Update());
REQUIRE(0 == jled.Hal().Value());
}
TEST_CASE("LowActive() inverts signal", "[jled]") {
TestJLed jled = TestJLed(10).On().LowActive();
REQUIRE(jled.IsLowActive());
REQUIRE(0 == jled.Hal().Value());
jled.Update();
REQUIRE(0 == jled.Hal().Value());
jled.Stop();
REQUIRE(255 == jled.Hal().Value());
}
TEST_CASE("blink led twice with delay and repeat", "[jled]") {
TestJLed jled(10);
// 1 ms on, 2 ms off + 2 ms delay = 3ms off in total per iteration
jled.DelayBefore(5).Blink(1, 2).DelayAfter(2).Repeat(2);
constexpr uint8_t expected[]{
/* delay before 5ms */ 0, 0, 0, 0, 0,
/* 1ms on */ 255,
/* 2ms off */ 0, 0,
/* 2ms delay */ 0, 0,
/* repeat */ 255, 0, 0, 0, 0,
/* finally stay off */ 0, 0};
uint32_t time = 0;
for (const auto val : expected) {
jled.Update();
REQUIRE(val == jled.Hal().Value());
jled.Hal().SetMillis(++time);
}
}
TEST_CASE("After calling Forever() the effect is repeated over and over again ",
"[jled]") {
constexpr auto kOnDuration = 5;
constexpr auto kOffDuration = 10;
constexpr auto kPeriod = kOnDuration + kOffDuration;
constexpr auto kRepetitions = 50; // test this number of times
TestJLed jled(10);
jled.Blink(kOnDuration, kOffDuration).Forever();
uint32_t time = 0;
for (auto i = 0; i < kRepetitions; i++) {
jled.Update();
const bool is_on = ((time % kPeriod) < kOnDuration);
const auto expected = (is_on ? 255 : 0);
REQUIRE(expected == jled.Hal().Value());
// time++;
// if (time >= kOnDuration + kOffDuration) {
// time = 0;
// }
jled.Hal().SetMillis(++time);
}
}
TEST_CASE("The Hal object provided in the ctor is used during update",
"[jled]") {
TestJLed jled = TestJLed(HalMock(10)).Blink(1, 1);
// test with a simple on-off sequence
uint32_t time = 0;
jled.Hal().SetMillis(time);
REQUIRE(jled.Update());
REQUIRE(255 == jled.Hal().Value());
jled.Hal().SetMillis(++time);
REQUIRE(!jled.Update());
REQUIRE(0 == jled.Hal().Value());
}
TEST_CASE("Update returns true while updating, else false", "[jled]") {
TestJLed jled = TestJLed(10).Blink(2, 3);
constexpr auto expectedTime = 2 + 3;
uint32_t time = 0;
for (auto i = 0; i < expectedTime - 1; i++) {
// returns FALSE on last step and beyond, else TRUE
jled.Hal().SetMillis(time++);
REQUIRE(jled.Update());
}
// when effect is done, we expect still false to be returned
jled.Hal().SetMillis(time++);
REQUIRE_FALSE(jled.Update());
}
TEST_CASE("After Reset() the effect can be restarted", "[jled]") {
TestJLed jled(10);
uint32_t time = 0;
typedef std::pair<bool, uint8_t> p;
// 1 ms on, 2 ms off + 2 ms delay = 3ms off in total per iteration
jled.Blink(1, 2);
constexpr p expected[]{p{true, 255}, p{true, 0}, p{false, 0}, p{false, 0}};
for (const auto x : expected) {
jled.Hal().SetMillis(time++);
REQUIRE(x.first == jled.Update());
REQUIRE(x.second == jled.Hal().Value());
}
// after Reset() effect starts over
jled.Reset();
for (const auto x : expected) {
jled.Hal().SetMillis(time++);
REQUIRE(x.first == jled.Update());
REQUIRE(x.second == jled.Hal().Value());
}
}
TEST_CASE("Changing the effect resets object and starts over", "[jled]") {
TestJLed jled(10);
uint32_t time = 0;
typedef std::pair<bool, uint8_t> p;
// 1 ms on, 2 ms off + 2 ms delay = 3ms off in total per iteration
jled.Blink(1, 2);
constexpr p expected_blink[]{p{true, 255}, p{true, 0}, p{false, 0},
p{false, 0}};
for (const auto x : expected_blink) {
jled.Hal().SetMillis(time++);
REQUIRE(x.first == jled.Update());
REQUIRE(x.second == jled.Hal().Value());
}
// expect to start over after changing effect.
jled.FadeOff(1000);
REQUIRE(jled.Update());
REQUIRE(0 < jled.Hal().Value());
}
TEST_CASE("Max brightness level is initialized to 255 within accuracy",
"[jled]") {
// maximum brightness is only stored with kBitsBrightness. Lower bits
// will always be 0 when the current value is read
constexpr uint8_t mask = (1 << (8 - TestJLed::kBitsBrightness)) - 1;
TestJLed jled(10);
REQUIRE(jled.MaxBrightness() == (255 & ~mask));
}
TEST_CASE("Setting max brightness level can be read back within accuracy",
"[jled]") {
constexpr uint8_t mask = (1 << (8 - TestJLed::kBitsBrightness)) - 1;
TestJLed jled(10);
jled.MaxBrightness(0);
REQUIRE(jled.MaxBrightness() == 0);
jled.MaxBrightness(100);
REQUIRE(jled.MaxBrightness() == (100 & ~mask));
jled.MaxBrightness(255);
REQUIRE(jled.MaxBrightness() == (255 & ~mask));
}
TEST_CASE("Setting max brightness level limits brightness value written to HAL",
"[jled]") {
class TestableJLed : public TestJLed {
public:
using TestJLed::TestJLed;
static void test() {
SECTION(
"After setting max brightness to 0, always 0 is written to the "
"HAL",
"max level is 0") {
TestableJLed jled(1);
jled.MaxBrightness(0);
for (auto b = 0; b <= 255; b++) {
jled.Write(b);
REQUIRE(0 == jled.Hal().Value());
}
}
SECTION(
"After setting max brightness to 255, the original value is "
"written to the HAL",
"max level is 255") {
TestableJLed jled(1);
jled.MaxBrightness(255);
for (auto b = 0; b <= 255; b++) {
jled.Write(b);
REQUIRE(b == jled.Hal().Value());
}
}
SECTION(
"After setting max brightness to 128, the original value is "
"scaled by 50% when written to the HAL",
"max level is 128") {
TestableJLed jled(1);
jled.MaxBrightness(128);
for (auto b = 0; b <= 255; b++) {
jled.Write(b);
REQUIRE(b >> 1 == jled.Hal().Value());
}
}
}
};
TestableJLed::test();
}
TEST_CASE("random generator delivers pseudo random numbers", "[rand]") {
jled::rand_seed(0);
REQUIRE(0x59 == jled::rand8());
REQUIRE(0x159 >> 1 == jled::rand8());
}
TEST_CASE("scaling a value with factor 0 scales it to 0", "[scale5]") {
REQUIRE(0 == jled::scale5(0, 0));
REQUIRE(0 == jled::scale5(255, 0));
}
TEST_CASE("scaling a value with factor 16 halfes the value", "[scale5]") {
REQUIRE(0 == jled::scale5(0, 16));
REQUIRE(50 == jled::scale5(100, 16));
REQUIRE(127 == jled::scale5(255, 16));
}
TEST_CASE("scaling a value with factor 31 returns original value", "[scale5]") {
REQUIRE(0 == jled::scale5(0, 31));
REQUIRE(127 == jled::scale5(127, 31));
REQUIRE(255 == jled::scale5(255, 31));
}
|
// 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 <gtest/gtest.h>
#include <libgen.h>
#include "plugin/plugin_loader.h"
#include "plugin/plugin.h"
#include "util/file_utils.h"
namespace doris {
class DemoPluginHandler {
public:
const std::string& hello(const std::string& msg) {
_msg = msg;
return _msg;
}
private:
std::string _msg;
};
int init_plugin(void* ptr) {
// handler
void** p = (void**) ptr;
*p = new DemoPluginHandler();
return 0;
}
int close_plugin(void* ptr) {
void** p = (void**) ptr;
delete (DemoPluginHandler*) (*p);
LOG(INFO) << "close demo plugin";
return 1;
}
class PluginLoaderTest : public testing::Test {
public:
PluginLoaderTest() {
char buf[1024];
readlink("/proc/self/exe", buf, 1023);
char* dir_path = dirname(buf);
_path = std::string(dir_path);
}
~PluginLoaderTest() { }
public:
std::string _path;
};
TEST_F(PluginLoaderTest, normal) {
FileUtils::remove_all(_path + "/plugin_test/target");
DynamicPluginLoader plugin_loader("PluginExample", PLUGIN_TYPE_STORAGE, _path + "/plugin_test/source/test.zip",
"libplugin_example.so", _path + "/plugin_test/target");
ASSERT_TRUE(plugin_loader.install().ok());
ASSERT_TRUE(FileUtils::is_dir(_path + "/plugin_test/target/PluginExample"));
ASSERT_TRUE(FileUtils::check_exist(_path + "/plugin_test/target/PluginExample/"));
std::shared_ptr<Plugin> plugin = plugin_loader.plugin();
ASSERT_EQ(3, plugin->flags);
ASSERT_EQ(1, plugin->init(nullptr));
ASSERT_EQ(2, plugin->close(nullptr));
ASSERT_TRUE(plugin->flags & PLUGIN_NOT_DYNAMIC_UNINSTALL);
ASSERT_FALSE(plugin_loader.uninstall().ok());
ASSERT_TRUE(FileUtils::is_dir(_path + "/plugin_test/target/PluginExample"));
ASSERT_TRUE(FileUtils::check_exist(_path + "/plugin_test/target/PluginExample/"));
FileUtils::remove_all(_path + "/plugin_test/target");
}
TEST_F(PluginLoaderTest, builtin) {
Plugin demoPlugin = {
nullptr,
&init_plugin,
&close_plugin,
PLUGIN_DEFAULT_FLAG,
nullptr,
nullptr,
};
BuiltinPluginLoader plugin_loader("test", PLUGIN_TYPE_AUDIT, &demoPlugin);
ASSERT_TRUE(plugin_loader.install().ok());
std::shared_ptr<Plugin> plugin = plugin_loader.plugin();
ASSERT_EQ(PLUGIN_DEFAULT_FLAG, plugin->flags);
ASSERT_NE(nullptr,plugin->handler);
ASSERT_EQ("test",((DemoPluginHandler *)plugin->handler)->hello("test"));
ASSERT_TRUE(plugin_loader.uninstall().ok());
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
//
// generic_gf_poly.cpp
// zxingpp
//
// Created by Kingle Zhuang on 6/12/18.
// Copyright © 2018 Kingle Zhuang. All rights reserved.
//
#include "generic_gf_poly.hpp"
|
//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the SmallVector class.
//
//===----------------------------------------------------------------------===//
// ATen: modified from llvm::SmallVector.
// replaced llvm::safe_malloc with std::bad_alloc
// deleted LLVM_ENABLE_EXCEPTIONS
#include <c10/util/SmallVector.h>
#include <cstdint>
#include <stdexcept>
using namespace c10;
// Check that no bytes are wasted and everything is well-aligned.
namespace {
// These structures may cause binary compat warnings on AIX. Suppress the
// warning since we are only using these types for the static assertions below.
#if defined(_AIX)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waix-compat"
#endif
struct Struct16B {
alignas(16) void* X;
};
struct Struct32B {
alignas(32) void* X;
};
#if defined(_AIX)
#pragma GCC diagnostic pop
#endif
} // namespace
static_assert(
sizeof(SmallVector<void*, 0>) == sizeof(unsigned) * 2 + sizeof(void*),
"wasted space in SmallVector size 0");
static_assert(
alignof(SmallVector<Struct16B, 0>) >= alignof(Struct16B),
"wrong alignment for 16-byte aligned T");
static_assert(
alignof(SmallVector<Struct32B, 0>) >= alignof(Struct32B),
"wrong alignment for 32-byte aligned T");
static_assert(
sizeof(SmallVector<Struct16B, 0>) >= alignof(Struct16B),
"missing padding for 16-byte aligned T");
static_assert(
sizeof(SmallVector<Struct32B, 0>) >= alignof(Struct32B),
"missing padding for 32-byte aligned T");
static_assert(
sizeof(SmallVector<void*, 1>) == sizeof(unsigned) * 2 + sizeof(void*) * 2,
"wasted space in SmallVector size 1");
static_assert(
sizeof(SmallVector<char, 0>) == sizeof(void*) * 2 + sizeof(void*),
"1 byte elements have word-sized type for size and capacity");
/// Report that MinSize doesn't fit into this vector's size type. Throws
/// std::length_error or calls report_fatal_error.
[[noreturn]] static void report_size_overflow(size_t MinSize, size_t MaxSize);
static void report_size_overflow(size_t MinSize, size_t MaxSize) {
std::string Reason = "SmallVector unable to grow. Requested capacity (" +
std::to_string(MinSize) +
") is larger than maximum value for size type (" +
std::to_string(MaxSize) + ")";
throw std::length_error(Reason);
}
/// Report that this vector is already at maximum capacity. Throws
/// std::length_error or calls report_fatal_error.
[[noreturn]] static void report_at_maximum_capacity(size_t MaxSize);
static void report_at_maximum_capacity(size_t MaxSize) {
std::string Reason =
"SmallVector capacity unable to grow. Already at maximum size " +
std::to_string(MaxSize);
throw std::length_error(Reason);
}
// Note: Moving this function into the header may cause performance regression.
template <class Size_T>
static size_t getNewCapacity(size_t MinSize, size_t TSize, size_t OldCapacity) {
constexpr size_t MaxSize = std::numeric_limits<Size_T>::max();
// Ensure we can fit the new capacity.
// This is only going to be applicable when the capacity is 32 bit.
if (MinSize > MaxSize)
report_size_overflow(MinSize, MaxSize);
// Ensure we can meet the guarantee of space for at least one more element.
// The above check alone will not catch the case where grow is called with a
// default MinSize of 0, but the current capacity cannot be increased.
// This is only going to be applicable when the capacity is 32 bit.
if (OldCapacity == MaxSize)
report_at_maximum_capacity(MaxSize);
// In theory 2*capacity can overflow if the capacity is 64 bit, but the
// original capacity would never be large enough for this to be a problem.
size_t NewCapacity = 2 * OldCapacity + 1; // Always grow.
return std::min(std::max(NewCapacity, MinSize), MaxSize);
}
// Note: Moving this function into the header may cause performance regression.
template <class Size_T>
void* SmallVectorBase<Size_T>::mallocForGrow(
size_t MinSize,
size_t TSize,
size_t& NewCapacity) {
NewCapacity = getNewCapacity<Size_T>(MinSize, TSize, this->capacity());
auto Result = std::malloc(NewCapacity * TSize);
if (Result == nullptr) {
throw std::bad_alloc();
}
return Result;
}
// Note: Moving this function into the header may cause performance regression.
template <class Size_T>
void SmallVectorBase<Size_T>::grow_pod(
void* FirstEl,
size_t MinSize,
size_t TSize) {
size_t NewCapacity = getNewCapacity<Size_T>(MinSize, TSize, this->capacity());
void* NewElts;
if (BeginX == FirstEl) {
NewElts = std::malloc(NewCapacity * TSize);
if (NewElts == nullptr) {
throw std::bad_alloc();
}
// Copy the elements over. No need to run dtors on PODs.
memcpy(NewElts, this->BeginX, size() * TSize);
} else {
// If this wasn't grown from the inline copy, grow the allocated space.
NewElts = std::realloc(this->BeginX, NewCapacity * TSize);
if (NewElts == nullptr) {
throw std::bad_alloc();
}
}
this->BeginX = NewElts;
this->Capacity = NewCapacity;
}
template class c10::SmallVectorBase<uint32_t>;
// Disable the uint64_t instantiation for 32-bit builds.
// Both uint32_t and uint64_t instantiations are needed for 64-bit builds.
// This instantiation will never be used in 32-bit builds, and will cause
// warnings when sizeof(Size_T) > sizeof(size_t).
#if SIZE_MAX > UINT32_MAX
template class c10::SmallVectorBase<uint64_t>;
// Assertions to ensure this #if stays in sync with SmallVectorSizeType.
static_assert(
sizeof(SmallVectorSizeType<char>) == sizeof(uint64_t),
"Expected SmallVectorBase<uint64_t> variant to be in use.");
#else
static_assert(
sizeof(SmallVectorSizeType<char>) == sizeof(uint32_t),
"Expected SmallVectorBase<uint32_t> variant to be in use.");
#endif
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkBinaryReconstructionLabelMapFilter.h"
#include "itkAttributeSelectionLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"
#include "itkTestingMacros.h"
int itkBinaryReconstructionLabelMapFilterTest(int argc, char * argv[])
{
if( argc != 5 )
{
std::cerr << "Usage: " << argv[0];
std::cerr << " input marker output";
std::cerr << " fg";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const unsigned int dim = 3;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, dim > ImageType;
typedef itk::AttributeLabelObject< PixelType, dim, bool > AttributeLabelObjectType;
typedef itk::LabelMap< AttributeLabelObjectType > LabelMapType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
I2LType::Pointer i2l = I2LType::New();
i2l->SetInput( reader->GetOutput() );
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName( argv[2] );
typedef itk::BinaryReconstructionLabelMapFilter< LabelMapType, ImageType > LabelReconstructionType;
LabelReconstructionType::Pointer reconstruction = LabelReconstructionType::New();
//testing get and set macros for Lambda
int fg = atoi( argv[4] );
reconstruction->SetForegroundValue( fg );
TEST_SET_GET_VALUE( fg , reconstruction->GetForegroundValue() );
reconstruction->SetInput( i2l->GetOutput() );
reconstruction->SetMarkerImage( reader2->GetOutput() );
itk::SimpleFilterWatcher watcher(reconstruction, "filter");
reconstruction->Update();
reconstruction->GetOutput()->PrintLabelObjects();
typedef itk::AttributeSelectionLabelMapFilter< LabelMapType > LabelOpeningType;
LabelOpeningType::Pointer opening = LabelOpeningType::New();
opening->SetInput( reconstruction->GetOutput() );
opening->SetAttribute(true);
typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
L2IType::Pointer l2i = L2IType::New();
l2i->SetInput( opening->GetOutput() );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( l2i->GetOutput() );
writer->SetFileName( argv[3] );
writer->UseCompressionOn();
TRY_EXPECT_NO_EXCEPTION( writer->Update() );
return EXIT_SUCCESS;
}
|
// Copyright (c) 2015-2016 The Khronos Group 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 <vector>
#include "test_fixture.h"
#include "unit_spirv.h"
namespace spvtools {
namespace {
using NamedIdTest = spvtest::TextToBinaryTest;
TEST_F(NamedIdTest, Default) {
const std::string input = R"(
OpCapability Shader
OpMemoryModel Logical Simple
OpEntryPoint Vertex %main "foo"
%void = OpTypeVoid
%fnMain = OpTypeFunction %void
%main = OpFunction %void None %fnMain
%lbMain = OpLabel
OpReturn
OpFunctionEnd)";
const std::string output =
"OpCapability Shader\n"
"OpMemoryModel Logical Simple\n"
"OpEntryPoint Vertex %1 \"foo\"\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%1 = OpFunction %2 None %3\n"
"%4 = OpLabel\n"
"OpReturn\n"
"OpFunctionEnd\n";
EXPECT_EQ(output, EncodeAndDecodeSuccessfully(input));
}
struct IdCheckCase {
std::string id;
bool valid;
};
using IdValidityTest =
spvtest::TextToBinaryTestBase<::testing::TestWithParam<IdCheckCase>>;
TEST_P(IdValidityTest, IdTypes) {
const std::string input = GetParam().id + " = OpTypeVoid";
SetText(input);
if (GetParam().valid) {
CompileSuccessfully(input);
} else {
CompileFailure(input);
}
}
INSTANTIATE_TEST_CASE_P(
ValidAndInvalidIds, IdValidityTest,
::testing::ValuesIn(std::vector<IdCheckCase>(
{{"%1", true}, {"%2abc", true}, {"%3Def", true},
{"%4GHI", true}, {"%5_j_k", true}, {"%6J_M", true},
{"%n", true}, {"%O", true}, {"%p7", true},
{"%Q8", true}, {"%R_S", true}, {"%T_10_U", true},
{"%V_11", true}, {"%W_X_13", true}, {"%_A", true},
{"%_", true}, {"%__", true}, {"%A_", true},
{"%_A_", true},
{"%@", false}, {"%!", false}, {"%ABC!", false},
{"%__A__@", false}, {"%%", false}, {"%-", false},
{"%foo_@_bar", false}, {"%", false},
{"5", false}, {"32", false}, {"foo", false},
{"a%bar", false}})), );
} // namespace
} // namespace spvtools
|
/*
* teleop_pr2
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <ORGANIZATION> 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 <pr2_controllers_msgs/Pr2GripperCommand.h>
#include <sensor_msgs/Joy.h>
class TeleopGripper
{
public:
TeleopGripper()
{
ros::NodeHandle private_nh_("~");
private_nh_.param("open_position", open_cmd_.position, 0.08);
private_nh_.param("open_max_effort", open_cmd_.max_effort, -1.0);
private_nh_.param("close_position", close_cmd_.position, -100.00);
private_nh_.param("close_max_effort", close_cmd_.max_effort, -1.0);
private_nh_.param("open_button", open_button_, 1);
private_nh_.param("close_button", close_button_, 2);
pub_ = nh_.advertise<pr2_controllers_msgs::Pr2GripperCommand>("command", 1, false);
sub_ = nh_.subscribe("joy", 1, &TeleopGripper::joyCallback, this);
ROS_DEBUG("teleop_gripper started");
}
void joyCallback(const sensor_msgs::JoyConstPtr& joy)
{
ROS_DEBUG("Got a joy msg");
if ((int) joy->buttons.size() <= open_button_ ||
(int) joy->buttons.size() <= close_button_ ||
open_button_ < 0 ||
close_button_ < 0)
{
ROS_ERROR("Array lookup error: Joystick message has %u elems. Open Index [%u]. Close Index [%u]", (unsigned int)joy->buttons.size(), open_button_, close_button_);
return;
}
ROS_DEBUG("open: Buttons[%u] = %u", open_button_, joy->buttons[open_button_]);
if (joy->buttons[open_button_] == 1)
{
pub_.publish(open_cmd_);
ROS_DEBUG("Opening");
}
else if (joy->buttons[close_button_] == 1)
{
pub_.publish(close_cmd_);
ROS_DEBUG("Closing");
}
}
private:
ros::NodeHandle nh_;
ros::Publisher pub_;
ros::Subscriber sub_;
int close_button_;
int open_button_;
pr2_controllers_msgs::Pr2GripperCommand open_cmd_;
pr2_controllers_msgs::Pr2GripperCommand close_cmd_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "teleop_gripper");
TeleopGripper teleop_gripper;
ros::spin();
}
|
//=========================================================================
// Copyright (C) 2012 The Elastos 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 "elastos/droid/launcher2/Utilities.h"
#include "Elastos.Droid.Service.h"
#include "Elastos.Droid.Utility.h"
#include "Elastos.CoreLibrary.Core.h"
#include "Elastos.CoreLibrary.Utility.h"
#include <elastos/core/AutoLock.h>
#include <elastos/utility/logging/Slogger.h>
#include "R.h"
#include <elastos/core/AutoLock.h>
using Elastos::Core::AutoLock;
using Elastos::Droid::Content::Res::IResources;
using Elastos::Droid::Graphics::BitmapConfig_ARGB_8888;
using Elastos::Droid::Graphics::PorterDuffMode_CLEAR;
using Elastos::Droid::Graphics::BlurMaskFilterBlur_NORMAL;
using Elastos::Droid::Graphics::CCanvas;
using Elastos::Droid::Graphics::CPaint;
using Elastos::Droid::Graphics::CRect;
using Elastos::Droid::Graphics::CColorMatrix;
using Elastos::Droid::Graphics::IColorMatrix;
using Elastos::Droid::Graphics::IColorFilter;
using Elastos::Droid::Graphics::IMaskFilter;
using Elastos::Droid::Graphics::IDrawFilter;
using Elastos::Droid::Graphics::CBitmapHelper;
using Elastos::Droid::Graphics::IBitmapHelper;
using Elastos::Droid::Graphics::IBlurMaskFilter;
using Elastos::Droid::Graphics::CBlurMaskFilter;
using Elastos::Droid::Graphics::CPaintFlagsDrawFilter;
using Elastos::Droid::Graphics::IPaintFlagsDrawFilter;
using Elastos::Droid::Graphics::IColorMatrixColorFilter;
using Elastos::Droid::Graphics::CColorMatrixColorFilter;
using Elastos::Droid::Graphics::Drawable::IBitmapDrawable;
using Elastos::Droid::Graphics::Drawable::CBitmapDrawable;
using Elastos::Droid::Graphics::Drawable::IPaintDrawable;
using Elastos::Droid::Graphics::Drawable::IShapeDrawable;
using Elastos::Droid::Utility::IDisplayMetrics;
using Elastos::Core::ISystem;
using Elastos::Core::CSystem;
using Elastos::Utility::Logging::Slogger;
using Elastos::Utility::IRandom;
using Elastos::Utility::CRandom;
namespace Elastos {
namespace Droid {
namespace Launcher2 {
const String Utilities::TAG("Launcher.Utilities");
Int32 Utilities::sIconWidth = -1;
Int32 Utilities::sIconHeight = -1;
Int32 Utilities::sIconTextureWidth = -1;
Int32 Utilities::sIconTextureHeight = -1;
AutoPtr<IPaint> Utilities::sBlurPaint;
AutoPtr<IPaint> Utilities::sGlowColorPressedPaint;
AutoPtr<IPaint> Utilities::sGlowColorFocusedPaint;
AutoPtr<IPaint> Utilities::sDisabledPaint;
AutoPtr<IRect> Utilities::sOldBounds;
AutoPtr<ICanvas> Utilities::sCanvas;
Object Utilities::sCanvasLock;
AutoPtr<ArrayOf<Int32> > Utilities::sColors;
Boolean Utilities::InitStaticBlock()
{
CPaint::New((IPaint**)&sBlurPaint);
CPaint::New((IPaint**)&sGlowColorPressedPaint);
CPaint::New((IPaint**)&sGlowColorFocusedPaint);
CPaint::New((IPaint**)&sDisabledPaint);
CRect::New((IRect**)&sOldBounds);
CCanvas::New((ICanvas**)&sCanvas);
AutoPtr<IPaintFlagsDrawFilter> filter;
CPaintFlagsDrawFilter::New(IPaint::DITHER_FLAG, IPaint::FILTER_BITMAP_FLAG, (IPaintFlagsDrawFilter**)&filter);
sCanvas->SetDrawFilter(IDrawFilter::Probe(filter));
sColors = ArrayOf<Int32>::Alloc(3);
(*sColors)[0] = 0xffff0000;
(*sColors)[1] = 0xff00ff00;
(*sColors)[2] = 0xff0000ff;
return TRUE;
}
Boolean Utilities::initStaticBlock = InitStaticBlock();
Int32 Utilities::sColorIndex = 0;
AutoPtr<IBitmap> Utilities::CreateIconBitmap(
/* [in] */ IBitmap* icon,
/* [in] */ IContext* context)
{
Int32 textureWidth = sIconTextureWidth;
Int32 textureHeight = sIconTextureHeight;
Int32 sourceWidth;
icon->GetWidth(&sourceWidth);
Int32 sourceHeight;
icon->GetHeight(&sourceHeight);
if (sourceWidth > textureWidth && sourceHeight > textureHeight) {
// Icon is bigger than it should be; clip it (solves the GB->ICS migration case)
AutoPtr<IBitmap> bitmap;
AutoPtr<IBitmapHelper> helper;
CBitmapHelper::AcquireSingleton((IBitmapHelper**)&helper);
helper->CreateBitmap(icon,
(sourceWidth - textureWidth) / 2,
(sourceHeight - textureHeight) / 2,
textureWidth, textureHeight, (IBitmap**)&bitmap);
return bitmap;
}
else if (sourceWidth == textureWidth && sourceHeight == textureHeight) {
// Icon is the right size, no need to change it
return icon;
}
else {
// Icon is too small, render to a larger bitmap
AutoPtr<IResources> resources;
context->GetResources((IResources**)&resources);
AutoPtr<IBitmapDrawable> drawable;
CBitmapDrawable::New(resources, icon, (IBitmapDrawable**)&drawable);
return CreateIconBitmap(IDrawable::Probe(drawable), context);
}
return NULL;
}
AutoPtr<IBitmap> Utilities::CreateIconBitmap(
/* [in] */ IDrawable* icon,
/* [in] */ IContext* context)
{
{
AutoLock syncLock(sCanvasLock); // we share the statics :-(
if (sIconWidth == -1) {
InitStatics(context);
}
Int32 width = sIconWidth;
Int32 height = sIconHeight;
if (IPaintDrawable::Probe(icon) != NULL) {
AutoPtr<IPaintDrawable> painter = IPaintDrawable::Probe(icon);
IShapeDrawable::Probe(painter)->SetIntrinsicWidth(width);
IShapeDrawable::Probe(painter)->SetIntrinsicHeight(height);
}
else if (IBitmapDrawable::Probe(icon) != NULL) {
// Ensure the bitmap has a density.
AutoPtr<IBitmapDrawable> bitmapDrawable = IBitmapDrawable::Probe(icon);
AutoPtr<IBitmap> bitmap;
bitmapDrawable->GetBitmap((IBitmap**)&bitmap);
Int32 density;
bitmap->GetDensity(&density);
if (density == IBitmap::DENSITY_NONE) {
AutoPtr<IResources> resources;
context->GetResources((IResources**)&resources);
AutoPtr<IDisplayMetrics> metrics;
resources->GetDisplayMetrics((IDisplayMetrics**)&metrics);
bitmapDrawable->SetTargetDensity(metrics);
}
}
Int32 sourceWidth;
icon->GetIntrinsicWidth(&sourceWidth);
Int32 sourceHeight;
icon->GetIntrinsicHeight(&sourceHeight);
if (sourceWidth > 0 && sourceHeight > 0) {
// There are intrinsic sizes.
if (width < sourceWidth || height < sourceHeight) {
// It's too big, scale it down.
const Float ratio = (Float) sourceWidth / sourceHeight;
if (sourceWidth > sourceHeight) {
height = (Int32) (width / ratio);
}
else if (sourceHeight > sourceWidth) {
width = (Int32) (height * ratio);
}
}
else if (sourceWidth < width && sourceHeight < height) {
// Don't scale up the icon
width = sourceWidth;
height = sourceHeight;
}
}
// no intrinsic size --> use default size
Int32 textureWidth = sIconTextureWidth;
Int32 textureHeight = sIconTextureHeight;
AutoPtr<IBitmap> bitmap;
AutoPtr<IBitmapHelper> helper;
CBitmapHelper::AcquireSingleton((IBitmapHelper**)&helper);
helper->CreateBitmap(textureWidth, textureHeight,
BitmapConfig_ARGB_8888, (IBitmap**)&bitmap);
const AutoPtr<ICanvas> canvas = sCanvas;
canvas->SetBitmap(bitmap);
const Int32 left = (textureWidth-width) / 2;
const Int32 top = (textureHeight-height) / 2;
//@SuppressWarnings("all") // suppress dead code warning
const Boolean debug = FALSE;
if (debug) {
// draw a big box for the icon for debugging
canvas->DrawColor((*sColors)[sColorIndex]);
if (++sColorIndex >= sColors->GetLength()) sColorIndex = 0;
AutoPtr<IPaint> debugPaint;
CPaint::New((IPaint**)&debugPaint);
debugPaint->SetColor(0xffcccc00);
canvas->DrawRect(left, top, left+width, top+height, debugPaint);
}
AutoPtr<IRect> bounds;
icon->GetBounds((IRect**)&bounds);
sOldBounds->Set(bounds);
icon->SetBounds(left, top, left+width, top+height);
icon->Draw(canvas);
icon->SetBounds(sOldBounds);
canvas->SetBitmap(NULL);
return bitmap;
}
return NULL;
}
ECode Utilities::DrawSelectedAllAppsBitmap(
/* [in] */ ICanvas* dest,
/* [in] */ Int32 destWidth,
/* [in] */ Int32 destHeight,
/* [in] */ Boolean pressed,
/* [in] */ IBitmap* src)
{
{ AutoLock syncLock(sCanvasLock); // we share the statics :-(
if (sIconWidth == -1) {
// We can't have gotten to here without src being initialized, which
// comes from this file already. So just assert.
//initStatics(context);
//throw new RuntimeException("Assertion failed: Utilities not initialized");
Slogger::E(TAG, "Assertion failed: Utilities not initialized");
return E_RUNTIME_EXCEPTION;
}
dest->DrawColor(0, PorterDuffMode_CLEAR);
AutoPtr<ArrayOf<Int32> > xy = ArrayOf<Int32>::Alloc(2);
AutoPtr<IBitmap> mask;
src->ExtractAlpha(sBlurPaint, xy, (IBitmap**)&mask);
Int32 width;
src->GetWidth(&width);
Int32 height;
src->GetHeight(&height);
Float px = (destWidth - width) / 2;
Float py = (destHeight - height) / 2;
dest->DrawBitmap(mask, px + (*xy)[0], py + (*xy)[1],
pressed ? sGlowColorPressedPaint : sGlowColorFocusedPaint);
return mask->Recycle();
}
return NOERROR;
}
AutoPtr<IBitmap> Utilities::ResampleIconBitmap(
/* [in] */ IBitmap* bitmap,
/* [in] */ IContext* context)
{
{
AutoLock syncLock(sCanvasLock); // we share the statics :-(
if (sIconWidth == -1) {
InitStatics(context);
}
Int32 width;
bitmap->GetWidth(&width);
Int32 height;
bitmap->GetHeight(&height);
if (width == sIconWidth && height == sIconHeight) {
return bitmap;
}
else {
AutoPtr<IResources> resources;
context->GetResources((IResources**)&resources);
AutoPtr<IBitmapDrawable> drawble;
CBitmapDrawable::New(resources, bitmap, (IBitmapDrawable**)&drawble);
return CreateIconBitmap(IBitmap::Probe(drawble), context);
}
}
return NULL;
}
AutoPtr<IBitmap> Utilities::DrawDisabledBitmap(
/* [in] */ IBitmap* bitmap,
/* [in] */ IContext* context)
{
{
AutoLock syncLock(sCanvasLock); // we share the statics :-(
if (sIconWidth == -1) {
InitStatics(context);
}
Int32 width;
bitmap->GetWidth(&width);
Int32 height;
bitmap->GetHeight(&height);
AutoPtr<IBitmap> disabled;
AutoPtr<IBitmapHelper> helper;
CBitmapHelper::AcquireSingleton((IBitmapHelper**)&helper);
helper->CreateBitmap(width, height, BitmapConfig_ARGB_8888,
(IBitmap**)&disabled);
AutoPtr<ICanvas> canvas = sCanvas;
canvas->SetBitmap(disabled);
canvas->DrawBitmap(bitmap, 0.0f, 0.0f, sDisabledPaint);
canvas->SetBitmap(NULL);
return disabled;
}
return NULL;
}
void Utilities::InitStatics(
/* [in] */ IContext* context)
{
AutoPtr<IResources> resources;
context->GetResources((IResources**)&resources);
AutoPtr<IDisplayMetrics> metrics;
resources->GetDisplayMetrics((IDisplayMetrics**)&metrics);
Float density;
metrics->GetDensity(&density);
Float dim;
resources->GetDimension(Elastos::Droid::Launcher2::R::dimen::app_icon_size, &dim);
sIconWidth = sIconHeight = (Int32)dim;
sIconTextureWidth = sIconTextureHeight = sIconWidth;
AutoPtr<IBlurMaskFilter> filter;
CBlurMaskFilter::New(5 * density, BlurMaskFilterBlur_NORMAL, (IBlurMaskFilter**)&filter);
sBlurPaint->SetMaskFilter(IMaskFilter::Probe(filter));
sGlowColorPressedPaint->SetColor(0xffffc300);
sGlowColorFocusedPaint->SetColor(0xffff8e00);
AutoPtr<IColorMatrix> cm;
CColorMatrix::New((IColorMatrix**)&cm);
cm->SetSaturation(0.2f);
AutoPtr<IColorMatrixColorFilter> colorFilter;
CColorMatrixColorFilter::New(cm, (IColorMatrixColorFilter**)&colorFilter);
sDisabledPaint->SetColorFilter(IColorFilter::Probe(colorFilter));
sDisabledPaint->SetAlpha(0x88);
return;
}
Int32 Utilities::RoundToPow2(
/* [in] */ Int32 n)
{
Int32 orig = n;
n >>= 1;
Int32 mask = 0x8000000;
while (mask != 0 && (n & mask) == 0) {
mask >>= 1;
}
while (mask != 0) {
n |= mask;
mask >>= 1;
}
n += 1;
if (n != orig) {
n <<= 1;
}
return n;
}
Int32 Utilities::GenerateRandomId()
{
Int64 currentTimeMillis;
AutoPtr<ISystem> system;
CSystem::AcquireSingleton((ISystem**)&system);
system->GetCurrentTimeMillis(¤tTimeMillis);
AutoPtr<IRandom> ran;
CRandom::New(currentTimeMillis, (IRandom**)&ran);
Int32 id;
ran->NextInt32(1 << 24, &id);
return id;
}
} // namespace Launcher2
} // namespace Droid
} // namespace Elastos
|
// Copyright (c) 2012-2016, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Urbancash.
//
// Urbancash is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Urbancash is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Urbancash. If not, see <http://www.gnu.org/licenses/>.
#include "IOutputStream.h"
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2015 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/base/thrift-buffer.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/variable-unserializer.h"
#include "hphp/util/logger.h"
#include <vector>
#define INVALID_DATA 1
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
ThriftBuffer::ThriftBuffer(int size,
VariableSerializer::Type sType /* = Serialize*/)
: m_size(size), m_safe(false), m_serializerType(sType) {
m_buf = (char *)malloc(m_size + 1);
if (!m_buf) throwOutOfMemory();
m_pEnd = m_buf + m_size;
m_pSafe = m_pEnd - sizeof(int64_t) - 1;
m_p = m_buf;
}
ThriftBuffer::~ThriftBuffer() {
free(m_buf);
}
void ThriftBuffer::reset(bool read) {
if (read) {
m_pEnd = m_buf;
m_safe = false;
} else {
m_pEnd = m_buf + m_size;
}
m_pSafe = m_pEnd - sizeof(int64_t) - 1;
m_p = m_buf;
}
///////////////////////////////////////////////////////////////////////////////
void ThriftBuffer::write(const String& data) {
int32_t len = data.size();
write(len);
if (m_p + len > m_pEnd) {
flush();
}
if (len > m_size) {
flushImpl(data);
} else {
memcpy(m_p, data.data(), len);
if ((m_p += len) > m_pSafe) flush();
}
}
void ThriftBuffer::flush() {
*m_p = '\0';
String data(m_buf, m_p - m_buf, CopyString);
m_p = m_buf;
flushImpl(data);
}
///////////////////////////////////////////////////////////////////////////////
void ThriftBuffer::read(char *data, int len) {
int avail = m_pEnd - m_p;
// still enough
if (avail >= len) {
if (data) memcpy(data, m_p, len);
if ((m_p += len) > m_pSafe) m_safe = false;
return;
}
if (data) memcpy(data, m_p, avail);
len -= avail;
data += avail;
while (true) {
String ret = readImpl();
if (ret.empty()) {
throwError("unable to read enough bytes",INVALID_DATA);
}
const char *rdata = ret.data();
int rsize = ret.size();
if (rsize >= len) {
if (data) memcpy(data, rdata, len);
rsize -= len;
if (rsize) {
memcpy(m_buf, rdata + len, rsize);
m_pEnd = m_buf + rsize;
} else {
m_pEnd = m_buf;
}
m_pSafe = m_pEnd - sizeof(int64_t) - 1;
m_p = m_buf;
if (m_p > m_pSafe) m_safe = false;
return; // done
}
if (data) memcpy(data, rdata, rsize);
len -= rsize;
data += rsize;
}
}
void ThriftBuffer::skip(int8_t type) {
switch (type) {
case T_STOP:
case T_VOID:
return;
case T_STRUCT:
while (true) {
int8_t ttype; read(ttype); // get field type
if (ttype == T_STOP) break;
read(nullptr, 2); // skip field number, I16
skip(ttype); // skip field payload
}
return;
case T_BOOL:
case T_BYTE:
read(nullptr, 1);
return;
case T_I16:
read(nullptr, 2);
return;
case T_I32:
read(nullptr, 4);
return;
case T_U64:
case T_I64:
case T_DOUBLE:
read(nullptr, 8);
return;
//case T_UTF7: // aliases T_STRING
case T_UTF8:
case T_UTF16:
case T_STRING: {
int32_t len; read(len);
read(nullptr, len);
} return;
case T_MAP: {
int8_t keytype; read(keytype);
int8_t valtype; read(valtype);
int32_t size; read(size);
for (int32_t i = 0; i < size; ++i) {
skip(keytype);
skip(valtype);
}
} return;
case T_LIST:
case T_SET: {
int8_t valtype; read(valtype);
int32_t size; read(size);
for (int32_t i = 0; i < size; ++i) {
skip(valtype);
}
} return;
};
char errbuf[128];
sprintf(errbuf, "Unknown field type: %d", (int)type);
throwError(errbuf, INVALID_DATA);
}
void ThriftBuffer::throwOutOfMemory() {
throwError("out of memory", 0);
}
void ThriftBuffer::throwInvalidStringSize(int size) {
char errbuf[128];
sprintf(errbuf, "Negative string size: %d", (int)size);
throwError(errbuf, INVALID_DATA);
}
///////////////////////////////////////////////////////////////////////////////
static Variant unserialize_with_no_notice(const String& str) {
VariableUnserializer vu(str.data(), str.size(),
VariableUnserializer::Type::Serialize, true);
Variant v;
try {
v = vu.unserialize();
} catch (ResourceExceededException &) {
throw;
} catch (Exception &e) {
Logger::Error("unserialize(): %s", e.getMessage().c_str());
}
return v;
}
void ThriftBuffer::read(std::string &data) {
String sdata;
read(sdata);
data = std::string(sdata.data(), sdata.size());
}
void ThriftBuffer::write(const std::string &data) {
write(String(data.data(), data.size(), CopyString));
}
void ThriftBuffer::read(std::vector<std::string> &data) {
int32_t size;
read(size);
data.resize(size);
for (int i = 0; i < size; i++) {
read(data[i]);
}
}
void ThriftBuffer::write(const std::vector<std::string> &data) {
int32_t size = data.size();
write(size);
for (int i = 0; i < size; i++) {
write(data[i]);
}
}
void ThriftBuffer::read(Array &data) {
String sdata;
read(sdata);
data = unserialize_with_no_notice(sdata).toArray();
}
void ThriftBuffer::write(const Array& data) {
VariableSerializer vs(m_serializerType);
String sdata = vs.serialize(VarNR(data), true);
write(sdata);
}
void ThriftBuffer::read(Object &data) {
String sdata;
read(sdata);
data = unserialize_with_no_notice(sdata).toObject();
}
void ThriftBuffer::write(const Object& data) {
VariableSerializer vs(m_serializerType);
String sdata = vs.serialize(VarNR(data), true);
write(sdata);
}
void ThriftBuffer::read(Variant &data) {
String sdata;
read(sdata);
data = unserialize_with_no_notice(sdata);
}
void ThriftBuffer::write(const Variant& data) {
VariableSerializer vs(m_serializerType);
String sdata = vs.serialize(data, true);
write(sdata);
}
///////////////////////////////////////////////////////////////////////////////
}
|
#ifndef __wrapper_EInvalidInput_def_gm2calc_1_3_0_hpp__
#define __wrapper_EInvalidInput_def_gm2calc_1_3_0_hpp__
#include <string>
#include "identification.hpp"
namespace CAT_3(BACKENDNAME,_,SAFE_VERSION)
{
namespace gm2calc
{
// Member functions:
inline ::std::basic_string<char, std::char_traits<char>, std::allocator<char> > EInvalidInput::what() const
{
return get_BEptr()->what();
}
// Wrappers for original constructors:
inline gm2calc::EInvalidInput::EInvalidInput(const ::std::basic_string<char, std::char_traits<char>, std::allocator<char> >& message_) :
Error(__factory0(message_))
{
get_BEptr()->set_wptr(this);
get_BEptr()->set_delete_wrapper(false);
}
// Special pointer-based constructor:
inline gm2calc::EInvalidInput::EInvalidInput(gm2calc::Abstract_EInvalidInput* in) :
Error(in)
{
get_BEptr()->set_wptr(this);
get_BEptr()->set_delete_wrapper(false);
}
// Copy constructor:
inline gm2calc::EInvalidInput::EInvalidInput(const EInvalidInput& in) :
Error(in.get_BEptr()->pointer_copy__BOSS())
{
get_BEptr()->set_wptr(this);
get_BEptr()->set_delete_wrapper(false);
}
// Assignment operator:
inline gm2calc::EInvalidInput& EInvalidInput::operator=(const EInvalidInput& in)
{
if (this != &in)
{
get_BEptr()->pointer_assign__BOSS(in.get_BEptr());
}
return *this;
}
// Destructor:
inline gm2calc::EInvalidInput::~EInvalidInput()
{
if (get_BEptr() != 0)
{
get_BEptr()->set_delete_wrapper(false);
if (can_delete_BEptr())
{
delete BEptr;
BEptr = 0;
}
}
set_delete_BEptr(false);
}
// Returns correctly casted pointer to Abstract class:
inline gm2calc::Abstract_EInvalidInput* gm2calc::EInvalidInput::get_BEptr() const
{
return dynamic_cast<gm2calc::Abstract_EInvalidInput*>(BEptr);
}
}
}
#include "gambit/Backends/backend_undefs.hpp"
#endif /* __wrapper_EInvalidInput_def_gm2calc_1_3_0_hpp__ */
|
/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */
#include <engine/e_server_interface.h>
#include <game/mapitems.hpp>
#include <game/server/entities/character.hpp>
#include <game/server/player.hpp>
#include <game/server/gamecontext.hpp>
#include "ctf.hpp"
GAMECONTROLLER_CTF::GAMECONTROLLER_CTF()
{
flags[0] = 0;
flags[1] = 0;
gametype = "CTF";
game_flags = GAMEFLAG_TEAMS|GAMEFLAG_FLAGS;
}
bool GAMECONTROLLER_CTF::on_entity(int index, vec2 pos)
{
if(GAMECONTROLLER::on_entity(index, pos))
return true;
int team = -1;
if(index == ENTITY_FLAGSTAND_RED) team = 0;
if(index == ENTITY_FLAGSTAND_BLUE) team = 1;
if(team == -1)
return false;
FLAG *f = new FLAG(team);
f->stand_pos = pos;
f->pos = pos;
flags[team] = f;
return true;
}
int GAMECONTROLLER_CTF::on_character_death(class CHARACTER *victim, class PLAYER *killer, int weaponid)
{
GAMECONTROLLER::on_character_death(victim, killer, weaponid);
int had_flag = 0;
// drop flags
for(int fi = 0; fi < 2; fi++)
{
FLAG *f = flags[fi];
if(f && killer && f->carrying_character == killer->get_character())
had_flag |= 2;
if(f && f->carrying_character == victim)
{
game.create_sound_global(SOUND_CTF_DROP);
f->drop_tick = server_tick();
f->carrying_character = 0;
f->vel = vec2(0,0);
if(killer && killer->team != victim->team)
killer->score++;
had_flag |= 1;
}
}
return had_flag;
}
void GAMECONTROLLER_CTF::tick()
{
GAMECONTROLLER::tick();
do_team_score_wincheck();
for(int fi = 0; fi < 2; fi++)
{
FLAG *f = flags[fi];
if(!f)
continue;
// flag hits death-tile, reset it
if(col_get((int)f->pos.x, (int)f->pos.y)&COLFLAG_DEATH || col_get_index(f->pos.x, f->pos.y) == TILE_BFD)
{
game.create_sound_global(SOUND_CTF_RETURN);
f->reset();
continue;
}
//
if(f->carrying_character)
{
// update flag position
f->pos = f->carrying_character->pos;
if(flags[fi^1] && flags[fi^1]->at_stand)
{
if(distance(f->pos, flags[fi^1]->pos) < 32)
{
// CAPTURE! \o/
teamscore[fi^1] += 100;
f->carrying_character->player->score += 5;
dbg_msg("game", "flag_capture player='%d:%s'",
f->carrying_character->player->client_id,
server_clientname(f->carrying_character->player->client_id));
char buf[512];
float capture_time = (server_tick() - f->grab_tick)/(float)server_tickspeed();
float exp = 20/capture_time;
int money = 20/(int)capture_time;
if(game.controller->x2_tick > 0)
{
exp *= 2;
money *= 2;
}
f->carrying_character->player->acc_data.exp += exp;
f->carrying_character->player->acc_data.money += money;
f->carrying_character->player->set_lvl(f->carrying_character->player->acc_data.exp, false);
if(capture_time <= 60)
{
str_format(buf, sizeof(buf), "the %s flag was captured by %s (%d.%s%d seconds)", fi ? "blue" : "red", server_clientname(f->carrying_character->player->client_id), (int)capture_time%60, ((int)(capture_time*100)%100)<10?"0":"", (int)(capture_time*100)%100);
}
else
{
str_format(buf, sizeof(buf), "the %s flag was captured by %s", fi ? "blue" : "red", server_clientname(f->carrying_character->player->client_id));
}
game.send_chat(-1, -2, buf);
for(int i = 0; i < 2; i++)
flags[i]->reset();
game.create_sound_global(SOUND_CTF_CAPTURE);
}
}
}
else
{
CHARACTER *close_characters[MAX_CLIENTS];
int num = game.world.find_entities(f->pos, 32.0f, (ENTITY**)close_characters, MAX_CLIENTS, NETOBJTYPE_CHARACTER);
for(int i = 0; i < num; i++)
{
if(!close_characters[i]->alive || close_characters[i]->player->team == -1 || col_intersect_line(f->pos, close_characters[i]->pos, NULL, NULL))
continue;
if(close_characters[i]->team == f->team)
{
// return the flag
if(!f->at_stand)
{
CHARACTER *chr = close_characters[i];
chr->player->score += 1;
dbg_msg("game", "flag_return player='%d:%s'",
chr->player->client_id,
server_clientname(chr->player->client_id));
game.create_sound_global(SOUND_CTF_RETURN);
f->reset();
}
}
else
{
// take the flag
if(f->at_stand)
{
teamscore[fi^1]++;
f->grab_tick = server_tick();
}
f->at_stand = 0;
f->carrying_character = close_characters[i];
f->carrying_character->player->score += 1;
dbg_msg("game", "flag_grab player='%d:%s'",
f->carrying_character->player->client_id,
server_clientname(f->carrying_character->player->client_id));
int points = 1;
if(f->carrying_character->player->lvl <= 20)
points++;
if(game.controller->x2_tick > 0)
points *= 2;
f->carrying_character->player->acc_data.exp += points;
f->carrying_character->player->acc_data.money += points;
f->carrying_character->player->set_lvl(f->carrying_character->player->acc_data.exp, false);
for(int c = 0; c < MAX_CLIENTS; c++)
{
if(!game.players[c])
continue;
if(game.players[c]->team == fi)
game.create_sound_global(SOUND_CTF_GRAB_EN, game.players[c]->client_id);
else
game.create_sound_global(SOUND_CTF_GRAB_PL, game.players[c]->client_id);
}
break;
}
}
if(!f->carrying_character && !f->at_stand)
{
if(server_tick() > f->drop_tick + server_tickspeed()*30)
{
game.create_sound_global(SOUND_CTF_RETURN);
f->reset();
}
else
{
f->vel.y += game.world.core.tuning.gravity;
move_box(&f->pos, &f->vel, vec2(f->phys_size, f->phys_size), 0.5f);
}
}
}
}
}
// Flag
FLAG::FLAG(int _team)
: ENTITY(NETOBJTYPE_FLAG)
{
team = _team;
proximity_radius = phys_size;
carrying_character = 0x0;
grab_tick = 0;
reset();
// TODO: should this be done here?
game.world.insert_entity(this);
}
void FLAG::reset()
{
carrying_character = 0x0;
at_stand = 1;
pos = stand_pos;
vel = vec2(0,0);
grab_tick = 0;
}
void FLAG::snap(int snapping_client)
{
NETOBJ_FLAG *flag = (NETOBJ_FLAG *)snap_new_item(NETOBJTYPE_FLAG, team, sizeof(NETOBJ_FLAG));
flag->x = (int)pos.x;
flag->y = (int)pos.y;
flag->team = team;
flag->carried_by = -1;
if(at_stand)
flag->carried_by = -2;
else if(carrying_character && carrying_character->player)
flag->carried_by = carrying_character->player->client_id;
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <vector>
// template <class... Args> reference emplace_back(Args&&... args);
// return type is 'reference' in C++17; 'void' before
#include <vector>
#include <cassert>
#include "test_macros.h"
#include "test_allocator.h"
#include "min_allocator.h"
#include "test_allocator.h"
#include "asan_testing.h"
class A
{
int i_;
double d_;
A(const A&);
A& operator=(const A&);
public:
A(int i, double d)
: i_(i), d_(d) {}
A(A&& a)
: i_(a.i_),
d_(a.d_)
{
a.i_ = 0;
a.d_ = 0;
}
A& operator=(A&& a)
{
i_ = a.i_;
d_ = a.d_;
a.i_ = 0;
a.d_ = 0;
return *this;
}
int geti() const {return i_;}
double getd() const {return d_;}
};
int main()
{
{
std::vector<A> c;
#if TEST_STD_VER > 14
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
#else
c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(is_contiguous_container_asan_correct(c));
c.emplace_back(3, 4.5);
assert(c.size() == 2);
#endif
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
assert(is_contiguous_container_asan_correct(c));
}
{
std::vector<A, limited_allocator<A, 4> > c;
#if TEST_STD_VER > 14
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
#else
c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(is_contiguous_container_asan_correct(c));
c.emplace_back(3, 4.5);
assert(c.size() == 2);
#endif
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
assert(is_contiguous_container_asan_correct(c));
}
{
std::vector<A, min_allocator<A>> c;
#if TEST_STD_VER > 14
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
#else
c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(is_contiguous_container_asan_correct(c));
c.emplace_back(3, 4.5);
assert(c.size() == 2);
#endif
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
assert(is_contiguous_container_asan_correct(c));
}
{
std::vector<Tag_X, TaggingAllocator<Tag_X>> c;
c.emplace_back();
assert(c.size() == 1);
c.emplace_back(1, 2, 3);
assert(c.size() == 2);
assert(is_contiguous_container_asan_correct(c));
}
}
|
#include "Mutex.h"
#ifdef WIN32
CMutex::CMutex()
{
InitializeCriticalSection(&_cs );
}
CMutex::~CMutex()
{
DeleteCriticalSection( &_cs );
}
void CMutex::lock()
{
EnterCriticalSection( &_cs );
}
void CMutex::unlock()
{
LeaveCriticalSection( &_cs );
}
#else
CMutex::CMutex()
{
pthread_mutex_init( &_mutex, NULL );
pthread_cond_init( &_cv, NULL );
}
CMutex::~CMutex()
{
pthread_cond_destroy( &_cv );
pthread_mutex_destroy( &_mutex );
}
void CMutex::lock()
{
pthread_mutex_lock( &_mutex );
}
void CMutex::unlock()
{
pthread_mutex_unlock( &_mutex );
}
#endif
|
#include "integerNumbers.h"
int task1a(int n, int k)
{
return k / n;
}
|
/* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#include <stdafx.h>
#include <luasample.hh>
#include <motor/application.hh>
#include <motor/plugin/plugin.hh>
MOTOR_PLUGIN_REGISTER(Motor::LuaSample);
|
#include <Python.h>
#include "numpy/arrayobject.h"
#include "densecrf.h"
#include "densecrf_core.h"
#include <iostream>
using namespace std;
// example to use numpy object: http://blog.debao.me/2013/04/my-first-c-extension-to-numpy/
// write a c extension ot Numpy: http://folk.uio.no/hpl/scripting/doc/python/NumPy/Numeric/numpy-13.html
static PyObject *
densecrf_wrapper(PyObject *self, PyObject *args)
{
PyObject *I=NULL, *fP=NULL, *param=NULL;
PyArrayObject *arr_I=NULL, *arr_fP=NULL;
if (!PyArg_ParseTuple(args, "OOO", &I, &fP, ¶m)) return NULL;
arr_I = (PyArrayObject*)PyArray_FROM_OTF(I, NPY_UINT8, NPY_IN_ARRAY);
if (arr_I == NULL) return NULL;
arr_fP = (PyArrayObject*)PyArray_FROM_OTF(fP, NPY_FLOAT32, NPY_IN_ARRAY);
if (arr_fP == NULL) return NULL;
/*vv* code that makes use of arguments *vv*/
int nd_I = PyArray_NDIM(arr_I); //number of dimensions
npy_intp * shape = PyArray_DIMS(arr_I); // npy_intp array of length nd showing length in each dim.
int nd_P = PyArray_NDIM(arr_fP);
npy_intp * shape_fP = PyArray_DIMS(arr_fP);
CRFParam crf_param;
crf_param.w1 = PyFloat_AsDouble(PyTuple_GET_ITEM(param, 0));
crf_param.alpha = PyFloat_AsDouble(PyTuple_GET_ITEM(param, 1));
crf_param.beta = PyFloat_AsDouble(PyTuple_GET_ITEM(param, 2));
crf_param.w2 = PyFloat_AsDouble(PyTuple_GET_ITEM(param, 3));
crf_param.gamma = PyFloat_AsDouble(PyTuple_GET_ITEM(param, 4));
crf_param.iter = int(PyFloat_AsDouble(PyTuple_GET_ITEM(param, 5)));
VectorXs map = dense_crf_inference((const unsigned char *)arr_I->data, (const float *)arr_fP->data,
shape_fP[0], shape_fP[1], shape_fP[2], crf_param);
npy_intp outshape[2];
outshape[0]=shape_fP[0];
outshape[1]=shape_fP[1];
PyArrayObject * labels = (PyArrayObject*) PyArray_SimpleNew(2, outshape, NPY_INT8);
for (int x=0;x<outshape[0]*outshape[1];x++)
{
*(labels->data + x*labels->strides[1]) = map[x];
}
Py_DECREF(arr_I);
Py_DECREF(arr_fP);
Py_INCREF(labels);
return PyArray_Return(labels);
}
static PyMethodDef Methods[] = {
{"densecrf", densecrf_wrapper, METH_VARARGS, "computing 2D dense CRF"},
{NULL, NULL, 0, NULL}
};
|
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google 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.
//
// Tests for Google Test itself. This verifies that the basic constructs of
// Google Test work.
#include "gtest/gtest.h"
// Verifies that the command line flag variables can be accessed in
// code once "gtest.h" has been #included.
// Do not move it after other gtest #includes.
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
bool dummy =
GTEST_FLAG_GET(also_run_disabled_tests) ||
GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
GTEST_FLAG_GET(repeat) > 0 ||
GTEST_FLAG_GET(recreate_environments_when_repeating) ||
GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
GTEST_FLAG_GET(stack_trace_depth) > 0 ||
GTEST_FLAG_GET(stream_result_to) != "unknown" ||
GTEST_FLAG_GET(throw_on_failure);
EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
}
#include <limits.h> // For INT_MAX.
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <cstdint>
#include <map>
#include <ostream>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
#include "gtest/gtest-spi.h"
#include "src/gtest-internal-inl.h"
namespace testing {
namespace internal {
#if GTEST_CAN_STREAM_RESULTS_
class StreamingListenerTest : public Test {
public:
class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
public:
// Sends a string to the socket.
void Send(const std::string& message) override { output_ += message; }
std::string output_;
};
StreamingListenerTest()
: fake_sock_writer_(new FakeSocketWriter),
streamer_(fake_sock_writer_),
test_info_obj_("FooTest", "Bar", nullptr, nullptr,
CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
protected:
std::string* output() { return &(fake_sock_writer_->output_); }
FakeSocketWriter* const fake_sock_writer_;
StreamingListener streamer_;
UnitTest unit_test_;
TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
};
TEST_F(StreamingListenerTest, OnTestProgramEnd) {
*output() = "";
streamer_.OnTestProgramEnd(unit_test_);
EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
}
TEST_F(StreamingListenerTest, OnTestIterationEnd) {
*output() = "";
streamer_.OnTestIterationEnd(unit_test_, 42);
EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
}
TEST_F(StreamingListenerTest, OnTestCaseStart) {
*output() = "";
streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
}
TEST_F(StreamingListenerTest, OnTestCaseEnd) {
*output() = "";
streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
}
TEST_F(StreamingListenerTest, OnTestStart) {
*output() = "";
streamer_.OnTestStart(test_info_obj_);
EXPECT_EQ("event=TestStart&name=Bar\n", *output());
}
TEST_F(StreamingListenerTest, OnTestEnd) {
*output() = "";
streamer_.OnTestEnd(test_info_obj_);
EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
}
TEST_F(StreamingListenerTest, OnTestPartResult) {
*output() = "";
streamer_.OnTestPartResult(TestPartResult(
TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
// Meta characters in the failure message should be properly escaped.
EXPECT_EQ(
"event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
*output());
}
#endif // GTEST_CAN_STREAM_RESULTS_
// Provides access to otherwise private parts of the TestEventListeners class
// that are needed to test it.
class TestEventListenersAccessor {
public:
static TestEventListener* GetRepeater(TestEventListeners* listeners) {
return listeners->repeater();
}
static void SetDefaultResultPrinter(TestEventListeners* listeners,
TestEventListener* listener) {
listeners->SetDefaultResultPrinter(listener);
}
static void SetDefaultXmlGenerator(TestEventListeners* listeners,
TestEventListener* listener) {
listeners->SetDefaultXmlGenerator(listener);
}
static bool EventForwardingEnabled(const TestEventListeners& listeners) {
return listeners.EventForwardingEnabled();
}
static void SuppressEventForwarding(TestEventListeners* listeners) {
listeners->SuppressEventForwarding();
}
};
class UnitTestRecordPropertyTestHelper : public Test {
protected:
UnitTestRecordPropertyTestHelper() {}
// Forwards to UnitTest::RecordProperty() to bypass access controls.
void UnitTestRecordProperty(const char* key, const std::string& value) {
unit_test_.RecordProperty(key, value);
}
UnitTest unit_test_;
};
} // namespace internal
} // namespace testing
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
using testing::DoubleLE;
using testing::EmptyTestEventListener;
using testing::Environment;
using testing::FloatLE;
using testing::IsNotSubstring;
using testing::IsSubstring;
using testing::kMaxStackTraceDepth;
using testing::Message;
using testing::ScopedFakeTestPartResultReporter;
using testing::StaticAssertTypeEq;
using testing::Test;
using testing::TestEventListeners;
using testing::TestInfo;
using testing::TestPartResult;
using testing::TestPartResultArray;
using testing::TestProperty;
using testing::TestResult;
using testing::TestSuite;
using testing::TimeInMillis;
using testing::UnitTest;
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
using testing::internal::AppendUserMessage;
using testing::internal::ArrayAwareFind;
using testing::internal::ArrayEq;
using testing::internal::CodePointToUtf8;
using testing::internal::CopyArray;
using testing::internal::CountIf;
using testing::internal::EqFailure;
using testing::internal::FloatingPoint;
using testing::internal::ForEach;
using testing::internal::FormatEpochTimeInMillisAsIso8601;
using testing::internal::FormatTimeInMillisAsSeconds;
using testing::internal::GetCurrentOsStackTraceExceptTop;
using testing::internal::GetElementOr;
using testing::internal::GetNextRandomSeed;
using testing::internal::GetRandomSeedFromFlag;
using testing::internal::GetTestTypeId;
using testing::internal::GetTimeInMillis;
using testing::internal::GetTypeId;
using testing::internal::GetUnitTestImpl;
using testing::internal::GTestFlagSaver;
using testing::internal::HasDebugStringAndShortDebugString;
using testing::internal::Int32FromEnvOrDie;
using testing::internal::IsContainer;
using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
using testing::internal::kMaxRandomSeed;
using testing::internal::kTestTypeIdInGoogleTest;
using testing::internal::NativeArray;
using testing::internal::OsStackTraceGetter;
using testing::internal::OsStackTraceGetterInterface;
using testing::internal::ParseFlag;
using testing::internal::RelationToSourceCopy;
using testing::internal::RelationToSourceReference;
using testing::internal::ShouldRunTestOnShard;
using testing::internal::ShouldShard;
using testing::internal::ShouldUseColor;
using testing::internal::Shuffle;
using testing::internal::ShuffleRange;
using testing::internal::SkipPrefix;
using testing::internal::StreamableToString;
using testing::internal::String;
using testing::internal::TestEventListenersAccessor;
using testing::internal::TestResultAccessor;
using testing::internal::UnitTestImpl;
using testing::internal::WideStringToUtf8;
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
using testing::internal::edit_distance::EditType;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif
#if GTEST_IS_THREADSAFE
using testing::internal::ThreadWithParam;
#endif
class TestingVector : public std::vector<int> {
};
::std::ostream& operator<<(::std::ostream& os,
const TestingVector& vector) {
os << "{ ";
for (size_t i = 0; i < vector.size(); i++) {
os << vector[i] << " ";
}
os << "}";
return os;
}
// This line tests that we can define tests in an unnamed namespace.
namespace {
TEST(GetRandomSeedFromFlagTest, HandlesZero) {
const int seed = GetRandomSeedFromFlag(0);
EXPECT_LE(1, seed);
EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
}
TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
EXPECT_EQ(1, GetRandomSeedFromFlag(1));
EXPECT_EQ(2, GetRandomSeedFromFlag(2));
EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
GetRandomSeedFromFlag(kMaxRandomSeed));
}
TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
const int seed1 = GetRandomSeedFromFlag(-1);
EXPECT_LE(1, seed1);
EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
EXPECT_LE(1, seed2);
EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
}
TEST(GetNextRandomSeedTest, WorksForValidInput) {
EXPECT_EQ(2, GetNextRandomSeed(1));
EXPECT_EQ(3, GetNextRandomSeed(2));
EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
GetNextRandomSeed(kMaxRandomSeed - 1));
EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
// We deliberately don't test GetNextRandomSeed() with invalid
// inputs, as that requires death tests, which are expensive. This
// is fine as GetNextRandomSeed() is internal and has a
// straightforward definition.
}
static void ClearCurrentTestPartResults() {
TestResultAccessor::ClearTestPartResults(
GetUnitTestImpl()->current_test_result());
}
// Tests GetTypeId.
TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
}
class SubClassOfTest : public Test {};
class AnotherSubClassOfTest : public Test {};
TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
}
// Verifies that GetTestTypeId() returns the same value, no matter it
// is called from inside Google Test or outside of it.
TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
}
// Tests CanonicalizeForStdLibVersioning.
using ::testing::internal::CanonicalizeForStdLibVersioning;
TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
}
TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
EXPECT_EQ("std::bind",
CanonicalizeForStdLibVersioning("std::__google::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
}
// Tests FormatTimeInMillisAsSeconds().
TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
}
// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
// for particular dates below was verified in Python using
// datetime.datetime.fromutctimestamp(<timestamp>/1000).
// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
// have to set up a particular timezone to obtain predictable results.
class FormatEpochTimeInMillisAsIso8601Test : public Test {
public:
// On Cygwin, GCC doesn't allow unqualified integer literals to exceed
// 32 bits, even when 64-bit integer types are available. We have to
// force the constants to have a 64-bit type here.
static const TimeInMillis kMillisPerSec = 1000;
private:
void SetUp() override {
saved_tz_ = nullptr;
GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
if (getenv("TZ"))
saved_tz_ = strdup(getenv("TZ"));
GTEST_DISABLE_MSC_DEPRECATED_POP_()
// Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
// cannot use the local time zone because the function's output depends
// on the time zone.
SetTimeZone("UTC+00");
}
void TearDown() override {
SetTimeZone(saved_tz_);
free(const_cast<char*>(saved_tz_));
saved_tz_ = nullptr;
}
static void SetTimeZone(const char* time_zone) {
// tzset() distinguishes between the TZ variable being present and empty
// and not being present, so we have to consider the case of time_zone
// being NULL.
#if _MSC_VER || GTEST_OS_WINDOWS_MINGW
// ...Unless it's MSVC, whose standard library's _putenv doesn't
// distinguish between an empty and a missing variable.
const std::string env_var =
std::string("TZ=") + (time_zone ? time_zone : "");
_putenv(env_var.c_str());
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
tzset();
GTEST_DISABLE_MSC_WARNINGS_POP_()
#else
#if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21
// Work around KitKat bug in tzset by setting "UTC" before setting "UTC+00".
// See https://github.com/android/ndk/issues/1604.
setenv("TZ", "UTC", 1);
tzset();
#endif
if (time_zone) {
setenv(("TZ"), time_zone, 1);
} else {
unsetenv("TZ");
}
tzset();
#endif
}
const char* saved_tz_;
};
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
EXPECT_EQ("2011-10-31T18:52:42.000",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
EXPECT_EQ(
"2011-10-31T18:52:42.234",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
EXPECT_EQ("2011-09-03T05:07:02.000",
FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
EXPECT_EQ("2011-09-28T17:08:22.000",
FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
}
# ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch
# endif
// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
// when the RHS is a pointer type.
TEST(NullLiteralTest, LHSAllowsNullLiterals) {
EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
const int* const p = nullptr;
EXPECT_EQ(0, p); // NOLINT
ASSERT_EQ(0, p); // NOLINT
EXPECT_EQ(NULL, p); // NOLINT
ASSERT_EQ(NULL, p); // NOLINT
EXPECT_EQ(nullptr, p);
ASSERT_EQ(nullptr, p);
}
struct ConvertToAll {
template <typename T>
operator T() const { // NOLINT
return T();
}
};
struct ConvertToPointer {
template <class T>
operator T*() const { // NOLINT
return nullptr;
}
};
struct ConvertToAllButNoPointers {
template <typename T,
typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
operator T() const { // NOLINT
return T();
}
};
struct MyType {};
inline bool operator==(MyType const&, MyType const&) { return true; }
TEST(NullLiteralTest, ImplicitConversion) {
EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
#if !defined(__GNUC__) || defined(__clang__)
// Disabled due to GCC bug gcc.gnu.org/PR89580
EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
#endif
EXPECT_EQ(ConvertToAll{}, MyType{});
EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
}
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
#endif
#endif
TEST(NullLiteralTest, NoConversionNoWarning) {
// Test that gtests detection and handling of null pointer constants
// doesn't trigger a warning when '0' isn't actually used as null.
EXPECT_EQ(0, 0);
ASSERT_EQ(0, 0);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
# ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them.
# pragma option pop
# endif
//
// Tests CodePointToUtf8().
// Tests that the NUL character L'\0' is encoded correctly.
TEST(CodePointToUtf8Test, CanEncodeNul) {
EXPECT_EQ("", CodePointToUtf8(L'\0'));
}
// Tests that ASCII characters are encoded correctly.
TEST(CodePointToUtf8Test, CanEncodeAscii) {
EXPECT_EQ("a", CodePointToUtf8(L'a'));
EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
EXPECT_EQ("&", CodePointToUtf8(L'&'));
EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
}
// Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
// 000 1101 0011 => 110-00011 10-010011
EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
// 101 0111 0110 => 110-10101 10-110110
// Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
// in wide strings and wide chars. In order to accommodate them, we have to
// introduce such character constants as integers.
EXPECT_EQ("\xD5\xB6",
CodePointToUtf8(static_cast<wchar_t>(0x576)));
}
// Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
// 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
EXPECT_EQ("\xE0\xA3\x93",
CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
// 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
EXPECT_EQ("\xEC\x9D\x8D",
CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
}
#if !GTEST_WIDE_STRING_USES_UTF16_
// Tests in this group require a wchar_t to hold > 16 bits, and thus
// are skipped on Windows, and Cygwin, where a wchar_t is
// 16-bit wide. This code may not compile on those systems.
// Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
// 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
// 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
// 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
}
// Tests that encoding an invalid code-point generates the expected result.
TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
}
#endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests WideStringToUtf8().
// Tests that the NUL character L'\0' is encoded correctly.
TEST(WideStringToUtf8Test, CanEncodeNul) {
EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
}
// Tests that ASCII strings are encoded correctly.
TEST(WideStringToUtf8Test, CanEncodeAscii) {
EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
}
// Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
// 000 1101 0011 => 110-00011 10-010011
EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
// 101 0111 0110 => 110-10101 10-110110
const wchar_t s[] = { 0x576, '\0' };
EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
}
// Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
// 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
const wchar_t s1[] = { 0x8D3, '\0' };
EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
// 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
const wchar_t s2[] = { 0xC74D, '\0' };
EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
}
// Tests that the conversion stops when the function encounters \0 character.
TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
}
// Tests that the conversion stops when the function reaches the limit
// specified by the 'length' parameter.
TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
}
#if !GTEST_WIDE_STRING_USES_UTF16_
// Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
// on the systems using UTF-16 encoding.
TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
// 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
// 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
}
// Tests that encoding an invalid code-point generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
WideStringToUtf8(L"\xABCDFF", -1).c_str());
}
#else // !GTEST_WIDE_STRING_USES_UTF16_
// Tests that surrogate pairs are encoded correctly on the systems using
// UTF-16 encoding in the wide strings.
TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
}
// Tests that encoding an invalid UTF-16 surrogate pair
// generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
// Leading surrogate is at the end of the string.
const wchar_t s1[] = { 0xD800, '\0' };
EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
// Leading surrogate is not followed by the trailing surrogate.
const wchar_t s2[] = { 0xD800, 'M', '\0' };
EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
// Trailing surrogate appearas without a leading surrogate.
const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
}
#endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests that codepoint concatenation works correctly.
#if !GTEST_WIDE_STRING_USES_UTF16_
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
EXPECT_STREQ(
"\xF4\x88\x98\xB4"
"\xEC\x9D\x8D"
"\n"
"\xD5\xB6"
"\xE0\xA3\x93"
"\xF4\x88\x98\xB4",
WideStringToUtf8(s, -1).c_str());
}
#else
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
EXPECT_STREQ(
"\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
WideStringToUtf8(s, -1).c_str());
}
#endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests the Random class.
TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
testing::internal::Random random(42);
EXPECT_DEATH_IF_SUPPORTED(
random.Generate(0),
"Cannot generate a number in the range \\[0, 0\\)");
EXPECT_DEATH_IF_SUPPORTED(
random.Generate(testing::internal::Random::kMaxRange + 1),
"Generation of a number in \\[0, 2147483649\\) was requested, "
"but this can only generate numbers in \\[0, 2147483648\\)");
}
TEST(RandomTest, GeneratesNumbersWithinRange) {
constexpr uint32_t kRange = 10000;
testing::internal::Random random(12345);
for (int i = 0; i < 10; i++) {
EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
}
testing::internal::Random random2(testing::internal::Random::kMaxRange);
for (int i = 0; i < 10; i++) {
EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
}
}
TEST(RandomTest, RepeatsWhenReseeded) {
constexpr int kSeed = 123;
constexpr int kArraySize = 10;
constexpr uint32_t kRange = 10000;
uint32_t values[kArraySize];
testing::internal::Random random(kSeed);
for (int i = 0; i < kArraySize; i++) {
values[i] = random.Generate(kRange);
}
random.Reseed(kSeed);
for (int i = 0; i < kArraySize; i++) {
EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
}
}
// Tests STL container utilities.
// Tests CountIf().
static bool IsPositive(int n) { return n > 0; }
TEST(ContainerUtilityTest, CountIf) {
std::vector<int> v;
EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
v.push_back(-1);
v.push_back(0);
EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
v.push_back(2);
v.push_back(-10);
v.push_back(10);
EXPECT_EQ(2, CountIf(v, IsPositive));
}
// Tests ForEach().
static int g_sum = 0;
static void Accumulate(int n) { g_sum += n; }
TEST(ContainerUtilityTest, ForEach) {
std::vector<int> v;
g_sum = 0;
ForEach(v, Accumulate);
EXPECT_EQ(0, g_sum); // Works for an empty container;
g_sum = 0;
v.push_back(1);
ForEach(v, Accumulate);
EXPECT_EQ(1, g_sum); // Works for a container with one element.
g_sum = 0;
v.push_back(20);
v.push_back(300);
ForEach(v, Accumulate);
EXPECT_EQ(321, g_sum);
}
// Tests GetElementOr().
TEST(ContainerUtilityTest, GetElementOr) {
std::vector<char> a;
EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
a.push_back('a');
a.push_back('b');
EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
}
TEST(ContainerUtilityDeathTest, ShuffleRange) {
std::vector<int> a;
a.push_back(0);
a.push_back(1);
a.push_back(2);
testing::internal::Random random(1);
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, -1, 1, &a),
"Invalid shuffle range start -1: must be in range \\[0, 3\\]");
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, 4, 4, &a),
"Invalid shuffle range start 4: must be in range \\[0, 3\\]");
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, 3, 2, &a),
"Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, 3, 4, &a),
"Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
}
class VectorShuffleTest : public Test {
protected:
static const size_t kVectorSize = 20;
VectorShuffleTest() : random_(1) {
for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
vector_.push_back(i);
}
}
static bool VectorIsCorrupt(const TestingVector& vector) {
if (kVectorSize != vector.size()) {
return true;
}
bool found_in_vector[kVectorSize] = { false };
for (size_t i = 0; i < vector.size(); i++) {
const int e = vector[i];
if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
return true;
}
found_in_vector[e] = true;
}
// Vector size is correct, elements' range is correct, no
// duplicate elements. Therefore no corruption has occurred.
return false;
}
static bool VectorIsNotCorrupt(const TestingVector& vector) {
return !VectorIsCorrupt(vector);
}
static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
for (int i = begin; i < end; i++) {
if (i != vector[static_cast<size_t>(i)]) {
return true;
}
}
return false;
}
static bool RangeIsUnshuffled(
const TestingVector& vector, int begin, int end) {
return !RangeIsShuffled(vector, begin, end);
}
static bool VectorIsShuffled(const TestingVector& vector) {
return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
}
static bool VectorIsUnshuffled(const TestingVector& vector) {
return !VectorIsShuffled(vector);
}
testing::internal::Random random_;
TestingVector vector_;
}; // class VectorShuffleTest
const size_t VectorShuffleTest::kVectorSize;
TEST_F(VectorShuffleTest, HandlesEmptyRange) {
// Tests an empty range at the beginning...
ShuffleRange(&random_, 0, 0, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...in the middle...
ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...at the end...
ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...and past the end.
ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
}
TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
// Tests a size one range at the beginning...
ShuffleRange(&random_, 0, 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...in the middle...
ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...and at the end.
ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
}
// Because we use our own random number generator and a fixed seed,
// we can guarantee that the following "random" tests will succeed.
TEST_F(VectorShuffleTest, ShufflesEntireVector) {
Shuffle(&random_, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
// Tests the first and last elements in particular to ensure that
// there are no off-by-one problems in our shuffle algorithm.
EXPECT_NE(0, vector_[0]);
EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
}
TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
const int kRangeSize = kVectorSize/2;
ShuffleRange(&random_, 0, kRangeSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
static_cast<int>(kVectorSize));
}
TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
const int kRangeSize = kVectorSize / 2;
ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
static_cast<int>(kVectorSize));
}
TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
const int kRangeSize = static_cast<int>(kVectorSize) / 3;
ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
static_cast<int>(kVectorSize));
}
TEST_F(VectorShuffleTest, ShufflesRepeatably) {
TestingVector vector2;
for (size_t i = 0; i < kVectorSize; i++) {
vector2.push_back(static_cast<int>(i));
}
random_.Reseed(1234);
Shuffle(&random_, &vector_);
random_.Reseed(1234);
Shuffle(&random_, &vector2);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector2);
for (size_t i = 0; i < kVectorSize; i++) {
EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
}
}
// Tests the size of the AssertHelper class.
TEST(AssertHelperTest, AssertHelperIsSmall) {
// To avoid breaking clients that use lots of assertions in one
// function, we cannot grow the size of AssertHelper.
EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
}
// Tests String::EndsWithCaseInsensitive().
TEST(StringTest, EndsWithCaseInsensitive) {
EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
}
// C++Builder's preprocessor is buggy; it fails to expand macros that
// appear in macro parameters after wide char literals. Provide an alias
// for NULL as a workaround.
static const wchar_t* const kNull = nullptr;
// Tests String::CaseInsensitiveWideCStringEquals
TEST(StringTest, CaseInsensitiveWideCStringEquals) {
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
}
#if GTEST_OS_WINDOWS
// Tests String::ShowWideCString().
TEST(StringTest, ShowWideCString) {
EXPECT_STREQ("(null)",
String::ShowWideCString(NULL).c_str());
EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
}
# if GTEST_OS_WINDOWS_MOBILE
TEST(StringTest, AnsiAndUtf16Null) {
EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
}
TEST(StringTest, AnsiAndUtf16ConvertBasic) {
const char* ansi = String::Utf16ToAnsi(L"str");
EXPECT_STREQ("str", ansi);
delete [] ansi;
const WCHAR* utf16 = String::AnsiToUtf16("str");
EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
delete [] utf16;
}
TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
EXPECT_STREQ(".:\\ \"*?", ansi);
delete [] ansi;
const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
delete [] utf16;
}
# endif // GTEST_OS_WINDOWS_MOBILE
#endif // GTEST_OS_WINDOWS
// Tests TestProperty construction.
TEST(TestPropertyTest, StringValue) {
TestProperty property("key", "1");
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("1", property.value());
}
// Tests TestProperty replacing a value.
TEST(TestPropertyTest, ReplaceStringValue) {
TestProperty property("key", "1");
EXPECT_STREQ("1", property.value());
property.SetValue("2");
EXPECT_STREQ("2", property.value());
}
// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
// functions (i.e. their definitions cannot be inlined at the call
// sites), or C++Builder won't compile the code.
static void AddFatalFailure() {
FAIL() << "Expected fatal failure.";
}
static void AddNonfatalFailure() {
ADD_FAILURE() << "Expected non-fatal failure.";
}
class ScopedFakeTestPartResultReporterTest : public Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2.
enum FailureMode {
FATAL_FAILURE,
NONFATAL_FAILURE
};
static void AddFailure(FailureMode failure) {
if (failure == FATAL_FAILURE) {
AddFatalFailure();
} else {
AddNonfatalFailure();
}
}
};
// Tests that ScopedFakeTestPartResultReporter intercepts test
// failures.
TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
TestPartResultArray results;
{
ScopedFakeTestPartResultReporter reporter(
ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
&results);
AddFailure(NONFATAL_FAILURE);
AddFailure(FATAL_FAILURE);
}
EXPECT_EQ(2, results.size());
EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
}
TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
TestPartResultArray results;
{
// Tests, that the deprecated constructor still works.
ScopedFakeTestPartResultReporter reporter(&results);
AddFailure(NONFATAL_FAILURE);
}
EXPECT_EQ(1, results.size());
}
#if GTEST_IS_THREADSAFE
class ScopedFakeTestPartResultReporterWithThreadsTest
: public ScopedFakeTestPartResultReporterTest {
protected:
static void AddFailureInOtherThread(FailureMode failure) {
ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
thread.Join();
}
};
TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
InterceptsTestFailuresInAllThreads) {
TestPartResultArray results;
{
ScopedFakeTestPartResultReporter reporter(
ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
AddFailure(NONFATAL_FAILURE);
AddFailure(FATAL_FAILURE);
AddFailureInOtherThread(NONFATAL_FAILURE);
AddFailureInOtherThread(FATAL_FAILURE);
}
EXPECT_EQ(4, results.size());
EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
}
#endif // GTEST_IS_THREADSAFE
// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
// work even if the failure is generated in a called function rather than
// the current context.
typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
}
TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
EXPECT_FATAL_FAILURE(AddFatalFailure(),
::std::string("Expected fatal failure."));
}
TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
// We have another test below to verify that the macro catches fatal
// failures generated on another thread.
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
"Expected fatal failure.");
}
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true"
# pragma option push -w-ccc
#endif
// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
// function even when the statement in it contains ASSERT_*.
int NonVoidFunction() {
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
return 0;
}
TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
NonVoidFunction();
}
// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
// current function even though 'statement' generates a fatal failure.
void DoesNotAbortHelper(bool* aborted) {
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
*aborted = false;
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them.
# pragma option pop
#endif
TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
bool aborted = true;
DoesNotAbortHelper(&aborted);
EXPECT_FALSE(aborted);
}
// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an
// unprotected comma.
static int global_var = 0;
#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE({
GTEST_USE_UNPROTECTED_COMMA_;
AddFatalFailure();
}, "");
#endif
EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
GTEST_USE_UNPROTECTED_COMMA_;
AddFatalFailure();
}, "");
}
// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
"Expected non-fatal failure.");
}
TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
::std::string("Expected non-fatal failure."));
}
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
// We have another test below to verify that the macro catches
// non-fatal failures generated on another thread.
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
"Expected non-fatal failure.");
}
// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an
// unprotected comma.
TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
EXPECT_NONFATAL_FAILURE({
GTEST_USE_UNPROTECTED_COMMA_;
AddNonfatalFailure();
}, "");
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
GTEST_USE_UNPROTECTED_COMMA_;
AddNonfatalFailure();
}, "");
}
#if GTEST_IS_THREADSAFE
typedef ScopedFakeTestPartResultReporterWithThreadsTest
ExpectFailureWithThreadsTest;
TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
"Expected fatal failure.");
}
TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
}
#endif // GTEST_IS_THREADSAFE
// Tests the TestProperty class.
TEST(TestPropertyTest, ConstructorWorks) {
const TestProperty property("key", "value");
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("value", property.value());
}
TEST(TestPropertyTest, SetValue) {
TestProperty property("key", "value_1");
EXPECT_STREQ("key", property.key());
property.SetValue("value_2");
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("value_2", property.value());
}
// Tests the TestResult class
// The test fixture for testing TestResult.
class TestResultTest : public Test {
protected:
typedef std::vector<TestPartResult> TPRVector;
// We make use of 2 TestPartResult objects,
TestPartResult * pr1, * pr2;
// ... and 3 TestResult objects.
TestResult * r0, * r1, * r2;
void SetUp() override {
// pr1 is for success.
pr1 = new TestPartResult(TestPartResult::kSuccess,
"foo/bar.cc",
10,
"Success!");
// pr2 is for fatal failure.
pr2 = new TestPartResult(TestPartResult::kFatalFailure,
"foo/bar.cc",
-1, // This line number means "unknown"
"Failure!");
// Creates the TestResult objects.
r0 = new TestResult();
r1 = new TestResult();
r2 = new TestResult();
// In order to test TestResult, we need to modify its internal
// state, in particular the TestPartResult vector it holds.
// test_part_results() returns a const reference to this vector.
// We cast it to a non-const object s.t. it can be modified
TPRVector* results1 = const_cast<TPRVector*>(
&TestResultAccessor::test_part_results(*r1));
TPRVector* results2 = const_cast<TPRVector*>(
&TestResultAccessor::test_part_results(*r2));
// r0 is an empty TestResult.
// r1 contains a single SUCCESS TestPartResult.
results1->push_back(*pr1);
// r2 contains a SUCCESS, and a FAILURE.
results2->push_back(*pr1);
results2->push_back(*pr2);
}
void TearDown() override {
delete pr1;
delete pr2;
delete r0;
delete r1;
delete r2;
}
// Helper that compares two TestPartResults.
static void CompareTestPartResult(const TestPartResult& expected,
const TestPartResult& actual) {
EXPECT_EQ(expected.type(), actual.type());
EXPECT_STREQ(expected.file_name(), actual.file_name());
EXPECT_EQ(expected.line_number(), actual.line_number());
EXPECT_STREQ(expected.summary(), actual.summary());
EXPECT_STREQ(expected.message(), actual.message());
EXPECT_EQ(expected.passed(), actual.passed());
EXPECT_EQ(expected.failed(), actual.failed());
EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
}
};
// Tests TestResult::total_part_count().
TEST_F(TestResultTest, total_part_count) {
ASSERT_EQ(0, r0->total_part_count());
ASSERT_EQ(1, r1->total_part_count());
ASSERT_EQ(2, r2->total_part_count());
}
// Tests TestResult::Passed().
TEST_F(TestResultTest, Passed) {
ASSERT_TRUE(r0->Passed());
ASSERT_TRUE(r1->Passed());
ASSERT_FALSE(r2->Passed());
}
// Tests TestResult::Failed().
TEST_F(TestResultTest, Failed) {
ASSERT_FALSE(r0->Failed());
ASSERT_FALSE(r1->Failed());
ASSERT_TRUE(r2->Failed());
}
// Tests TestResult::GetTestPartResult().
typedef TestResultTest TestResultDeathTest;
TEST_F(TestResultDeathTest, GetTestPartResult) {
CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
}
// Tests TestResult has no properties when none are added.
TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
TestResult test_result;
ASSERT_EQ(0, test_result.test_property_count());
}
// Tests TestResult has the expected property when added.
TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
TestResult test_result;
TestProperty property("key_1", "1");
TestResultAccessor::RecordProperty(&test_result, "testcase", property);
ASSERT_EQ(1, test_result.test_property_count());
const TestProperty& actual_property = test_result.GetTestProperty(0);
EXPECT_STREQ("key_1", actual_property.key());
EXPECT_STREQ("1", actual_property.value());
}
// Tests TestResult has multiple properties when added.
TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
TestResult test_result;
TestProperty property_1("key_1", "1");
TestProperty property_2("key_2", "2");
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
ASSERT_EQ(2, test_result.test_property_count());
const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
EXPECT_STREQ("key_1", actual_property_1.key());
EXPECT_STREQ("1", actual_property_1.value());
const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
EXPECT_STREQ("key_2", actual_property_2.key());
EXPECT_STREQ("2", actual_property_2.value());
}
// Tests TestResult::RecordProperty() overrides values for duplicate keys.
TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
TestResult test_result;
TestProperty property_1_1("key_1", "1");
TestProperty property_2_1("key_2", "2");
TestProperty property_1_2("key_1", "12");
TestProperty property_2_2("key_2", "22");
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
ASSERT_EQ(2, test_result.test_property_count());
const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
EXPECT_STREQ("key_1", actual_property_1.key());
EXPECT_STREQ("12", actual_property_1.value());
const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
EXPECT_STREQ("key_2", actual_property_2.key());
EXPECT_STREQ("22", actual_property_2.value());
}
// Tests TestResult::GetTestProperty().
TEST(TestResultPropertyTest, GetTestProperty) {
TestResult test_result;
TestProperty property_1("key_1", "1");
TestProperty property_2("key_2", "2");
TestProperty property_3("key_3", "3");
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
EXPECT_STREQ("key_1", fetched_property_1.key());
EXPECT_STREQ("1", fetched_property_1.value());
EXPECT_STREQ("key_2", fetched_property_2.key());
EXPECT_STREQ("2", fetched_property_2.value());
EXPECT_STREQ("key_3", fetched_property_3.key());
EXPECT_STREQ("3", fetched_property_3.value());
EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
}
// Tests the Test class.
//
// It's difficult to test every public method of this class (we are
// already stretching the limit of Google Test by using it to test itself!).
// Fortunately, we don't have to do that, as we are already testing
// the functionalities of the Test class extensively by using Google Test
// alone.
//
// Therefore, this section only contains one test.
// Tests that GTestFlagSaver works on Windows and Mac.
class GTestFlagSaverTest : public Test {
protected:
// Saves the Google Test flags such that we can restore them later, and
// then sets them to their default values. This will be called
// before the first test in this test case is run.
static void SetUpTestSuite() {
saver_ = new GTestFlagSaver;
GTEST_FLAG_SET(also_run_disabled_tests, false);
GTEST_FLAG_SET(break_on_failure, false);
GTEST_FLAG_SET(catch_exceptions, false);
GTEST_FLAG_SET(death_test_use_fork, false);
GTEST_FLAG_SET(color, "auto");
GTEST_FLAG_SET(fail_fast, false);
GTEST_FLAG_SET(filter, "");
GTEST_FLAG_SET(list_tests, false);
GTEST_FLAG_SET(output, "");
GTEST_FLAG_SET(brief, false);
GTEST_FLAG_SET(print_time, true);
GTEST_FLAG_SET(random_seed, 0);
GTEST_FLAG_SET(repeat, 1);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(shuffle, false);
GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
GTEST_FLAG_SET(stream_result_to, "");
GTEST_FLAG_SET(throw_on_failure, false);
}
// Restores the Google Test flags that the tests have modified. This will
// be called after the last test in this test case is run.
static void TearDownTestSuite() {
delete saver_;
saver_ = nullptr;
}
// Verifies that the Google Test flags have their default values, and then
// modifies each of them.
void VerifyAndModifyFlags() {
EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(brief));
EXPECT_TRUE(GTEST_FLAG_GET(print_time));
EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
GTEST_FLAG_SET(also_run_disabled_tests, true);
GTEST_FLAG_SET(break_on_failure, true);
GTEST_FLAG_SET(catch_exceptions, true);
GTEST_FLAG_SET(color, "no");
GTEST_FLAG_SET(death_test_use_fork, true);
GTEST_FLAG_SET(fail_fast, true);
GTEST_FLAG_SET(filter, "abc");
GTEST_FLAG_SET(list_tests, true);
GTEST_FLAG_SET(output, "xml:foo.xml");
GTEST_FLAG_SET(brief, true);
GTEST_FLAG_SET(print_time, false);
GTEST_FLAG_SET(random_seed, 1);
GTEST_FLAG_SET(repeat, 100);
GTEST_FLAG_SET(recreate_environments_when_repeating, false);
GTEST_FLAG_SET(shuffle, true);
GTEST_FLAG_SET(stack_trace_depth, 1);
GTEST_FLAG_SET(stream_result_to, "localhost:1234");
GTEST_FLAG_SET(throw_on_failure, true);
}
private:
// For saving Google Test flags during this test case.
static GTestFlagSaver* saver_;
};
GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
// Google Test doesn't guarantee the order of tests. The following two
// tests are designed to work regardless of their order.
// Modifies the Google Test flags in the test body.
TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
VerifyAndModifyFlags();
}
// Verifies that the Google Test flags in the body of the previous test were
// restored to their original values.
TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
VerifyAndModifyFlags();
}
// Sets an environment variable with the given name to the given
// value. If the value argument is "", unsets the environment
// variable. The caller must ensure that both arguments are not NULL.
static void SetEnv(const char* name, const char* value) {
#if GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
return;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
// C++Builder's putenv only stores a pointer to its parameter; we have to
// ensure that the string remains valid as long as it might be needed.
// We use an std::map to do so.
static std::map<std::string, std::string*> added_env;
// Because putenv stores a pointer to the string buffer, we can't delete the
// previous string (if present) until after it's replaced.
std::string *prev_env = NULL;
if (added_env.find(name) != added_env.end()) {
prev_env = added_env[name];
}
added_env[name] = new std::string(
(Message() << name << "=" << value).GetString());
// The standard signature of putenv accepts a 'char*' argument. Other
// implementations, like C++Builder's, accept a 'const char*'.
// We cast away the 'const' since that would work for both variants.
putenv(const_cast<char*>(added_env[name]->c_str()));
delete prev_env;
#elif GTEST_OS_WINDOWS // If we are on Windows proper.
_putenv((Message() << name << "=" << value).GetString().c_str());
#else
if (*value == '\0') {
unsetenv(name);
} else {
setenv(name, value, 1);
}
#endif // GTEST_OS_WINDOWS_MOBILE
}
#if !GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
using testing::internal::Int32FromGTestEnv;
// Tests Int32FromGTestEnv().
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable is not set.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
}
# if !defined(GTEST_GET_INT32_FROM_ENV_)
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable overflows as an Int32.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
printf("(expecting 2 warnings)\n");
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
}
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable does not represent a valid decimal integer.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n");
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
}
# endif // !defined(GTEST_GET_INT32_FROM_ENV_)
// Tests that Int32FromGTestEnv() parses and returns the value of the
// environment variable when it represents a valid decimal integer in
// the range of an Int32.
TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests ParseFlag().
// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag has wrong format
TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
int32_t value = 123;
EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
EXPECT_EQ(123, value);
EXPECT_FALSE(ParseFlag("a=100", "a", &value));
EXPECT_EQ(123, value);
}
// Tests that ParseFlag() returns false and doesn't change the
// output value when the flag overflows as an Int32.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
printf("(expecting 2 warnings)\n");
int32_t value = 123;
EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
EXPECT_EQ(123, value);
EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
EXPECT_EQ(123, value);
}
// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag does not represent a valid decimal
// integer.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n");
int32_t value = 123;
EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
EXPECT_EQ(123, value);
EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
EXPECT_EQ(123, value);
}
// Tests that ParseInt32Flag() parses the value of the flag and
// returns true when the flag represents a valid decimal integer in
// the range of an Int32.
TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
int32_t value = 123;
EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
EXPECT_EQ(456, value);
EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
EXPECT_EQ(-789, value);
}
// Tests that Int32FromEnvOrDie() parses the value of the var or
// returns the correct default.
// Environment variables are not supported on Windows CE.
#if !GTEST_OS_WINDOWS_MOBILE
TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable is not an int32_t.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
EXPECT_DEATH_IF_SUPPORTED(
Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
".*");
}
// Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable cannot be represented by an int32_t.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
EXPECT_DEATH_IF_SUPPORTED(
Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
".*");
}
// Tests that ShouldRunTestOnShard() selects all tests
// where there is 1 shard.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
}
class ShouldShardTest : public testing::Test {
protected:
void SetUp() override {
index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
}
void TearDown() override {
SetEnv(index_var_, "");
SetEnv(total_var_, "");
}
const char* index_var_;
const char* total_var_;
};
// Tests that sharding is disabled if neither of the environment variables
// are set.
TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
SetEnv(index_var_, "");
SetEnv(total_var_, "");
EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
// Tests that sharding is not enabled if total_shards == 1.
TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
SetEnv(index_var_, "0");
SetEnv(total_var_, "1");
EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
// Tests that sharding is enabled if total_shards > 1 and
// we are not in a death test subprocess.
// Environment variables are not supported on Windows CE.
#if !GTEST_OS_WINDOWS_MOBILE
TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
SetEnv(index_var_, "4");
SetEnv(total_var_, "22");
EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
SetEnv(index_var_, "8");
SetEnv(total_var_, "9");
EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
SetEnv(index_var_, "0");
SetEnv(total_var_, "9");
EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests that we exit in error if the sharding values are not valid.
typedef ShouldShardTest ShouldShardDeathTest;
TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
SetEnv(index_var_, "4");
SetEnv(total_var_, "4");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
SetEnv(index_var_, "4");
SetEnv(total_var_, "-2");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
SetEnv(index_var_, "5");
SetEnv(total_var_, "");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
SetEnv(index_var_, "");
SetEnv(total_var_, "5");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
}
// Tests that ShouldRunTestOnShard is a partition when 5
// shards are used.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
// Choose an arbitrary number of tests and shards.
const int num_tests = 17;
const int num_shards = 5;
// Check partitioning: each test should be on exactly 1 shard.
for (int test_id = 0; test_id < num_tests; test_id++) {
int prev_selected_shard_index = -1;
for (int shard_index = 0; shard_index < num_shards; shard_index++) {
if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
if (prev_selected_shard_index < 0) {
prev_selected_shard_index = shard_index;
} else {
ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
<< shard_index << " are both selected to run test " << test_id;
}
}
}
}
// Check balance: This is not required by the sharding protocol, but is a
// desirable property for performance.
for (int shard_index = 0; shard_index < num_shards; shard_index++) {
int num_tests_on_shard = 0;
for (int test_id = 0; test_id < num_tests; test_id++) {
num_tests_on_shard +=
ShouldRunTestOnShard(num_shards, shard_index, test_id);
}
EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
}
}
// For the same reason we are not explicitly testing everything in the
// Test class, there are no separate tests for the following classes
// (except for some trivial cases):
//
// TestSuite, UnitTest, UnitTestResultPrinter.
//
// Similarly, there are no separate tests for the following macros:
//
// TEST, TEST_F, RUN_ALL_TESTS
TEST(UnitTestTest, CanGetOriginalWorkingDir) {
ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
}
TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
}
// When a property using a reserved key is supplied to this function, it
// tests that a non-fatal failure is added, a fatal failure is not added,
// and that the property is not recorded.
void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
const TestResult& test_result, const char* key) {
EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
<< "' recorded unexpectedly.";
}
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
const char* key) {
const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(test_info != nullptr);
ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
key);
}
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
const char* key) {
const testing::TestSuite* test_suite =
UnitTest::GetInstance()->current_test_suite();
ASSERT_TRUE(test_suite != nullptr);
ExpectNonFatalFailureRecordingPropertyWithReservedKey(
test_suite->ad_hoc_test_result(), key);
}
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
const char* key) {
ExpectNonFatalFailureRecordingPropertyWithReservedKey(
UnitTest::GetInstance()->ad_hoc_test_result(), key);
}
// Tests that property recording functions in UnitTest outside of tests
// functions correctly. Creating a separate instance of UnitTest ensures it
// is in a state similar to the UnitTest's singleton's between tests.
class UnitTestRecordPropertyTest :
public testing::internal::UnitTestRecordPropertyTestHelper {
public:
static void SetUpTestSuite() {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"disabled");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"errors");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"failures");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"tests");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"time");
Test::RecordProperty("test_case_key_1", "1");
const testing::TestSuite* test_suite =
UnitTest::GetInstance()->current_test_suite();
ASSERT_TRUE(test_suite != nullptr);
ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
EXPECT_STREQ("test_case_key_1",
test_suite->ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1",
test_suite->ad_hoc_test_result().GetTestProperty(0).value());
}
};
// Tests TestResult has the expected property when added.
TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
UnitTestRecordProperty("key_1", "1");
ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
}
// Tests TestResult has multiple properties when added.
TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
UnitTestRecordProperty("key_1", "1");
UnitTestRecordProperty("key_2", "2");
ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
EXPECT_STREQ("key_2",
unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
}
// Tests TestResult::RecordProperty() overrides values for duplicate keys.
TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
UnitTestRecordProperty("key_1", "1");
UnitTestRecordProperty("key_2", "2");
UnitTestRecordProperty("key_1", "12");
UnitTestRecordProperty("key_2", "22");
ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("12",
unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
EXPECT_STREQ("key_2",
unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
EXPECT_STREQ("22",
unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
}
TEST_F(UnitTestRecordPropertyTest,
AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"value_param");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"type_param");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"status");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"time");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"classname");
}
TEST_F(UnitTestRecordPropertyTest,
AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
EXPECT_NONFATAL_FAILURE(
Test::RecordProperty("name", "1"),
"'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
" 'file', and 'line' are reserved");
}
class UnitTestRecordPropertyTestEnvironment : public Environment {
public:
void TearDown() override {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"tests");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"failures");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"disabled");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"errors");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"timestamp");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"time");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"random_seed");
}
};
// This will test property recording outside of any test or test case.
static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
// of various arities. They do not attempt to be exhaustive. Rather,
// view them as smoke tests that can be easily reviewed and verified.
// A more complete set of tests for predicate assertions can be found
// in gtest_pred_impl_unittest.cc.
// First, some predicates and predicate-formatters needed by the tests.
// Returns true if and only if the argument is an even number.
bool IsEven(int n) {
return (n % 2) == 0;
}
// A functor that returns true if and only if the argument is an even number.
struct IsEvenFunctor {
bool operator()(int n) { return IsEven(n); }
};
// A predicate-formatter function that asserts the argument is an even
// number.
AssertionResult AssertIsEven(const char* expr, int n) {
if (IsEven(n)) {
return AssertionSuccess();
}
Message msg;
msg << expr << " evaluates to " << n << ", which is not even.";
return AssertionFailure(msg);
}
// A predicate function that returns AssertionResult for use in
// EXPECT/ASSERT_TRUE/FALSE.
AssertionResult ResultIsEven(int n) {
if (IsEven(n))
return AssertionSuccess() << n << " is even";
else
return AssertionFailure() << n << " is odd";
}
// A predicate function that returns AssertionResult but gives no
// explanation why it succeeds. Needed for testing that
// EXPECT/ASSERT_FALSE handles such functions correctly.
AssertionResult ResultIsEvenNoExplanation(int n) {
if (IsEven(n))
return AssertionSuccess();
else
return AssertionFailure() << n << " is odd";
}
// A predicate-formatter functor that asserts the argument is an even
// number.
struct AssertIsEvenFunctor {
AssertionResult operator()(const char* expr, int n) {
return AssertIsEven(expr, n);
}
};
// Returns true if and only if the sum of the arguments is an even number.
bool SumIsEven2(int n1, int n2) {
return IsEven(n1 + n2);
}
// A functor that returns true if and only if the sum of the arguments is an
// even number.
struct SumIsEven3Functor {
bool operator()(int n1, int n2, int n3) {
return IsEven(n1 + n2 + n3);
}
};
// A predicate-formatter function that asserts the sum of the
// arguments is an even number.
AssertionResult AssertSumIsEven4(
const char* e1, const char* e2, const char* e3, const char* e4,
int n1, int n2, int n3, int n4) {
const int sum = n1 + n2 + n3 + n4;
if (IsEven(sum)) {
return AssertionSuccess();
}
Message msg;
msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
<< " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
<< ") evaluates to " << sum << ", which is not even.";
return AssertionFailure(msg);
}
// A predicate-formatter functor that asserts the sum of the arguments
// is an even number.
struct AssertSumIsEven5Functor {
AssertionResult operator()(
const char* e1, const char* e2, const char* e3, const char* e4,
const char* e5, int n1, int n2, int n3, int n4, int n5) {
const int sum = n1 + n2 + n3 + n4 + n5;
if (IsEven(sum)) {
return AssertionSuccess();
}
Message msg;
msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
<< " ("
<< n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
<< ") evaluates to " << sum << ", which is not even.";
return AssertionFailure(msg);
}
};
// Tests unary predicate assertions.
// Tests unary predicate assertions that don't use a custom formatter.
TEST(Pred1Test, WithoutFormat) {
// Success cases.
EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
ASSERT_PRED1(IsEven, 4);
// Failure cases.
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
"evaluates to false");
}
// Tests unary predicate assertions that use a custom formatter.
TEST(Pred1Test, WithFormat) {
// Success cases.
EXPECT_PRED_FORMAT1(AssertIsEven, 2);
ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
<< "This failure is UNEXPECTED!";
// Failure cases.
const int n = 5;
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
"n evaluates to 5, which is not even.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
}, "This failure is expected.");
}
// Tests that unary predicate assertions evaluates their arguments
// exactly once.
TEST(Pred1Test, SingleEvaluationOnFailure) {
// A success case.
static int n = 0;
EXPECT_PRED1(IsEven, n++);
EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
// A failure case.
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
<< "This failure is expected.";
}, "This failure is expected.");
EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
}
// Tests predicate assertions whose arity is >= 2.
// Tests predicate assertions that don't use a custom formatter.
TEST(PredTest, WithoutFormat) {
// Success cases.
ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
// Failure cases.
const int n1 = 1;
const int n2 = 2;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
}, "evaluates to false");
}
// Tests predicate assertions that use a custom formatter.
TEST(PredTest, WithFormat) {
// Success cases.
ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
"This failure is UNEXPECTED!";
EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
// Failure cases.
const int n1 = 1;
const int n2 = 2;
const int n3 = 4;
const int n4 = 6;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
}, "evaluates to 13, which is not even.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
<< "This failure is expected.";
}, "This failure is expected.");
}
// Tests that predicate assertions evaluates their arguments
// exactly once.
TEST(PredTest, SingleEvaluationOnFailure) {
// A success case.
int n1 = 0;
int n2 = 0;
EXPECT_PRED2(SumIsEven2, n1++, n2++);
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
// Another success case.
n1 = n2 = 0;
int n3 = 0;
int n4 = 0;
int n5 = 0;
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
n1++, n2++, n3++, n4++, n5++)
<< "This failure is UNEXPECTED!";
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
// A failure case.
n1 = n2 = n3 = 0;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
<< "This failure is expected.";
}, "This failure is expected.");
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
// Another failure case.
n1 = n2 = n3 = n4 = 0;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
}, "evaluates to 1, which is not even.");
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
}
// Test predicate assertions for sets
TEST(PredTest, ExpectPredEvalFailure) {
std::set<int> set_a = {2, 1, 3, 4, 5};
std::set<int> set_b = {0, 4, 8};
const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
EXPECT_NONFATAL_FAILURE(
EXPECT_PRED2(compare_sets, set_a, set_b),
"compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
"to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
}
// Some helper functions for testing using overloaded/template
// functions with ASSERT_PREDn and EXPECT_PREDn.
bool IsPositive(double x) {
return x > 0;
}
template <typename T>
bool IsNegative(T x) {
return x < 0;
}
template <typename T1, typename T2>
bool GreaterThan(T1 x1, T2 x2) {
return x1 > x2;
}
// Tests that overloaded functions can be used in *_PRED* as long as
// their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
// C++Builder requires C-style casts rather than static_cast.
EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
}
// Tests that template functions can be used in *_PRED* as long as
// their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
EXPECT_PRED1(IsNegative<int>, -5);
// Makes sure that we can handle templates with more than one
// parameter.
ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
}
// Some helper functions for testing using overloaded/template
// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
return n > 0 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
return x > 0 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
template <typename T>
AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
return x < 0 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
template <typename T1, typename T2>
AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
const T1& x1, const T2& x2) {
return x1 == x2 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
// Tests that overloaded functions can be used in *_PRED_FORMAT*
// without explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
}
// Tests that template functions can be used in *_PRED_FORMAT* without
// explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
}
// Tests string assertions.
// Tests ASSERT_STREQ with non-NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ) {
const char * const p1 = "good";
ASSERT_STREQ(p1, p1);
// Let p2 have the same content as p1, but be at a different address.
const char p2[] = "good";
ASSERT_STREQ(p1, p2);
EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
" \"bad\"\n \"good\"");
}
// Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null) {
ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
}
// Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
}
// Tests ASSERT_STRNE.
TEST(StringAssertionTest, ASSERT_STRNE) {
ASSERT_STRNE("hi", "Hi");
ASSERT_STRNE("Hi", nullptr);
ASSERT_STRNE(nullptr, "Hi");
ASSERT_STRNE("", nullptr);
ASSERT_STRNE(nullptr, "");
ASSERT_STRNE("", "Hi");
ASSERT_STRNE("Hi", "");
EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
"\"Hi\" vs \"Hi\"");
}
// Tests ASSERT_STRCASEEQ.
TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
ASSERT_STRCASEEQ("hi", "Hi");
ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
ASSERT_STRCASEEQ("", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
"Ignoring case");
}
// Tests ASSERT_STRCASENE.
TEST(StringAssertionTest, ASSERT_STRCASENE) {
ASSERT_STRCASENE("hi1", "Hi2");
ASSERT_STRCASENE("Hi", nullptr);
ASSERT_STRCASENE(nullptr, "Hi");
ASSERT_STRCASENE("", nullptr);
ASSERT_STRCASENE(nullptr, "");
ASSERT_STRCASENE("", "Hi");
ASSERT_STRCASENE("Hi", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
"(ignoring case)");
}
// Tests *_STREQ on wide strings.
TEST(StringAssertionTest, STREQ_Wide) {
// NULL strings.
ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
// Empty strings.
ASSERT_STREQ(L"", L"");
// Non-null vs NULL.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
// Equal strings.
EXPECT_STREQ(L"Hi", L"Hi");
// Unequal strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
"Abc");
// Strings containing wide characters.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
"abc");
// The streaming variation.
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
}, "Expected failure");
}
// Tests *_STRNE on wide strings.
TEST(StringAssertionTest, STRNE_Wide) {
// NULL strings.
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
},
"");
// Empty strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
"L\"\"");
// Non-null vs NULL.
ASSERT_STRNE(L"non-null", nullptr);
// Equal strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
"L\"Hi\"");
// Unequal strings.
EXPECT_STRNE(L"abc", L"Abc");
// Strings containing wide characters.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
"abc");
// The streaming variation.
ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
}
// Tests for ::testing::IsSubstring().
// Tests that IsSubstring() returns the correct result when the input
// argument type is const char*.
TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
}
// Tests that IsSubstring() returns the correct result when the input
// argument type is const wchar_t*.
TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
EXPECT_TRUE(
IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
}
// Tests that IsSubstring() generates the correct message when the input
// argument type is const char*.
TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: \"needle\"\n"
"Expected: a substring of haystack_expr\n"
"Which is: \"haystack\"",
IsSubstring("needle_expr", "haystack_expr",
"needle", "haystack").failure_message());
}
// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
}
#if GTEST_HAS_STD_WSTRING
// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::wstring.
TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
}
// Tests that IsSubstring() generates the correct message when the input
// argument type is ::std::wstring.
TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: L\"needle\"\n"
"Expected: a substring of haystack_expr\n"
"Which is: L\"haystack\"",
IsSubstring(
"needle_expr", "haystack_expr",
::std::wstring(L"needle"), L"haystack").failure_message());
}
#endif // GTEST_HAS_STD_WSTRING
// Tests for ::testing::IsNotSubstring().
// Tests that IsNotSubstring() returns the correct result when the input
// argument type is const char*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
}
// Tests that IsNotSubstring() returns the correct result when the input
// argument type is const wchar_t*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
}
// Tests that IsNotSubstring() generates the correct message when the input
// argument type is const wchar_t*.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: L\"needle\"\n"
"Expected: not a substring of haystack_expr\n"
"Which is: L\"two needles\"",
IsNotSubstring(
"needle_expr", "haystack_expr",
L"needle", L"two needles").failure_message());
}
// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
}
// Tests that IsNotSubstring() generates the correct message when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: \"needle\"\n"
"Expected: not a substring of haystack_expr\n"
"Which is: \"two needles\"",
IsNotSubstring(
"needle_expr", "haystack_expr",
::std::string("needle"), "two needles").failure_message());
}
#if GTEST_HAS_STD_WSTRING
// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::wstring.
TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
EXPECT_FALSE(
IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
}
#endif // GTEST_HAS_STD_WSTRING
// Tests floating-point assertions.
template <typename RawType>
class FloatingPointTest : public Test {
protected:
// Pre-calculated numbers to be used by the tests.
struct TestValues {
RawType close_to_positive_zero;
RawType close_to_negative_zero;
RawType further_from_negative_zero;
RawType close_to_one;
RawType further_from_one;
RawType infinity;
RawType close_to_infinity;
RawType further_from_infinity;
RawType nan1;
RawType nan2;
};
typedef typename testing::internal::FloatingPoint<RawType> Floating;
typedef typename Floating::Bits Bits;
void SetUp() override {
const uint32_t max_ulps = Floating::kMaxUlps;
// The bits that represent 0.0.
const Bits zero_bits = Floating(0).bits();
// Makes some numbers close to 0.0.
values_.close_to_positive_zero = Floating::ReinterpretBits(
zero_bits + max_ulps/2);
values_.close_to_negative_zero = -Floating::ReinterpretBits(
zero_bits + max_ulps - max_ulps/2);
values_.further_from_negative_zero = -Floating::ReinterpretBits(
zero_bits + max_ulps + 1 - max_ulps/2);
// The bits that represent 1.0.
const Bits one_bits = Floating(1).bits();
// Makes some numbers close to 1.0.
values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
values_.further_from_one = Floating::ReinterpretBits(
one_bits + max_ulps + 1);
// +infinity.
values_.infinity = Floating::Infinity();
// The bits that represent +infinity.
const Bits infinity_bits = Floating(values_.infinity).bits();
// Makes some numbers close to infinity.
values_.close_to_infinity = Floating::ReinterpretBits(
infinity_bits - max_ulps);
values_.further_from_infinity = Floating::ReinterpretBits(
infinity_bits - max_ulps - 1);
// Makes some NAN's. Sets the most significant bit of the fraction so that
// our NaN's are quiet; trying to process a signaling NaN would raise an
// exception if our environment enables floating point exceptions.
values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
| (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
| (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
}
void TestSize() {
EXPECT_EQ(sizeof(RawType), sizeof(Bits));
}
static TestValues values_;
};
template <typename RawType>
typename FloatingPointTest<RawType>::TestValues
FloatingPointTest<RawType>::values_;
// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
typedef FloatingPointTest<float> FloatTest;
// Tests that the size of Float::Bits matches the size of float.
TEST_F(FloatTest, Size) {
TestSize();
}
// Tests comparing with +0 and -0.
TEST_F(FloatTest, Zeros) {
EXPECT_FLOAT_EQ(0.0, -0.0);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
"1.0");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
"1.5");
}
// Tests comparing numbers close to 0.
//
// This ensures that *_FLOAT_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very
// small.
TEST_F(FloatTest, AlmostZeros) {
// In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax
// (parentheses).
static const FloatTest::TestValues& v = this->values_;
EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_FLOAT_EQ(v.close_to_positive_zero,
v.further_from_negative_zero);
}, "v.further_from_negative_zero");
}
// Tests comparing numbers close to each other.
TEST_F(FloatTest, SmallDiff) {
EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
"values_.further_from_one");
}
// Tests comparing numbers far apart.
TEST_F(FloatTest, LargeDiff) {
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
"3.0");
}
// Tests comparing with infinity.
//
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(FloatTest, Infinity) {
EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
"-values_.infinity");
// This is interesting as the representations of infinity and nan1
// are only 1 DLP apart.
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
"values_.nan1");
}
// Tests that comparing with NAN always returns false.
TEST_F(FloatTest, NaN) {
// In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax
// (parentheses).
static const FloatTest::TestValues& v = this->values_;
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
"v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
"v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
"v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
"v.infinity");
}
// Tests that *_FLOAT_EQ are reflexive.
TEST_F(FloatTest, Reflexive) {
EXPECT_FLOAT_EQ(0.0, 0.0);
EXPECT_FLOAT_EQ(1.0, 1.0);
ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
}
// Tests that *_FLOAT_EQ are commutative.
TEST_F(FloatTest, Commutative) {
// We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
// We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
"1.0");
}
// Tests EXPECT_NEAR.
TEST_F(FloatTest, EXPECT_NEAR) {
EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
EXPECT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
}
// Tests ASSERT_NEAR.
TEST_F(FloatTest, ASSERT_NEAR) {
ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
ASSERT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
}
// Tests the cases where FloatLE() should succeed.
TEST_F(FloatTest, FloatLESucceeds) {
EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
// or when val1 is greater than, but almost equals to, val2.
EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
}
// Tests the cases where FloatLE() should fail.
TEST_F(FloatTest, FloatLEFails) {
// When val1 is greater than val2 by a large margin,
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
"(2.0f) <= (1.0f)");
// or by a small yet non-negligible margin,
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
}, "(values_.further_from_one) <= (1.0f)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
}, "(values_.nan1) <= (values_.infinity)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
}, "(-values_.infinity) <= (values_.nan1)");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
}, "(values_.nan1) <= (values_.nan1)");
}
// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
typedef FloatingPointTest<double> DoubleTest;
// Tests that the size of Double::Bits matches the size of double.
TEST_F(DoubleTest, Size) {
TestSize();
}
// Tests comparing with +0 and -0.
TEST_F(DoubleTest, Zeros) {
EXPECT_DOUBLE_EQ(0.0, -0.0);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
"1.0");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
"1.0");
}
// Tests comparing numbers close to 0.
//
// This ensures that *_DOUBLE_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very
// small.
TEST_F(DoubleTest, AlmostZeros) {
// In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax
// (parentheses).
static const DoubleTest::TestValues& v = this->values_;
EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
v.further_from_negative_zero);
}, "v.further_from_negative_zero");
}
// Tests comparing numbers close to each other.
TEST_F(DoubleTest, SmallDiff) {
EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
"values_.further_from_one");
}
// Tests comparing numbers far apart.
TEST_F(DoubleTest, LargeDiff) {
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
"3.0");
}
// Tests comparing with infinity.
//
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(DoubleTest, Infinity) {
EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
"-values_.infinity");
// This is interesting as the representations of infinity_ and nan1_
// are only 1 DLP apart.
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
"values_.nan1");
}
// Tests that comparing with NAN always returns false.
TEST_F(DoubleTest, NaN) {
static const DoubleTest::TestValues& v = this->values_;
// Nokia's STLport crashes if we try to output infinity or NaN.
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
"v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
"v.infinity");
}
// Tests that *_DOUBLE_EQ are reflexive.
TEST_F(DoubleTest, Reflexive) {
EXPECT_DOUBLE_EQ(0.0, 0.0);
EXPECT_DOUBLE_EQ(1.0, 1.0);
ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
}
// Tests that *_DOUBLE_EQ are commutative.
TEST_F(DoubleTest, Commutative) {
// We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
// We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
"1.0");
}
// Tests EXPECT_NEAR.
TEST_F(DoubleTest, EXPECT_NEAR) {
EXPECT_NEAR(-1.0, -1.1, 0.2);
EXPECT_NEAR(2.0, 3.0, 1.0);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
// At this magnitude adjacent doubles are 512.0 apart, so this triggers a
// slightly different failure reporting path.
EXPECT_NONFATAL_FAILURE(
EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
"The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
"minimum distance between doubles for numbers of this magnitude which is "
"512");
}
// Tests ASSERT_NEAR.
TEST_F(DoubleTest, ASSERT_NEAR) {
ASSERT_NEAR(-1.0, -1.1, 0.2);
ASSERT_NEAR(2.0, 3.0, 1.0);
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
}
// Tests the cases where DoubleLE() should succeed.
TEST_F(DoubleTest, DoubleLESucceeds) {
EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
// or when val1 is greater than, but almost equals to, val2.
EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
}
// Tests the cases where DoubleLE() should fail.
TEST_F(DoubleTest, DoubleLEFails) {
// When val1 is greater than val2 by a large margin,
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
"(2.0) <= (1.0)");
// or by a small yet non-negligible margin,
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
}, "(values_.further_from_one) <= (1.0)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
}, "(values_.nan1) <= (values_.infinity)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
}, " (-values_.infinity) <= (values_.nan1)");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
}, "(values_.nan1) <= (values_.nan1)");
}
// Verifies that a test or test case whose name starts with DISABLED_ is
// not run.
// A test whose name starts with DISABLED_.
// Should not run.
TEST(DisabledTest, DISABLED_TestShouldNotRun) {
FAIL() << "Unexpected failure: Disabled test should not be run.";
}
// A test whose name does not start with DISABLED_.
// Should run.
TEST(DisabledTest, NotDISABLED_TestShouldRun) {
EXPECT_EQ(1, 1);
}
// A test case whose name starts with DISABLED_.
// Should not run.
TEST(DISABLED_TestSuite, TestShouldNotRun) {
FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
}
// A test case and test whose names start with DISABLED_.
// Should not run.
TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
}
// Check that when all tests in a test case are disabled, SetUpTestSuite() and
// TearDownTestSuite() are not called.
class DisabledTestsTest : public Test {
protected:
static void SetUpTestSuite() {
FAIL() << "Unexpected failure: All tests disabled in test case. "
"SetUpTestSuite() should not be called.";
}
static void TearDownTestSuite() {
FAIL() << "Unexpected failure: All tests disabled in test case. "
"TearDownTestSuite() should not be called.";
}
};
TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
FAIL() << "Unexpected failure: Disabled test should not be run.";
}
TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
FAIL() << "Unexpected failure: Disabled test should not be run.";
}
// Tests that disabled typed tests aren't run.
template <typename T>
class TypedTest : public Test {
};
typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(TypedTest, NumericTypes);
TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run.";
}
template <typename T>
class DISABLED_TypedTest : public Test {
};
TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run.";
}
// Tests that disabled type-parameterized tests aren't run.
template <typename T>
class TypedTestP : public Test {
};
TYPED_TEST_SUITE_P(TypedTestP);
TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
FAIL() << "Unexpected failure: "
<< "Disabled type-parameterized test should not run.";
}
REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
template <typename T>
class DISABLED_TypedTestP : public Test {
};
TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
FAIL() << "Unexpected failure: "
<< "Disabled type-parameterized test should not run.";
}
REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
// Tests that assertion macros evaluate their arguments exactly once.
class SingleEvaluationTest : public Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2.
// This helper function is needed by the FailedASSERT_STREQ test
// below. It's public to work around C++Builder's bug with scoping local
// classes.
static void CompareAndIncrementCharPtrs() {
ASSERT_STREQ(p1_++, p2_++);
}
// This helper function is needed by the FailedASSERT_NE test below. It's
// public to work around C++Builder's bug with scoping local classes.
static void CompareAndIncrementInts() {
ASSERT_NE(a_++, b_++);
}
protected:
SingleEvaluationTest() {
p1_ = s1_;
p2_ = s2_;
a_ = 0;
b_ = 0;
}
static const char* const s1_;
static const char* const s2_;
static const char* p1_;
static const char* p2_;
static int a_;
static int b_;
};
const char* const SingleEvaluationTest::s1_ = "01234";
const char* const SingleEvaluationTest::s2_ = "abcde";
const char* SingleEvaluationTest::p1_;
const char* SingleEvaluationTest::p2_;
int SingleEvaluationTest::a_;
int SingleEvaluationTest::b_;
// Tests that when ASSERT_STREQ fails, it evaluates its arguments
// exactly once.
TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
"p2_++");
EXPECT_EQ(s1_ + 1, p1_);
EXPECT_EQ(s2_ + 1, p2_);
}
// Tests that string assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ASSERT_STR) {
// successful EXPECT_STRNE
EXPECT_STRNE(p1_++, p2_++);
EXPECT_EQ(s1_ + 1, p1_);
EXPECT_EQ(s2_ + 1, p2_);
// failed EXPECT_STRCASEEQ
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
"Ignoring case");
EXPECT_EQ(s1_ + 2, p1_);
EXPECT_EQ(s2_ + 2, p2_);
}
// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
// once.
TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
"(a_++) != (b_++)");
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
}
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, OtherCases) {
// successful EXPECT_TRUE
EXPECT_TRUE(0 == a_++); // NOLINT
EXPECT_EQ(1, a_);
// failed EXPECT_TRUE
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
EXPECT_EQ(2, a_);
// successful EXPECT_GT
EXPECT_GT(a_++, b_++);
EXPECT_EQ(3, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_LT
EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
EXPECT_EQ(4, a_);
EXPECT_EQ(2, b_);
// successful ASSERT_TRUE
ASSERT_TRUE(0 < a_++); // NOLINT
EXPECT_EQ(5, a_);
// successful ASSERT_GT
ASSERT_GT(a_++, b_++);
EXPECT_EQ(6, a_);
EXPECT_EQ(3, b_);
}
#if GTEST_HAS_EXCEPTIONS
#if GTEST_HAS_RTTI
#ifdef _MSC_VER
#define ERROR_DESC "class std::runtime_error"
#else
#define ERROR_DESC "std::runtime_error"
#endif
#else // GTEST_HAS_RTTI
#define ERROR_DESC "an std::exception-derived error"
#endif // GTEST_HAS_RTTI
void ThrowAnInteger() {
throw 1;
}
void ThrowRuntimeError(const char* what) {
throw std::runtime_error(what);
}
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ExceptionTests) {
// successful EXPECT_THROW
EXPECT_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}, int);
EXPECT_EQ(1, a_);
// failed EXPECT_THROW, throws different
EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}, bool), "throws a different type");
EXPECT_EQ(2, a_);
// failed EXPECT_THROW, throws runtime error
EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
a_++;
ThrowRuntimeError("A description");
}, bool), "throws " ERROR_DESC " with description \"A description\"");
EXPECT_EQ(3, a_);
// failed EXPECT_THROW, throws nothing
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
EXPECT_EQ(4, a_);
// successful EXPECT_NO_THROW
EXPECT_NO_THROW(a_++);
EXPECT_EQ(5, a_);
// failed EXPECT_NO_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}), "it throws");
EXPECT_EQ(6, a_);
// successful EXPECT_ANY_THROW
EXPECT_ANY_THROW({ // NOLINT
a_++;
ThrowAnInteger();
});
EXPECT_EQ(7, a_);
// failed EXPECT_ANY_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
EXPECT_EQ(8, a_);
}
#endif // GTEST_HAS_EXCEPTIONS
// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
class NoFatalFailureTest : public Test {
protected:
void Succeeds() {}
void FailsNonFatal() {
ADD_FAILURE() << "some non-fatal failure";
}
void Fails() {
FAIL() << "some fatal failure";
}
void DoAssertNoFatalFailureOnFails() {
ASSERT_NO_FATAL_FAILURE(Fails());
ADD_FAILURE() << "should not reach here.";
}
void DoExpectNoFatalFailureOnFails() {
EXPECT_NO_FATAL_FAILURE(Fails());
ADD_FAILURE() << "other failure";
}
};
TEST_F(NoFatalFailureTest, NoFailure) {
EXPECT_NO_FATAL_FAILURE(Succeeds());
ASSERT_NO_FATAL_FAILURE(Succeeds());
}
TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
EXPECT_NONFATAL_FAILURE(
EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
"some non-fatal failure");
EXPECT_NONFATAL_FAILURE(
ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
"some non-fatal failure");
}
TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
DoAssertNoFatalFailureOnFails();
}
ASSERT_EQ(2, gtest_failures.size());
EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(1).type());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
gtest_failures.GetTestPartResult(0).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
gtest_failures.GetTestPartResult(1).message());
}
TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
DoExpectNoFatalFailureOnFails();
}
ASSERT_EQ(3, gtest_failures.size());
EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(1).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(2).type());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
gtest_failures.GetTestPartResult(0).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
gtest_failures.GetTestPartResult(1).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
gtest_failures.GetTestPartResult(2).message());
}
TEST_F(NoFatalFailureTest, MessageIsStreamable) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
}
ASSERT_EQ(2, gtest_failures.size());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(1).type());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
gtest_failures.GetTestPartResult(0).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
gtest_failures.GetTestPartResult(1).message());
}
// Tests non-string assertions.
std::string EditsToString(const std::vector<EditType>& edits) {
std::string out;
for (size_t i = 0; i < edits.size(); ++i) {
static const char kEdits[] = " +-/";
out.append(1, kEdits[edits[i]]);
}
return out;
}
std::vector<size_t> CharsToIndices(const std::string& str) {
std::vector<size_t> out;
for (size_t i = 0; i < str.size(); ++i) {
out.push_back(static_cast<size_t>(str[i]));
}
return out;
}
std::vector<std::string> CharsToLines(const std::string& str) {
std::vector<std::string> out;
for (size_t i = 0; i < str.size(); ++i) {
out.push_back(str.substr(i, 1));
}
return out;
}
TEST(EditDistance, TestSuites) {
struct Case {
int line;
const char* left;
const char* right;
const char* expected_edits;
const char* expected_diff;
};
static const Case kCases[] = {
// No change.
{__LINE__, "A", "A", " ", ""},
{__LINE__, "ABCDE", "ABCDE", " ", ""},
// Simple adds.
{__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
{__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
// Simple removes.
{__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
{__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
// Simple replaces.
{__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
{__LINE__, "ABCD", "abcd", "////",
"@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
// Path finding.
{__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
"@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
{__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
"@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
{__LINE__, "ABCDE", "BCDCD", "- +/",
"@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
{__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
"@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
"@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
{}};
for (const Case* c = kCases; c->left; ++c) {
EXPECT_TRUE(c->expected_edits ==
EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
CharsToIndices(c->right))))
<< "Left <" << c->left << "> Right <" << c->right << "> Edits <"
<< EditsToString(CalculateOptimalEdits(
CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
CharsToLines(c->right)))
<< "Left <" << c->left << "> Right <" << c->right << "> Diff <"
<< CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
<< ">";
}
}
// Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest, EqFailure) {
const std::string foo_val("5"), bar_val("6");
const std::string msg1(
EqFailure("foo", "bar", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
" Which is: 5\n"
" bar\n"
" Which is: 6",
msg1.c_str());
const std::string msg2(
EqFailure("foo", "6", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
" Which is: 5\n"
" 6",
msg2.c_str());
const std::string msg3(
EqFailure("5", "bar", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" 5\n"
" bar\n"
" Which is: 6",
msg3.c_str());
const std::string msg4(
EqFailure("5", "6", foo_val, bar_val, false).failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" 5\n"
" 6",
msg4.c_str());
const std::string msg5(
EqFailure("foo", "bar",
std::string("\"x\""), std::string("\"y\""),
true).failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
" Which is: \"x\"\n"
" bar\n"
" Which is: \"y\"\n"
"Ignoring case",
msg5.c_str());
}
TEST(AssertionTest, EqFailureWithDiff) {
const std::string left(
"1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
const std::string right(
"1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
const std::string msg1(
EqFailure("left", "right", left, right, false).failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" left\n"
" Which is: "
"1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
" right\n"
" Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
"With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
"@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
msg1.c_str());
}
// Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest, AppendUserMessage) {
const std::string foo("foo");
Message msg;
EXPECT_STREQ("foo",
AppendUserMessage(foo, msg).c_str());
msg << "bar";
EXPECT_STREQ("foo\nbar",
AppendUserMessage(foo, msg).c_str());
}
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch
#endif
// Tests ASSERT_TRUE.
TEST(AssertionTest, ASSERT_TRUE) {
ASSERT_TRUE(2 > 1); // NOLINT
EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
"2 < 1");
}
// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertTrueWithAssertionResult) {
ASSERT_TRUE(ResultIsEven(2));
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
"Value of: ResultIsEven(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
#endif
ASSERT_TRUE(ResultIsEvenNoExplanation(2));
EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
"Value of: ResultIsEvenNoExplanation(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
}
// Tests ASSERT_FALSE.
TEST(AssertionTest, ASSERT_FALSE) {
ASSERT_FALSE(2 < 1); // NOLINT
EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
"Value of: 2 > 1\n"
" Actual: true\n"
"Expected: false");
}
// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertFalseWithAssertionResult) {
ASSERT_FALSE(ResultIsEven(3));
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
"Value of: ResultIsEven(2)\n"
" Actual: true (2 is even)\n"
"Expected: false");
#endif
ASSERT_FALSE(ResultIsEvenNoExplanation(3));
EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
"Value of: ResultIsEvenNoExplanation(2)\n"
" Actual: true\n"
"Expected: false");
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
// Tests using ASSERT_EQ on double values. The purpose is to make
// sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments.
TEST(ExpectTest, ASSERT_EQ_Double) {
// A success.
ASSERT_EQ(5.6, 5.6);
// A failure.
EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
"5.1");
}
// Tests ASSERT_EQ.
TEST(AssertionTest, ASSERT_EQ) {
ASSERT_EQ(5, 2 + 3);
EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
"Expected equality of these values:\n"
" 5\n"
" 2*3\n"
" Which is: 6");
}
// Tests ASSERT_EQ(NULL, pointer).
TEST(AssertionTest, ASSERT_EQ_NULL) {
// A success.
const char* p = nullptr;
ASSERT_EQ(nullptr, p);
// A failure.
static int n = 0;
EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
}
// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
// treated as a null pointer by the compiler, we need to make sure
// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, ASSERT_EQ_0) {
int n = 0;
// A success.
ASSERT_EQ(0, n);
// A failure.
EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
" 0\n 5.6");
}
// Tests ASSERT_NE.
TEST(AssertionTest, ASSERT_NE) {
ASSERT_NE(6, 7);
EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
"Expected: ('a') != ('a'), "
"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
}
// Tests ASSERT_LE.
TEST(AssertionTest, ASSERT_LE) {
ASSERT_LE(2, 3);
ASSERT_LE(2, 2);
EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
"Expected: (2) <= (0), actual: 2 vs 0");
}
// Tests ASSERT_LT.
TEST(AssertionTest, ASSERT_LT) {
ASSERT_LT(2, 3);
EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
"Expected: (2) < (2), actual: 2 vs 2");
}
// Tests ASSERT_GE.
TEST(AssertionTest, ASSERT_GE) {
ASSERT_GE(2, 1);
ASSERT_GE(2, 2);
EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
"Expected: (2) >= (3), actual: 2 vs 3");
}
// Tests ASSERT_GT.
TEST(AssertionTest, ASSERT_GT) {
ASSERT_GT(2, 1);
EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
"Expected: (2) > (2), actual: 2 vs 2");
}
#if GTEST_HAS_EXCEPTIONS
void ThrowNothing() {}
// Tests ASSERT_THROW.
TEST(AssertionTest, ASSERT_THROW) {
ASSERT_THROW(ThrowAnInteger(), int);
# ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of type bool.\n"
" Actual: it throws a different type.");
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
"Expected: ThrowRuntimeError(\"A description\") "
"throws an exception of type std::logic_error.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
# endif
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing.");
}
// Tests ASSERT_NO_THROW.
TEST(AssertionTest, ASSERT_NO_THROW) {
ASSERT_NO_THROW(ThrowNothing());
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an exception."
"\n Actual: it throws.");
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
}
// Tests ASSERT_ANY_THROW.
TEST(AssertionTest, ASSERT_ANY_THROW) {
ASSERT_ANY_THROW(ThrowAnInteger());
EXPECT_FATAL_FAILURE(
ASSERT_ANY_THROW(ThrowNothing()),
"Expected: ThrowNothing() throws an exception.\n"
" Actual: it doesn't.");
}
#endif // GTEST_HAS_EXCEPTIONS
// Makes sure we deal with the precedence of <<. This test should
// compile.
TEST(AssertionTest, AssertPrecedence) {
ASSERT_EQ(1 < 2, true);
bool false_value = false;
ASSERT_EQ(true && false_value, false);
}
// A subroutine used by the following test.
void TestEq1(int x) {
ASSERT_EQ(1, x);
}
// Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest, NonFixtureSubroutine) {
EXPECT_FATAL_FAILURE(TestEq1(2),
" x\n Which is: 2");
}
// An uncopyable class.
class Uncopyable {
public:
explicit Uncopyable(int a_value) : value_(a_value) {}
int value() const { return value_; }
bool operator==(const Uncopyable& rhs) const {
return value() == rhs.value();
}
private:
// This constructor deliberately has no implementation, as we don't
// want this class to be copyable.
Uncopyable(const Uncopyable&); // NOLINT
int value_;
};
::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
return os << value.value();
}
bool IsPositiveUncopyable(const Uncopyable& x) {
return x.value() > 0;
}
// A subroutine used by the following test.
void TestAssertNonPositive() {
Uncopyable y(-1);
ASSERT_PRED1(IsPositiveUncopyable, y);
}
// A subroutine used by the following test.
void TestAssertEqualsUncopyable() {
Uncopyable x(5);
Uncopyable y(-1);
ASSERT_EQ(x, y);
}
// Tests that uncopyable objects can be used in assertions.
TEST(AssertionTest, AssertWorksWithUncopyableObject) {
Uncopyable x(5);
ASSERT_PRED1(IsPositiveUncopyable, x);
ASSERT_EQ(x, x);
EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
"Expected equality of these values:\n"
" x\n Which is: 5\n y\n Which is: -1");
}
// Tests that uncopyable objects can be used in expects.
TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
Uncopyable x(5);
EXPECT_PRED1(IsPositiveUncopyable, x);
Uncopyable y(-1);
EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_EQ(x, x);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
"Expected equality of these values:\n"
" x\n Which is: 5\n y\n Which is: -1");
}
enum NamedEnum {
kE1 = 0,
kE2 = 1
};
TEST(AssertionTest, NamedEnum) {
EXPECT_EQ(kE1, kE1);
EXPECT_LT(kE1, kE2);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
}
// Sun Studio and HP aCC2reject this code.
#if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
// Tests using assertions with anonymous enums.
enum {
kCaseA = -1,
# if GTEST_OS_LINUX
// We want to test the case where the size of the anonymous enum is
// larger than sizeof(int), to make sure our implementation of the
// assertions doesn't truncate the enums. However, MSVC
// (incorrectly) doesn't allow an enum value to exceed the range of
// an int, so this has to be conditionally compiled.
//
// On Linux, kCaseB and kCaseA have the same value when truncated to
// int size. We want to test whether this will confuse the
// assertions.
kCaseB = testing::internal::kMaxBiggestInt,
# else
kCaseB = INT_MAX,
# endif // GTEST_OS_LINUX
kCaseC = 42
};
TEST(AssertionTest, AnonymousEnum) {
# if GTEST_OS_LINUX
EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
# endif // GTEST_OS_LINUX
EXPECT_EQ(kCaseA, kCaseA);
EXPECT_NE(kCaseA, kCaseB);
EXPECT_LT(kCaseA, kCaseB);
EXPECT_LE(kCaseA, kCaseB);
EXPECT_GT(kCaseB, kCaseA);
EXPECT_GE(kCaseA, kCaseA);
EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
"(kCaseA) >= (kCaseB)");
EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
"-1 vs 42");
ASSERT_EQ(kCaseA, kCaseA);
ASSERT_NE(kCaseA, kCaseB);
ASSERT_LT(kCaseA, kCaseB);
ASSERT_LE(kCaseA, kCaseB);
ASSERT_GT(kCaseB, kCaseA);
ASSERT_GE(kCaseA, kCaseA);
# ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
" kCaseB\n Which is: ");
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
"\n Which is: 42");
# endif
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
"\n Which is: -1");
}
#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
#if GTEST_OS_WINDOWS
static HRESULT UnexpectedHRESULTFailure() {
return E_UNEXPECTED;
}
static HRESULT OkHRESULTSuccess() {
return S_OK;
}
static HRESULT FalseHRESULTSuccess() {
return S_FALSE;
}
// HRESULT assertion tests test both zero and non-zero
// success codes as well as failure message for each.
//
// Windows CE doesn't support message texts.
TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
EXPECT_HRESULT_SUCCEEDED(S_OK);
EXPECT_HRESULT_SUCCEEDED(S_FALSE);
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
"Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
" Actual: 0x8000FFFF");
}
TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
ASSERT_HRESULT_SUCCEEDED(S_OK);
ASSERT_HRESULT_SUCCEEDED(S_FALSE);
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
"Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
" Actual: 0x8000FFFF");
}
TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
EXPECT_HRESULT_FAILED(E_UNEXPECTED);
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
"Expected: (OkHRESULTSuccess()) fails.\n"
" Actual: 0x0");
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
"Expected: (FalseHRESULTSuccess()) fails.\n"
" Actual: 0x1");
}
TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
ASSERT_HRESULT_FAILED(E_UNEXPECTED);
# ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
"Expected: (OkHRESULTSuccess()) fails.\n"
" Actual: 0x0");
# endif
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
"Expected: (FalseHRESULTSuccess()) fails.\n"
" Actual: 0x1");
}
// Tests that streaming to the HRESULT macros works.
TEST(HRESULTAssertionTest, Streaming) {
EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
"expected failure");
# ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(
ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
"expected failure");
# endif
EXPECT_NONFATAL_FAILURE(
EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(
ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
"expected failure");
}
#endif // GTEST_OS_WINDOWS
// The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas"
#endif
// Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
ASSERT_TRUE(false) << "This should never be executed; "
"It's a compilation test only.";
if (AlwaysTrue())
EXPECT_FALSE(false);
else
; // NOLINT
if (AlwaysFalse())
ASSERT_LT(1, 3);
if (AlwaysFalse())
; // NOLINT
else
EXPECT_GT(3, 2) << "";
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#if GTEST_HAS_EXCEPTIONS
// Tests that the compiler will not complain about unreachable code in the
// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
int n = 0;
EXPECT_THROW(throw 1, int);
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
EXPECT_NO_THROW(n++);
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
EXPECT_ANY_THROW(throw 1);
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
}
TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
EXPECT_THROW(throw std::exception(), std::exception);
}
// The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas"
#endif
TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_THROW(ThrowNothing(), bool);
if (AlwaysTrue())
EXPECT_THROW(ThrowAnInteger(), int);
else
; // NOLINT
if (AlwaysFalse())
EXPECT_NO_THROW(ThrowAnInteger());
if (AlwaysTrue())
EXPECT_NO_THROW(ThrowNothing());
else
; // NOLINT
if (AlwaysFalse())
EXPECT_ANY_THROW(ThrowNothing());
if (AlwaysTrue())
EXPECT_ANY_THROW(ThrowAnInteger());
else
; // NOLINT
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#endif // GTEST_HAS_EXCEPTIONS
// The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas"
#endif
TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
<< "It's a compilation test only.";
else
; // NOLINT
if (AlwaysFalse())
ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
else
; // NOLINT
if (AlwaysTrue())
EXPECT_NO_FATAL_FAILURE(SUCCEED());
else
; // NOLINT
if (AlwaysFalse())
; // NOLINT
else
ASSERT_NO_FATAL_FAILURE(SUCCEED());
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
// Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) {
switch (0) {
case 1:
break;
default:
ASSERT_TRUE(true);
}
switch (0)
case 0:
EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
// Binary assertions are implemented using a different code path
// than the Boolean assertions. Hence we test them separately.
switch (0) {
case 1:
default:
ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
}
switch (0)
case 0:
EXPECT_NE(1, 2);
}
#if GTEST_HAS_EXCEPTIONS
void ThrowAString() {
throw "std::string";
}
// Test that the exception assertion macros compile and work with const
// type qualifier.
TEST(AssertionSyntaxTest, WorksWithConst) {
ASSERT_THROW(ThrowAString(), const char*);
EXPECT_THROW(ThrowAString(), const char*);
}
#endif // GTEST_HAS_EXCEPTIONS
} // namespace
namespace testing {
// Tests that Google Test tracks SUCCEED*.
TEST(SuccessfulAssertionTest, SUCCEED) {
SUCCEED();
SUCCEED() << "OK";
EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful EXPECT_*.
TEST(SuccessfulAssertionTest, EXPECT) {
EXPECT_TRUE(true);
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful EXPECT_STR*.
TEST(SuccessfulAssertionTest, EXPECT_STR) {
EXPECT_STREQ("", "");
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful ASSERT_*.
TEST(SuccessfulAssertionTest, ASSERT) {
ASSERT_TRUE(true);
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful ASSERT_STR*.
TEST(SuccessfulAssertionTest, ASSERT_STR) {
ASSERT_STREQ("", "");
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
} // namespace testing
namespace {
// Tests the message streaming variation of assertions.
TEST(AssertionWithMessageTest, EXPECT) {
EXPECT_EQ(1, 1) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
"Expected failure #1");
EXPECT_LE(1, 2) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
"Expected failure #2.");
EXPECT_GE(1, 0) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
"Expected failure #3.");
EXPECT_STREQ("1", "1") << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
"Expected failure #4.");
EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
"Expected failure #5.");
EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
"Expected failure #6.");
EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
}
TEST(AssertionWithMessageTest, ASSERT) {
ASSERT_EQ(1, 1) << "This should succeed.";
ASSERT_NE(1, 2) << "This should succeed.";
ASSERT_LE(1, 2) << "This should succeed.";
ASSERT_LT(1, 2) << "This should succeed.";
ASSERT_GE(1, 0) << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
"Expected failure.");
}
TEST(AssertionWithMessageTest, ASSERT_STR) {
ASSERT_STREQ("1", "1") << "This should succeed.";
ASSERT_STRNE("1", "2") << "This should succeed.";
ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
"Expected failure.");
}
TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
"Expect failure.");
}
// Tests using ASSERT_FALSE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_FALSE) {
ASSERT_FALSE(false) << "This shouldn't fail.";
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
<< " evaluates to " << true;
}, "Expected failure");
}
// Tests using FAIL with a streamed message.
TEST(AssertionWithMessageTest, FAIL) {
EXPECT_FATAL_FAILURE(FAIL() << 0,
"0");
}
// Tests using SUCCEED with a streamed message.
TEST(AssertionWithMessageTest, SUCCEED) {
SUCCEED() << "Success == " << 1;
}
// Tests using ASSERT_TRUE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_TRUE) {
ASSERT_TRUE(true) << "This should succeed.";
ASSERT_TRUE(true) << true;
EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
<< static_cast<char*>(nullptr);
},
"(null)(null)");
}
#if GTEST_OS_WINDOWS
// Tests using wide strings in assertion messages.
TEST(AssertionWithMessageTest, WideStringMessage) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_TRUE(false) << L"This failure is expected.\x8119";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_EQ(1, 2) << "This failure is "
<< L"expected too.\x8120";
}, "This failure is expected too.");
}
#endif // GTEST_OS_WINDOWS
// Tests EXPECT_TRUE.
TEST(ExpectTest, EXPECT_TRUE) {
EXPECT_TRUE(true) << "Intentional success";
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
"Intentional failure #1.");
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
"Intentional failure #2.");
EXPECT_TRUE(2 > 1); // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
"Value of: 2 < 1\n"
" Actual: false\n"
"Expected: true");
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
"2 > 3");
}
// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectTrueWithAssertionResult) {
EXPECT_TRUE(ResultIsEven(2));
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
"Value of: ResultIsEven(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
EXPECT_TRUE(ResultIsEvenNoExplanation(2));
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
"Value of: ResultIsEvenNoExplanation(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
}
// Tests EXPECT_FALSE with a streamed message.
TEST(ExpectTest, EXPECT_FALSE) {
EXPECT_FALSE(2 < 1); // NOLINT
EXPECT_FALSE(false) << "Intentional success";
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
"Intentional failure #1.");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
"Intentional failure #2.");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
"Value of: 2 > 1\n"
" Actual: true\n"
"Expected: false");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
"2 < 3");
}
// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectFalseWithAssertionResult) {
EXPECT_FALSE(ResultIsEven(3));
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
"Value of: ResultIsEven(2)\n"
" Actual: true (2 is even)\n"
"Expected: false");
EXPECT_FALSE(ResultIsEvenNoExplanation(3));
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
"Value of: ResultIsEvenNoExplanation(2)\n"
" Actual: true\n"
"Expected: false");
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
// Tests EXPECT_EQ.
TEST(ExpectTest, EXPECT_EQ) {
EXPECT_EQ(5, 2 + 3);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
"Expected equality of these values:\n"
" 5\n"
" 2*3\n"
" Which is: 6");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
"2 - 3");
}
// Tests using EXPECT_EQ on double values. The purpose is to make
// sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments.
TEST(ExpectTest, EXPECT_EQ_Double) {
// A success.
EXPECT_EQ(5.6, 5.6);
// A failure.
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
"5.1");
}
// Tests EXPECT_EQ(NULL, pointer).
TEST(ExpectTest, EXPECT_EQ_NULL) {
// A success.
const char* p = nullptr;
EXPECT_EQ(nullptr, p);
// A failure.
int n = 0;
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
}
// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
// treated as a null pointer by the compiler, we need to make sure
// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, EXPECT_EQ_0) {
int n = 0;
// A success.
EXPECT_EQ(0, n);
// A failure.
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
" 0\n 5.6");
}
// Tests EXPECT_NE.
TEST(ExpectTest, EXPECT_NE) {
EXPECT_NE(6, 7);
EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
"Expected: ('a') != ('a'), "
"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
"2");
char* const p0 = nullptr;
EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
"p0");
// Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does
// a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT
char* const p1 = reinterpret_cast<char*>(pv1);
EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
"p1");
}
// Tests EXPECT_LE.
TEST(ExpectTest, EXPECT_LE) {
EXPECT_LE(2, 3);
EXPECT_LE(2, 2);
EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
"Expected: (2) <= (0), actual: 2 vs 0");
EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
"(1.1) <= (0.9)");
}
// Tests EXPECT_LT.
TEST(ExpectTest, EXPECT_LT) {
EXPECT_LT(2, 3);
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
"Expected: (2) < (2), actual: 2 vs 2");
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
"(2) < (1)");
}
// Tests EXPECT_GE.
TEST(ExpectTest, EXPECT_GE) {
EXPECT_GE(2, 1);
EXPECT_GE(2, 2);
EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
"Expected: (2) >= (3), actual: 2 vs 3");
EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
"(0.9) >= (1.1)");
}
// Tests EXPECT_GT.
TEST(ExpectTest, EXPECT_GT) {
EXPECT_GT(2, 1);
EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
"Expected: (2) > (2), actual: 2 vs 2");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
"(2) > (3)");
}
#if GTEST_HAS_EXCEPTIONS
// Tests EXPECT_THROW.
TEST(ExpectTest, EXPECT_THROW) {
EXPECT_THROW(ThrowAnInteger(), int);
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of "
"type bool.\n Actual: it throws a different type.");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
std::logic_error),
"Expected: ThrowRuntimeError(\"A description\") "
"throws an exception of type std::logic_error.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing.");
}
// Tests EXPECT_NO_THROW.
TEST(ExpectTest, EXPECT_NO_THROW) {
EXPECT_NO_THROW(ThrowNothing());
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an "
"exception.\n Actual: it throws.");
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
}
// Tests EXPECT_ANY_THROW.
TEST(ExpectTest, EXPECT_ANY_THROW) {
EXPECT_ANY_THROW(ThrowAnInteger());
EXPECT_NONFATAL_FAILURE(
EXPECT_ANY_THROW(ThrowNothing()),
"Expected: ThrowNothing() throws an exception.\n"
" Actual: it doesn't.");
}
#endif // GTEST_HAS_EXCEPTIONS
// Make sure we deal with the precedence of <<.
TEST(ExpectTest, ExpectPrecedence) {
EXPECT_EQ(1 < 2, true);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
" true && false\n Which is: false");
}
// Tests the StreamableToString() function.
// Tests using StreamableToString() on a scalar.
TEST(StreamableToStringTest, Scalar) {
EXPECT_STREQ("5", StreamableToString(5).c_str());
}
// Tests using StreamableToString() on a non-char pointer.
TEST(StreamableToStringTest, Pointer) {
int n = 0;
int* p = &n;
EXPECT_STRNE("(null)", StreamableToString(p).c_str());
}
// Tests using StreamableToString() on a NULL non-char pointer.
TEST(StreamableToStringTest, NullPointer) {
int* p = nullptr;
EXPECT_STREQ("(null)", StreamableToString(p).c_str());
}
// Tests using StreamableToString() on a C string.
TEST(StreamableToStringTest, CString) {
EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
}
// Tests using StreamableToString() on a NULL C string.
TEST(StreamableToStringTest, NullCString) {
char* p = nullptr;
EXPECT_STREQ("(null)", StreamableToString(p).c_str());
}
// Tests using streamable values as assertion messages.
// Tests using std::string as an assertion message.
TEST(StreamableTest, string) {
static const std::string str(
"This failure message is a std::string, and is expected.");
EXPECT_FATAL_FAILURE(FAIL() << str,
str.c_str());
}
// Tests that we can output strings containing embedded NULs.
// Limited to Linux because we can only do this with std::string's.
TEST(StreamableTest, stringWithEmbeddedNUL) {
static const char char_array_with_nul[] =
"Here's a NUL\0 and some more string";
static const std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul)
- 1); // drops the trailing NUL
EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
"Here's a NUL\\0 and some more string");
}
// Tests that we can output a NUL char.
TEST(StreamableTest, NULChar) {
EXPECT_FATAL_FAILURE({ // NOLINT
FAIL() << "A NUL" << '\0' << " and some more string";
}, "A NUL\\0 and some more string");
}
// Tests using int as an assertion message.
TEST(StreamableTest, int) {
EXPECT_FATAL_FAILURE(FAIL() << 900913,
"900913");
}
// Tests using NULL char pointer as an assertion message.
//
// In MSVC, streaming a NULL char * causes access violation. Google Test
// implemented a workaround (substituting "(null)" for NULL). This
// tests whether the workaround works.
TEST(StreamableTest, NullCharPtr) {
EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
}
// Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to testing::Message.
TEST(StreamableTest, BasicIoManip) {
EXPECT_FATAL_FAILURE({ // NOLINT
FAIL() << "Line 1." << std::endl
<< "A NUL char " << std::ends << std::flush << " in line 2.";
}, "Line 1.\nA NUL char \\0 in line 2.");
}
// Tests the macros that haven't been covered so far.
void AddFailureHelper(bool* aborted) {
*aborted = true;
ADD_FAILURE() << "Intentional failure.";
*aborted = false;
}
// Tests ADD_FAILURE.
TEST(MacroTest, ADD_FAILURE) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
"Intentional failure.");
EXPECT_FALSE(aborted);
}
// Tests ADD_FAILURE_AT.
TEST(MacroTest, ADD_FAILURE_AT) {
// Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
// the failure message contains the user-streamed part.
EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
// Verifies that the user-streamed part is optional.
EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
// Unfortunately, we cannot verify that the failure message contains
// the right file path and line number the same way, as
// EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
// line number. Instead, we do that in googletest-output-test_.cc.
}
// Tests FAIL.
TEST(MacroTest, FAIL) {
EXPECT_FATAL_FAILURE(FAIL(),
"Failed");
EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
"Intentional failure.");
}
// Tests GTEST_FAIL_AT.
TEST(MacroTest, GTEST_FAIL_AT) {
// Verifies that GTEST_FAIL_AT does generate a fatal failure and
// the failure message contains the user-streamed part.
EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
// Verifies that the user-streamed part is optional.
EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
// See the ADD_FAIL_AT test above to see how we test that the failure message
// contains the right filename and line number -- the same applies here.
}
// Tests SUCCEED
TEST(MacroTest, SUCCEED) {
SUCCEED();
SUCCEED() << "Explicit success.";
}
// Tests for EXPECT_EQ() and ASSERT_EQ().
//
// These tests fail *intentionally*, s.t. the failure messages can be
// generated and tested.
//
// We have different tests for different argument types.
// Tests using bool values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Bool) {
EXPECT_EQ(true, true);
EXPECT_FATAL_FAILURE({
bool false_value = false;
ASSERT_EQ(false_value, true);
}, " false_value\n Which is: false\n true");
}
// Tests using int values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Int) {
ASSERT_EQ(32, 32);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
" 32\n 33");
}
// Tests using time_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Time_T) {
EXPECT_EQ(static_cast<time_t>(0),
static_cast<time_t>(0));
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
static_cast<time_t>(1234)),
"1234");
}
// Tests using char values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Char) {
ASSERT_EQ('z', 'z');
const char ch = 'b';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
" ch\n Which is: 'b'");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
" ch\n Which is: 'b'");
}
// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideChar) {
EXPECT_EQ(L'b', L'b');
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
"Expected equality of these values:\n"
" L'\0'\n"
" Which is: L'\0' (0, 0x0)\n"
" L'x'\n"
" Which is: L'x' (120, 0x78)");
static wchar_t wchar;
wchar = L'b';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
"wchar");
wchar = 0x8119;
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
" wchar\n Which is: L'");
}
// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdString) {
// Compares a const char* to an std::string that has identical
// content.
ASSERT_EQ("Test", ::std::string("Test"));
// Compares two identical std::strings.
static const ::std::string str1("A * in the middle");
static const ::std::string str2(str1);
EXPECT_EQ(str1, str2);
// Compares a const char* to an std::string that has different
// content
EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
"\"test\"");
// Compares an std::string to a char* that has different content.
char* const p1 = const_cast<char*>("foo");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
"p1");
// Compares two std::strings that have different contents, one of
// which having a NUL character in the middle. This should fail.
static ::std::string str3(str1);
str3.at(2) = '\0';
EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
" str3\n Which is: \"A \\0 in the middle\"");
}
#if GTEST_HAS_STD_WSTRING
// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdWideString) {
// Compares two identical std::wstrings.
const ::std::wstring wstr1(L"A * in the middle");
const ::std::wstring wstr2(wstr1);
ASSERT_EQ(wstr1, wstr2);
// Compares an std::wstring to a const wchar_t* that has identical
// content.
const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
// Compares an std::wstring to a const wchar_t* that has different
// content.
const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
}, "kTestX8120");
// Compares two std::wstrings that have different contents, one of
// which having a NUL character in the middle.
::std::wstring wstr3(wstr1);
wstr3.at(2) = L'\0';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
"wstr3");
// Compares a wchar_t* to an std::wstring that has different
// content.
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
}, "");
}
#endif // GTEST_HAS_STD_WSTRING
// Tests using char pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, CharPointer) {
char* const p0 = nullptr;
// Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does
// a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT
void* pv2 = (void*)0xABC0; // NOLINT
char* const p1 = reinterpret_cast<char*>(pv1);
char* const p2 = reinterpret_cast<char*>(pv2);
ASSERT_EQ(p1, p1);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
" p2\n Which is:");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
" p2\n Which is:");
EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
reinterpret_cast<char*>(0xABC0)),
"ABC0");
}
// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideCharPointer) {
wchar_t* const p0 = nullptr;
// Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does
// a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT
void* pv2 = (void*)0xABC0; // NOLINT
wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
EXPECT_EQ(p0, p0);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
" p2\n Which is:");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
" p2\n Which is:");
void* pv3 = (void*)0x1234; // NOLINT
void* pv4 = (void*)0xABC0; // NOLINT
const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
"p4");
}
// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, OtherPointer) {
ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
reinterpret_cast<const int*>(0x1234)),
"0x1234");
}
// A class that supports binary comparison operators but not streaming.
class UnprintableChar {
public:
explicit UnprintableChar(char ch) : char_(ch) {}
bool operator==(const UnprintableChar& rhs) const {
return char_ == rhs.char_;
}
bool operator!=(const UnprintableChar& rhs) const {
return char_ != rhs.char_;
}
bool operator<(const UnprintableChar& rhs) const {
return char_ < rhs.char_;
}
bool operator<=(const UnprintableChar& rhs) const {
return char_ <= rhs.char_;
}
bool operator>(const UnprintableChar& rhs) const {
return char_ > rhs.char_;
}
bool operator>=(const UnprintableChar& rhs) const {
return char_ >= rhs.char_;
}
private:
char char_;
};
// Tests that ASSERT_EQ() and friends don't require the arguments to
// be printable.
TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
const UnprintableChar x('x'), y('y');
ASSERT_EQ(x, x);
EXPECT_NE(x, y);
ASSERT_LT(x, y);
EXPECT_LE(x, y);
ASSERT_GT(y, x);
EXPECT_GE(x, x);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
// Code tested by EXPECT_FATAL_FAILURE cannot reference local
// variables, so we have to write UnprintableChar('x') instead of x.
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
"1-byte object <78>");
EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
"1-byte object <78>");
#endif
EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
"1-byte object <79>");
EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
"1-byte object <78>");
EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
"1-byte object <79>");
}
// Tests the FRIEND_TEST macro.
// This class has a private member we want to test. We will test it
// both in a TEST and in a TEST_F.
class Foo {
public:
Foo() {}
private:
int Bar() const { return 1; }
// Declares the friend tests that can access the private member
// Bar().
FRIEND_TEST(FRIEND_TEST_Test, TEST);
FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
};
// Tests that the FRIEND_TEST declaration allows a TEST to access a
// class's private members. This should compile.
TEST(FRIEND_TEST_Test, TEST) {
ASSERT_EQ(1, Foo().Bar());
}
// The fixture needed to test using FRIEND_TEST with TEST_F.
class FRIEND_TEST_Test2 : public Test {
protected:
Foo foo;
};
// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
// class's private members. This should compile.
TEST_F(FRIEND_TEST_Test2, TEST_F) {
ASSERT_EQ(1, foo.Bar());
}
// Tests the life cycle of Test objects.
// The test fixture for testing the life cycle of Test objects.
//
// This class counts the number of live test objects that uses this
// fixture.
class TestLifeCycleTest : public Test {
protected:
// Constructor. Increments the number of test objects that uses
// this fixture.
TestLifeCycleTest() { count_++; }
// Destructor. Decrements the number of test objects that uses this
// fixture.
~TestLifeCycleTest() override { count_--; }
// Returns the number of live test objects that uses this fixture.
int count() const { return count_; }
private:
static int count_;
};
int TestLifeCycleTest::count_ = 0;
// Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest, Test1) {
// There should be only one test object in this test case that's
// currently alive.
ASSERT_EQ(1, count());
}
// Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest, Test2) {
// After Test1 is done and Test2 is started, there should still be
// only one live test object, as the object for Test1 should've been
// deleted.
ASSERT_EQ(1, count());
}
} // namespace
// Tests that the copy constructor works when it is NOT optimized away by
// the compiler.
TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
// Checks that the copy constructor doesn't try to dereference NULL pointers
// in the source object.
AssertionResult r1 = AssertionSuccess();
AssertionResult r2 = r1;
// The following line is added to prevent the compiler from optimizing
// away the constructor call.
r1 << "abc";
AssertionResult r3 = r1;
EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
EXPECT_STREQ("abc", r1.message());
}
// Tests that AssertionSuccess and AssertionFailure construct
// AssertionResult objects as expected.
TEST(AssertionResultTest, ConstructionWorks) {
AssertionResult r1 = AssertionSuccess();
EXPECT_TRUE(r1);
EXPECT_STREQ("", r1.message());
AssertionResult r2 = AssertionSuccess() << "abc";
EXPECT_TRUE(r2);
EXPECT_STREQ("abc", r2.message());
AssertionResult r3 = AssertionFailure();
EXPECT_FALSE(r3);
EXPECT_STREQ("", r3.message());
AssertionResult r4 = AssertionFailure() << "def";
EXPECT_FALSE(r4);
EXPECT_STREQ("def", r4.message());
AssertionResult r5 = AssertionFailure(Message() << "ghi");
EXPECT_FALSE(r5);
EXPECT_STREQ("ghi", r5.message());
}
// Tests that the negation flips the predicate result but keeps the message.
TEST(AssertionResultTest, NegationWorks) {
AssertionResult r1 = AssertionSuccess() << "abc";
EXPECT_FALSE(!r1);
EXPECT_STREQ("abc", (!r1).message());
AssertionResult r2 = AssertionFailure() << "def";
EXPECT_TRUE(!r2);
EXPECT_STREQ("def", (!r2).message());
}
TEST(AssertionResultTest, StreamingWorks) {
AssertionResult r = AssertionSuccess();
r << "abc" << 'd' << 0 << true;
EXPECT_STREQ("abcd0true", r.message());
}
TEST(AssertionResultTest, CanStreamOstreamManipulators) {
AssertionResult r = AssertionSuccess();
r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
EXPECT_STREQ("Data\n\\0Will be visible", r.message());
}
// The next test uses explicit conversion operators
TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
struct ExplicitlyConvertibleToBool {
explicit operator bool() const { return value; }
bool value;
};
ExplicitlyConvertibleToBool v1 = {false};
ExplicitlyConvertibleToBool v2 = {true};
EXPECT_FALSE(v1);
EXPECT_TRUE(v2);
}
struct ConvertibleToAssertionResult {
operator AssertionResult() const { return AssertionResult(true); }
};
TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
ConvertibleToAssertionResult obj;
EXPECT_TRUE(obj);
}
// Tests streaming a user type whose definition and operator << are
// both in the global namespace.
class Base {
public:
explicit Base(int an_x) : x_(an_x) {}
int x() const { return x_; }
private:
int x_;
};
std::ostream& operator<<(std::ostream& os,
const Base& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const Base* pointer) {
return os << "(" << pointer->x() << ")";
}
TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
Message msg;
Base a(1);
msg << a << &a; // Uses ::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming a user type whose definition and operator<< are
// both in an unnamed namespace.
namespace {
class MyTypeInUnnamedNameSpace : public Base {
public:
explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
};
std::ostream& operator<<(std::ostream& os,
const MyTypeInUnnamedNameSpace& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const MyTypeInUnnamedNameSpace* pointer) {
return os << "(" << pointer->x() << ")";
}
} // namespace
TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
Message msg;
MyTypeInUnnamedNameSpace a(1);
msg << a << &a; // Uses <unnamed_namespace>::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming a user type whose definition and operator<< are
// both in a user namespace.
namespace namespace1 {
class MyTypeInNameSpace1 : public Base {
public:
explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
};
std::ostream& operator<<(std::ostream& os,
const MyTypeInNameSpace1& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const MyTypeInNameSpace1* pointer) {
return os << "(" << pointer->x() << ")";
}
} // namespace namespace1
TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
Message msg;
namespace1::MyTypeInNameSpace1 a(1);
msg << a << &a; // Uses namespace1::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming a user type whose definition is in a user namespace
// but whose operator<< is in the global namespace.
namespace namespace2 {
class MyTypeInNameSpace2 : public ::Base {
public:
explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
};
} // namespace namespace2
std::ostream& operator<<(std::ostream& os,
const namespace2::MyTypeInNameSpace2& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const namespace2::MyTypeInNameSpace2* pointer) {
return os << "(" << pointer->x() << ")";
}
TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
Message msg;
namespace2::MyTypeInNameSpace2 a(1);
msg << a << &a; // Uses ::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming NULL pointers to testing::Message.
TEST(MessageTest, NullPointers) {
Message msg;
char* const p1 = nullptr;
unsigned char* const p2 = nullptr;
int* p3 = nullptr;
double* p4 = nullptr;
bool* p5 = nullptr;
Message* p6 = nullptr;
msg << p1 << p2 << p3 << p4 << p5 << p6;
ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
msg.GetString().c_str());
}
// Tests streaming wide strings to testing::Message.
TEST(MessageTest, WideStrings) {
// Streams a NULL of type const wchar_t*.
const wchar_t* const_wstr = nullptr;
EXPECT_STREQ("(null)",
(Message() << const_wstr).GetString().c_str());
// Streams a NULL of type wchar_t*.
wchar_t* wstr = nullptr;
EXPECT_STREQ("(null)",
(Message() << wstr).GetString().c_str());
// Streams a non-NULL of type const wchar_t*.
const_wstr = L"abc\x8119";
EXPECT_STREQ("abc\xe8\x84\x99",
(Message() << const_wstr).GetString().c_str());
// Streams a non-NULL of type wchar_t*.
wstr = const_cast<wchar_t*>(const_wstr);
EXPECT_STREQ("abc\xe8\x84\x99",
(Message() << wstr).GetString().c_str());
}
// This line tests that we can define tests in the testing namespace.
namespace testing {
// Tests the TestInfo class.
class TestInfoTest : public Test {
protected:
static const TestInfo* GetTestInfo(const char* test_name) {
const TestSuite* const test_suite =
GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
for (int i = 0; i < test_suite->total_test_count(); ++i) {
const TestInfo* const test_info = test_suite->GetTestInfo(i);
if (strcmp(test_name, test_info->name()) == 0)
return test_info;
}
return nullptr;
}
static const TestResult* GetTestResult(
const TestInfo* test_info) {
return test_info->result();
}
};
// Tests TestInfo::test_case_name() and TestInfo::name().
TEST_F(TestInfoTest, Names) {
const TestInfo* const test_info = GetTestInfo("Names");
ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
ASSERT_STREQ("Names", test_info->name());
}
// Tests TestInfo::result().
TEST_F(TestInfoTest, result) {
const TestInfo* const test_info = GetTestInfo("result");
// Initially, there is no TestPartResult for this test.
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
// After the previous assertion, there is still none.
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
}
#define VERIFY_CODE_LOCATION \
const int expected_line = __LINE__ - 1; \
const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
ASSERT_TRUE(test_info); \
EXPECT_STREQ(__FILE__, test_info->file()); \
EXPECT_EQ(expected_line, test_info->line())
TEST(CodeLocationForTEST, Verify) {
VERIFY_CODE_LOCATION;
}
class CodeLocationForTESTF : public Test {
};
TEST_F(CodeLocationForTESTF, Verify) {
VERIFY_CODE_LOCATION;
}
class CodeLocationForTESTP : public TestWithParam<int> {
};
TEST_P(CodeLocationForTESTP, Verify) {
VERIFY_CODE_LOCATION;
}
INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
template <typename T>
class CodeLocationForTYPEDTEST : public Test {
};
TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
VERIFY_CODE_LOCATION;
}
template <typename T>
class CodeLocationForTYPEDTESTP : public Test {
};
TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
VERIFY_CODE_LOCATION;
}
REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
#undef VERIFY_CODE_LOCATION
// Tests setting up and tearing down a test case.
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
class SetUpTestCaseTest : public Test {
protected:
// This will be called once before the first test in this test case
// is run.
static void SetUpTestCase() {
printf("Setting up the test case . . .\n");
// Initializes some shared resource. In this simple example, we
// just create a C string. More complex stuff can be done if
// desired.
shared_resource_ = "123";
// Increments the number of test cases that have been set up.
counter_++;
// SetUpTestCase() should be called only once.
EXPECT_EQ(1, counter_);
}
// This will be called once after the last test in this test case is
// run.
static void TearDownTestCase() {
printf("Tearing down the test case . . .\n");
// Decrements the number of test cases that have been set up.
counter_--;
// TearDownTestCase() should be called only once.
EXPECT_EQ(0, counter_);
// Cleans up the shared resource.
shared_resource_ = nullptr;
}
// This will be called before each test in this test case.
void SetUp() override {
// SetUpTestCase() should be called only once, so counter_ should
// always be 1.
EXPECT_EQ(1, counter_);
}
// Number of test cases that have been set up.
static int counter_;
// Some resource to be shared by all tests in this test case.
static const char* shared_resource_;
};
int SetUpTestCaseTest::counter_ = 0;
const char* SetUpTestCaseTest::shared_resource_ = nullptr;
// A test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
// Another test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test2) {
EXPECT_STREQ("123", shared_resource_);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Tests SetupTestSuite/TearDown TestSuite
class SetUpTestSuiteTest : public Test {
protected:
// This will be called once before the first test in this test case
// is run.
static void SetUpTestSuite() {
printf("Setting up the test suite . . .\n");
// Initializes some shared resource. In this simple example, we
// just create a C string. More complex stuff can be done if
// desired.
shared_resource_ = "123";
// Increments the number of test cases that have been set up.
counter_++;
// SetUpTestSuite() should be called only once.
EXPECT_EQ(1, counter_);
}
// This will be called once after the last test in this test case is
// run.
static void TearDownTestSuite() {
printf("Tearing down the test suite . . .\n");
// Decrements the number of test suites that have been set up.
counter_--;
// TearDownTestSuite() should be called only once.
EXPECT_EQ(0, counter_);
// Cleans up the shared resource.
shared_resource_ = nullptr;
}
// This will be called before each test in this test case.
void SetUp() override {
// SetUpTestSuite() should be called only once, so counter_ should
// always be 1.
EXPECT_EQ(1, counter_);
}
// Number of test suites that have been set up.
static int counter_;
// Some resource to be shared by all tests in this test case.
static const char* shared_resource_;
};
int SetUpTestSuiteTest::counter_ = 0;
const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
// A test that uses the shared resource.
TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
EXPECT_STRNE(nullptr, shared_resource_);
}
// Another test that uses the shared resource.
TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
EXPECT_STREQ("123", shared_resource_);
}
// The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
// The Flags struct stores a copy of all Google Test flags.
struct Flags {
// Constructs a Flags struct where each flag has its default value.
Flags()
: also_run_disabled_tests(false),
break_on_failure(false),
catch_exceptions(false),
death_test_use_fork(false),
fail_fast(false),
filter(""),
list_tests(false),
output(""),
brief(false),
print_time(true),
random_seed(0),
repeat(1),
recreate_environments_when_repeating(true),
shuffle(false),
stack_trace_depth(kMaxStackTraceDepth),
stream_result_to(""),
throw_on_failure(false) {}
// Factory methods.
// Creates a Flags struct where the gtest_also_run_disabled_tests flag has
// the given value.
static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
Flags flags;
flags.also_run_disabled_tests = also_run_disabled_tests;
return flags;
}
// Creates a Flags struct where the gtest_break_on_failure flag has
// the given value.
static Flags BreakOnFailure(bool break_on_failure) {
Flags flags;
flags.break_on_failure = break_on_failure;
return flags;
}
// Creates a Flags struct where the gtest_catch_exceptions flag has
// the given value.
static Flags CatchExceptions(bool catch_exceptions) {
Flags flags;
flags.catch_exceptions = catch_exceptions;
return flags;
}
// Creates a Flags struct where the gtest_death_test_use_fork flag has
// the given value.
static Flags DeathTestUseFork(bool death_test_use_fork) {
Flags flags;
flags.death_test_use_fork = death_test_use_fork;
return flags;
}
// Creates a Flags struct where the gtest_fail_fast flag has
// the given value.
static Flags FailFast(bool fail_fast) {
Flags flags;
flags.fail_fast = fail_fast;
return flags;
}
// Creates a Flags struct where the gtest_filter flag has the given
// value.
static Flags Filter(const char* filter) {
Flags flags;
flags.filter = filter;
return flags;
}
// Creates a Flags struct where the gtest_list_tests flag has the
// given value.
static Flags ListTests(bool list_tests) {
Flags flags;
flags.list_tests = list_tests;
return flags;
}
// Creates a Flags struct where the gtest_output flag has the given
// value.
static Flags Output(const char* output) {
Flags flags;
flags.output = output;
return flags;
}
// Creates a Flags struct where the gtest_brief flag has the given
// value.
static Flags Brief(bool brief) {
Flags flags;
flags.brief = brief;
return flags;
}
// Creates a Flags struct where the gtest_print_time flag has the given
// value.
static Flags PrintTime(bool print_time) {
Flags flags;
flags.print_time = print_time;
return flags;
}
// Creates a Flags struct where the gtest_random_seed flag has the given
// value.
static Flags RandomSeed(int32_t random_seed) {
Flags flags;
flags.random_seed = random_seed;
return flags;
}
// Creates a Flags struct where the gtest_repeat flag has the given
// value.
static Flags Repeat(int32_t repeat) {
Flags flags;
flags.repeat = repeat;
return flags;
}
// Creates a Flags struct where the gtest_recreate_environments_when_repeating
// flag has the given value.
static Flags RecreateEnvironmentsWhenRepeating(
bool recreate_environments_when_repeating) {
Flags flags;
flags.recreate_environments_when_repeating =
recreate_environments_when_repeating;
return flags;
}
// Creates a Flags struct where the gtest_shuffle flag has the given
// value.
static Flags Shuffle(bool shuffle) {
Flags flags;
flags.shuffle = shuffle;
return flags;
}
// Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
// the given value.
static Flags StackTraceDepth(int32_t stack_trace_depth) {
Flags flags;
flags.stack_trace_depth = stack_trace_depth;
return flags;
}
// Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
// the given value.
static Flags StreamResultTo(const char* stream_result_to) {
Flags flags;
flags.stream_result_to = stream_result_to;
return flags;
}
// Creates a Flags struct where the gtest_throw_on_failure flag has
// the given value.
static Flags ThrowOnFailure(bool throw_on_failure) {
Flags flags;
flags.throw_on_failure = throw_on_failure;
return flags;
}
// These fields store the flag values.
bool also_run_disabled_tests;
bool break_on_failure;
bool catch_exceptions;
bool death_test_use_fork;
bool fail_fast;
const char* filter;
bool list_tests;
const char* output;
bool brief;
bool print_time;
int32_t random_seed;
int32_t repeat;
bool recreate_environments_when_repeating;
bool shuffle;
int32_t stack_trace_depth;
const char* stream_result_to;
bool throw_on_failure;
};
// Fixture for testing ParseGoogleTestFlagsOnly().
class ParseFlagsTest : public Test {
protected:
// Clears the flags before each test.
void SetUp() override {
GTEST_FLAG_SET(also_run_disabled_tests, false);
GTEST_FLAG_SET(break_on_failure, false);
GTEST_FLAG_SET(catch_exceptions, false);
GTEST_FLAG_SET(death_test_use_fork, false);
GTEST_FLAG_SET(fail_fast, false);
GTEST_FLAG_SET(filter, "");
GTEST_FLAG_SET(list_tests, false);
GTEST_FLAG_SET(output, "");
GTEST_FLAG_SET(brief, false);
GTEST_FLAG_SET(print_time, true);
GTEST_FLAG_SET(random_seed, 0);
GTEST_FLAG_SET(repeat, 1);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(shuffle, false);
GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
GTEST_FLAG_SET(stream_result_to, "");
GTEST_FLAG_SET(throw_on_failure, false);
}
// Asserts that two narrow or wide string arrays are equal.
template <typename CharType>
static void AssertStringArrayEq(int size1, CharType** array1, int size2,
CharType** array2) {
ASSERT_EQ(size1, size2) << " Array sizes different.";
for (int i = 0; i != size1; i++) {
ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
}
}
// Verifies that the flag values match the expected values.
static void CheckFlags(const Flags& expected) {
EXPECT_EQ(expected.also_run_disabled_tests,
GTEST_FLAG_GET(also_run_disabled_tests));
EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
EXPECT_EQ(expected.death_test_use_fork,
GTEST_FLAG_GET(death_test_use_fork));
EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
EXPECT_EQ(expected.recreate_environments_when_repeating,
GTEST_FLAG_GET(recreate_environments_when_repeating));
EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
EXPECT_STREQ(expected.stream_result_to,
GTEST_FLAG_GET(stream_result_to).c_str());
EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
}
// Parses a command line (specified by argc1 and argv1), then
// verifies that the flag values are expected and that the
// recognized flags are removed from the command line.
template <typename CharType>
static void TestParsingFlags(int argc1, const CharType** argv1,
int argc2, const CharType** argv2,
const Flags& expected, bool should_print_help) {
const bool saved_help_flag = ::testing::internal::g_help_flag;
::testing::internal::g_help_flag = false;
# if GTEST_HAS_STREAM_REDIRECTION
CaptureStdout();
# endif
// Parses the command line.
internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
# if GTEST_HAS_STREAM_REDIRECTION
const std::string captured_stdout = GetCapturedStdout();
# endif
// Verifies the flag values.
CheckFlags(expected);
// Verifies that the recognized flags are removed from the command
// line.
AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
// ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
// help message for the flags it recognizes.
EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
# if GTEST_HAS_STREAM_REDIRECTION
const char* const expected_help_fragment =
"This program contains tests written using";
if (should_print_help) {
EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
} else {
EXPECT_PRED_FORMAT2(IsNotSubstring,
expected_help_fragment, captured_stdout);
}
# endif // GTEST_HAS_STREAM_REDIRECTION
::testing::internal::g_help_flag = saved_help_flag;
}
// This macro wraps TestParsingFlags s.t. the user doesn't need
// to specify the array sizes.
# define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
expected, should_print_help)
};
// Tests parsing an empty command line.
TEST_F(ParseFlagsTest, Empty) {
const char* argv[] = {nullptr};
const char* argv2[] = {nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
// Tests parsing a command line that has no flag.
TEST_F(ParseFlagsTest, NoFlag) {
const char* argv[] = {"foo.exe", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
// Tests parsing --gtest_fail_fast.
TEST_F(ParseFlagsTest, FailFast) {
const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
}
// Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterBad) {
const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
}
// Tests parsing an empty --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterEmpty) {
const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
}
// Tests parsing a non-empty --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterNonEmpty) {
const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
}
// Tests parsing --gtest_break_on_failure.
TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
}
// Tests parsing --gtest_break_on_failure=0.
TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
}
// Tests parsing --gtest_break_on_failure=f.
TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
}
// Tests parsing --gtest_break_on_failure=F.
TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
}
// Tests parsing a --gtest_break_on_failure flag that has a "true"
// definition.
TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
}
// Tests parsing --gtest_catch_exceptions.
TEST_F(ParseFlagsTest, CatchExceptions) {
const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
}
// Tests parsing --gtest_death_test_use_fork.
TEST_F(ParseFlagsTest, DeathTestUseFork) {
const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
}
// Tests having the same flag twice with different values. The
// expected behavior is that the one coming last takes precedence.
TEST_F(ParseFlagsTest, DuplicatedFlags) {
const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
}
// Tests having an unrecognized flag on the command line.
TEST_F(ParseFlagsTest, UnrecognizedFlag) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
"bar", // Unrecognized by Google Test.
"--gtest_filter=b", nullptr};
const char* argv2[] = {"foo.exe", "bar", nullptr};
Flags flags;
flags.break_on_failure = true;
flags.filter = "b";
GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
}
// Tests having a --gtest_list_tests flag
TEST_F(ParseFlagsTest, ListTestsFlag) {
const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
}
// Tests having a --gtest_list_tests flag with a "true" value
TEST_F(ParseFlagsTest, ListTestsTrue) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
}
// Tests having a --gtest_list_tests flag with a "false" value
TEST_F(ParseFlagsTest, ListTestsFalse) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
}
// Tests parsing --gtest_list_tests=f.
TEST_F(ParseFlagsTest, ListTestsFalse_f) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
}
// Tests parsing --gtest_list_tests=F.
TEST_F(ParseFlagsTest, ListTestsFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
}
// Tests parsing --gtest_output (invalid).
TEST_F(ParseFlagsTest, OutputEmpty) {
const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
}
// Tests parsing --gtest_output=xml
TEST_F(ParseFlagsTest, OutputXml) {
const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
}
// Tests parsing --gtest_output=xml:file
TEST_F(ParseFlagsTest, OutputXmlFile) {
const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
}
// Tests parsing --gtest_output=xml:directory/path/
TEST_F(ParseFlagsTest, OutputXmlDirectory) {
const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2,
Flags::Output("xml:directory/path/"), false);
}
// Tests having a --gtest_brief flag
TEST_F(ParseFlagsTest, BriefFlag) {
const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
}
// Tests having a --gtest_brief flag with a "true" value
TEST_F(ParseFlagsTest, BriefFlagTrue) {
const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
}
// Tests having a --gtest_brief flag with a "false" value
TEST_F(ParseFlagsTest, BriefFlagFalse) {
const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
}
// Tests having a --gtest_print_time flag
TEST_F(ParseFlagsTest, PrintTimeFlag) {
const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
}
// Tests having a --gtest_print_time flag with a "true" value
TEST_F(ParseFlagsTest, PrintTimeTrue) {
const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
}
// Tests having a --gtest_print_time flag with a "false" value
TEST_F(ParseFlagsTest, PrintTimeFalse) {
const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
}
// Tests parsing --gtest_print_time=f.
TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
}
// Tests parsing --gtest_print_time=F.
TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
}
// Tests parsing --gtest_random_seed=number
TEST_F(ParseFlagsTest, RandomSeed) {
const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
}
// Tests parsing --gtest_repeat=number
TEST_F(ParseFlagsTest, Repeat) {
const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
}
// Tests parsing --gtest_recreate_environments_when_repeating
TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
const char* argv[] = {
"foo.exe",
"--gtest_recreate_environments_when_repeating=0",
nullptr,
};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(
argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
}
// Tests having a --gtest_also_run_disabled_tests flag
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
false);
}
// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
false);
}
// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
false);
}
// Tests parsing --gtest_shuffle.
TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
}
// Tests parsing --gtest_shuffle=0.
TEST_F(ParseFlagsTest, ShuffleFalse_0) {
const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
}
// Tests parsing a --gtest_shuffle flag that has a "true" definition.
TEST_F(ParseFlagsTest, ShuffleTrue) {
const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
}
// Tests parsing --gtest_stack_trace_depth=number.
TEST_F(ParseFlagsTest, StackTraceDepth) {
const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
}
TEST_F(ParseFlagsTest, StreamResultTo) {
const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(
argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
}
// Tests parsing --gtest_throw_on_failure.
TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
}
// Tests parsing --gtest_throw_on_failure=0.
TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
}
// Tests parsing a --gtest_throw_on_failure flag that has a "true"
// definition.
TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
}
# if GTEST_OS_WINDOWS
// Tests parsing wide strings.
TEST_F(ParseFlagsTest, WideStrings) {
const wchar_t* argv[] = {
L"foo.exe",
L"--gtest_filter=Foo*",
L"--gtest_list_tests=1",
L"--gtest_break_on_failure",
L"--non_gtest_flag",
NULL
};
const wchar_t* argv2[] = {
L"foo.exe",
L"--non_gtest_flag",
NULL
};
Flags expected_flags;
expected_flags.break_on_failure = true;
expected_flags.filter = "Foo*";
expected_flags.list_tests = true;
GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
}
# endif // GTEST_OS_WINDOWS
#if GTEST_USE_OWN_FLAGFILE_FLAG_
class FlagfileTest : public ParseFlagsTest {
public:
void SetUp() override {
ParseFlagsTest::SetUp();
testdata_path_.Set(internal::FilePath(
testing::TempDir() + internal::GetCurrentExecutableName().string() +
"_flagfile_test"));
testing::internal::posix::RmDir(testdata_path_.c_str());
EXPECT_TRUE(testdata_path_.CreateFolder());
}
void TearDown() override {
testing::internal::posix::RmDir(testdata_path_.c_str());
ParseFlagsTest::TearDown();
}
internal::FilePath CreateFlagfile(const char* contents) {
internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
testdata_path_, internal::FilePath("unique"), "txt"));
FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
fprintf(f, "%s", contents);
fclose(f);
return file_path;
}
private:
internal::FilePath testdata_path_;
};
// Tests an empty flagfile.
TEST_F(FlagfileTest, Empty) {
internal::FilePath flagfile_path(CreateFlagfile(""));
std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
TEST_F(FlagfileTest, FilterNonEmpty) {
internal::FilePath flagfile_path(CreateFlagfile(
"--" GTEST_FLAG_PREFIX_ "filter=abc"));
std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
}
// Tests passing several flags via --gtest_flagfile.
TEST_F(FlagfileTest, SeveralFlags) {
internal::FilePath flagfile_path(CreateFlagfile(
"--" GTEST_FLAG_PREFIX_ "filter=abc\n"
"--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
"--" GTEST_FLAG_PREFIX_ "list_tests"));
std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr};
Flags expected_flags;
expected_flags.break_on_failure = true;
expected_flags.filter = "abc";
expected_flags.list_tests = true;
GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
}
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
// Tests current_test_info() in UnitTest.
class CurrentTestInfoTest : public Test {
protected:
// Tests that current_test_info() returns NULL before the first test in
// the test case is run.
static void SetUpTestSuite() {
// There should be no tests running at this point.
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
EXPECT_TRUE(test_info == nullptr)
<< "There should be no tests running at this point.";
}
// Tests that current_test_info() returns NULL after the last test in
// the test case has run.
static void TearDownTestSuite() {
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
EXPECT_TRUE(test_info == nullptr)
<< "There should be no tests running at this point.";
}
};
// Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one.
TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
<< "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
// Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one. We
// use this test to see that the TestInfo object actually changed from
// the previous invocation.
TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
<< "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
} // namespace testing
// These two lines test that we can define tests in a namespace that
// has the name "testing" and is nested in another namespace.
namespace my_namespace {
namespace testing {
// Makes sure that TEST knows to use ::testing::Test instead of
// ::my_namespace::testing::Test.
class Test {};
// Makes sure that an assertion knows to use ::testing::Message instead of
// ::my_namespace::testing::Message.
class Message {};
// Makes sure that an assertion knows to use
// ::testing::AssertionResult instead of
// ::my_namespace::testing::AssertionResult.
class AssertionResult {};
// Tests that an assertion that should succeed works as expected.
TEST(NestedTestingNamespaceTest, Success) {
EXPECT_EQ(1, 1) << "This shouldn't fail.";
}
// Tests that an assertion that should fail works as expected.
TEST(NestedTestingNamespaceTest, Failure) {
EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
"This failure is expected.");
}
} // namespace testing
} // namespace my_namespace
// Tests that one can call superclass SetUp and TearDown methods--
// that is, that they are not private.
// No tests are based on this fixture; the test "passes" if it compiles
// successfully.
class ProtectedFixtureMethodsTest : public Test {
protected:
void SetUp() override { Test::SetUp(); }
void TearDown() override { Test::TearDown(); }
};
// StreamingAssertionsTest tests the streaming versions of a representative
// sample of assertions.
TEST(StreamingAssertionsTest, Unconditional) {
SUCCEED() << "expected success";
EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
"expected failure");
}
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch
#endif
TEST(StreamingAssertionsTest, Truth) {
EXPECT_TRUE(true) << "unexpected failure";
ASSERT_TRUE(true) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, Truth2) {
EXPECT_FALSE(false) << "unexpected failure";
ASSERT_FALSE(false) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
"expected failure");
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
TEST(StreamingAssertionsTest, IntegerEquals) {
EXPECT_EQ(1, 1) << "unexpected failure";
ASSERT_EQ(1, 1) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, IntegerLessThan) {
EXPECT_LT(1, 2) << "unexpected failure";
ASSERT_LT(1, 2) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringsEqual) {
EXPECT_STREQ("foo", "foo") << "unexpected failure";
ASSERT_STREQ("foo", "foo") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringsNotEqual) {
EXPECT_STRNE("foo", "bar") << "unexpected failure";
ASSERT_STRNE("foo", "bar") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, FloatingPointEquals) {
EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
"expected failure");
}
#if GTEST_HAS_EXCEPTIONS
TEST(StreamingAssertionsTest, Throw) {
EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
"expected failure", "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
"expected failure", "expected failure");
}
TEST(StreamingAssertionsTest, NoThrow) {
EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
"expected failure", "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
"expected failure", "expected failure");
}
TEST(StreamingAssertionsTest, AnyThrow) {
EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
"expected failure", "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
"expected failure", "expected failure");
}
#endif // GTEST_HAS_EXCEPTIONS
// Tests that Google Test correctly decides whether to use colors in the output.
TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
GTEST_FLAG_SET(color, "yes");
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
}
TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
GTEST_FLAG_SET(color, "True");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
GTEST_FLAG_SET(color, "t");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
GTEST_FLAG_SET(color, "1");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
}
TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
GTEST_FLAG_SET(color, "no");
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
}
TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
SetEnv("TERM", "xterm"); // TERM supports colors.
GTEST_FLAG_SET(color, "F");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
GTEST_FLAG_SET(color, "0");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
GTEST_FLAG_SET(color, "unknown");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
}
TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
GTEST_FLAG_SET(color, "auto");
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
}
TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
GTEST_FLAG_SET(color, "auto");
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
// On Windows, we ignore the TERM variable as it's usually not set.
SetEnv("TERM", "dumb");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
#else
// On non-Windows platforms, we rely on TERM to determine if the
// terminal supports colors.
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "emacs"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "vt100"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "screen"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "screen-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "tmux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "tmux-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "linux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "cygwin"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
#endif // GTEST_OS_WINDOWS
}
// Verifies that StaticAssertTypeEq works in a namespace scope.
static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
StaticAssertTypeEq<const int, const int>();
// Verifies that StaticAssertTypeEq works in a class.
template <typename T>
class StaticAssertTypeEqTestHelper {
public:
StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
};
TEST(StaticAssertTypeEqTest, WorksInClass) {
StaticAssertTypeEqTestHelper<bool>();
}
// Verifies that StaticAssertTypeEq works inside a function.
typedef int IntAlias;
TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
StaticAssertTypeEq<int, IntAlias>();
StaticAssertTypeEq<int*, IntAlias*>();
}
TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
EXPECT_FALSE(HasNonfatalFailure());
}
static void FailFatally() { FAIL(); }
TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
FailFatally();
const bool has_nonfatal_failure = HasNonfatalFailure();
ClearCurrentTestPartResults();
EXPECT_FALSE(has_nonfatal_failure);
}
TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
ADD_FAILURE();
const bool has_nonfatal_failure = HasNonfatalFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_nonfatal_failure);
}
TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
FailFatally();
ADD_FAILURE();
const bool has_nonfatal_failure = HasNonfatalFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_nonfatal_failure);
}
// A wrapper for calling HasNonfatalFailure outside of a test body.
static bool HasNonfatalFailureHelper() {
return testing::Test::HasNonfatalFailure();
}
TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
EXPECT_FALSE(HasNonfatalFailureHelper());
}
TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
ADD_FAILURE();
const bool has_nonfatal_failure = HasNonfatalFailureHelper();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_nonfatal_failure);
}
TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
EXPECT_FALSE(HasFailure());
}
TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
FailFatally();
const bool has_failure = HasFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
ADD_FAILURE();
const bool has_failure = HasFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
FailFatally();
ADD_FAILURE();
const bool has_failure = HasFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
// A wrapper for calling HasFailure outside of a test body.
static bool HasFailureHelper() { return testing::Test::HasFailure(); }
TEST(HasFailureTest, WorksOutsideOfTestBody) {
EXPECT_FALSE(HasFailureHelper());
}
TEST(HasFailureTest, WorksOutsideOfTestBody2) {
ADD_FAILURE();
const bool has_failure = HasFailureHelper();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
class TestListener : public EmptyTestEventListener {
public:
TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
TestListener(int* on_start_counter, bool* is_destroyed)
: on_start_counter_(on_start_counter),
is_destroyed_(is_destroyed) {}
~TestListener() override {
if (is_destroyed_)
*is_destroyed_ = true;
}
protected:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
if (on_start_counter_ != nullptr) (*on_start_counter_)++;
}
private:
int* on_start_counter_;
bool* is_destroyed_;
};
// Tests the constructor.
TEST(TestEventListenersTest, ConstructionWorks) {
TestEventListeners listeners;
EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
}
// Tests that the TestEventListeners destructor deletes all the listeners it
// owns.
TEST(TestEventListenersTest, DestructionWorks) {
bool default_result_printer_is_destroyed = false;
bool default_xml_printer_is_destroyed = false;
bool extra_listener_is_destroyed = false;
TestListener* default_result_printer =
new TestListener(nullptr, &default_result_printer_is_destroyed);
TestListener* default_xml_printer =
new TestListener(nullptr, &default_xml_printer_is_destroyed);
TestListener* extra_listener =
new TestListener(nullptr, &extra_listener_is_destroyed);
{
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
default_result_printer);
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
default_xml_printer);
listeners.Append(extra_listener);
}
EXPECT_TRUE(default_result_printer_is_destroyed);
EXPECT_TRUE(default_xml_printer_is_destroyed);
EXPECT_TRUE(extra_listener_is_destroyed);
}
// Tests that a listener Append'ed to a TestEventListeners list starts
// receiving events.
TEST(TestEventListenersTest, Append) {
int on_start_counter = 0;
bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
listeners.Append(listener);
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
}
EXPECT_TRUE(is_destroyed);
}
// Tests that listeners receive events in the order they were appended to
// the list, except for *End requests, which must be received in the reverse
// order.
class SequenceTestingListener : public EmptyTestEventListener {
public:
SequenceTestingListener(std::vector<std::string>* vector, const char* id)
: vector_(vector), id_(id) {}
protected:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
vector_->push_back(GetEventDescription("OnTestProgramStart"));
}
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
vector_->push_back(GetEventDescription("OnTestProgramEnd"));
}
void OnTestIterationStart(const UnitTest& /*unit_test*/,
int /*iteration*/) override {
vector_->push_back(GetEventDescription("OnTestIterationStart"));
}
void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int /*iteration*/) override {
vector_->push_back(GetEventDescription("OnTestIterationEnd"));
}
private:
std::string GetEventDescription(const char* method) {
Message message;
message << id_ << "." << method;
return message.GetString();
}
std::vector<std::string>* vector_;
const char* const id_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
};
TEST(EventListenerTest, AppendKeepsOrder) {
std::vector<std::string> vec;
TestEventListeners listeners;
listeners.Append(new SequenceTestingListener(&vec, "1st"));
listeners.Append(new SequenceTestingListener(&vec, "2nd"));
listeners.Append(new SequenceTestingListener(&vec, "3rd"));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
*UnitTest::GetInstance());
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
*UnitTest::GetInstance(), 0);
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
*UnitTest::GetInstance(), 0);
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
}
// Tests that a listener removed from a TestEventListeners list stops receiving
// events and is not deleted when the list is destroyed.
TEST(TestEventListenersTest, Release) {
int on_start_counter = 0;
bool is_destroyed = false;
// Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the
// test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
listeners.Append(listener);
EXPECT_EQ(listener, listeners.Release(listener));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_TRUE(listeners.Release(listener) == nullptr);
}
EXPECT_EQ(0, on_start_counter);
EXPECT_FALSE(is_destroyed);
delete listener;
}
// Tests that no events are forwarded when event forwarding is disabled.
TEST(EventListenerTest, SuppressEventForwarding) {
int on_start_counter = 0;
TestListener* listener = new TestListener(&on_start_counter, nullptr);
TestEventListeners listeners;
listeners.Append(listener);
ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
TestEventListenersAccessor::SuppressEventForwarding(&listeners);
ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter);
}
// Tests that events generated by Google Test are not forwarded in
// death test subprocesses.
TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
EXPECT_DEATH_IF_SUPPORTED({
GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
*GetUnitTestImpl()->listeners())) << "expected failure";},
"expected failure");
}
// Tests that a listener installed via SetDefaultResultPrinter() starts
// receiving events and is returned via default_result_printer() and that
// the previous default_result_printer is removed from the list and deleted.
TEST(EventListenerTest, default_result_printer) {
int on_start_counter = 0;
bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
EXPECT_EQ(listener, listeners.default_result_printer());
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
// Replacing default_result_printer with something else should remove it
// from the list and destroy it.
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_TRUE(is_destroyed);
// After broadcasting an event the counter is still the same, indicating
// the listener is not in the list anymore.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
}
// Tests that the default_result_printer listener stops receiving events
// when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
int on_start_counter = 0;
bool is_destroyed = false;
// Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the
// test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
EXPECT_EQ(listener, listeners.Release(listener));
EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_FALSE(is_destroyed);
// Broadcasting events now should not affect default_result_printer.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter);
}
// Destroying the list should not affect the listener now, too.
EXPECT_FALSE(is_destroyed);
delete listener;
}
// Tests that a listener installed via SetDefaultXmlGenerator() starts
// receiving events and is returned via default_xml_generator() and that
// the previous default_xml_generator is removed from the list and deleted.
TEST(EventListenerTest, default_xml_generator) {
int on_start_counter = 0;
bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
EXPECT_EQ(listener, listeners.default_xml_generator());
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
// Replacing default_xml_generator with something else should remove it
// from the list and destroy it.
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
EXPECT_TRUE(is_destroyed);
// After broadcasting an event the counter is still the same, indicating
// the listener is not in the list anymore.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
}
// Tests that the default_xml_generator listener stops receiving events
// when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
int on_start_counter = 0;
bool is_destroyed = false;
// Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the
// test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
EXPECT_EQ(listener, listeners.Release(listener));
EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
EXPECT_FALSE(is_destroyed);
// Broadcasting events now should not affect default_xml_generator.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter);
}
// Destroying the list should not affect the listener now, too.
EXPECT_FALSE(is_destroyed);
delete listener;
}
// Sanity tests to ensure that the alternative, verbose spellings of
// some of the macros work. We don't test them thoroughly as that
// would be quite involved. Since their implementations are
// straightforward, and they are rarely used, we'll just rely on the
// users to tell us when they are broken.
GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
// GTEST_FAIL is the same as FAIL.
EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
"An expected failure");
// GTEST_ASSERT_XY is the same as ASSERT_XY.
GTEST_ASSERT_EQ(0, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
"An expected failure");
EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_NE(0, 1);
GTEST_ASSERT_NE(1, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_LE(0, 0);
GTEST_ASSERT_LE(0, 1);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_LT(0, 1);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
"An expected failure");
EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_GE(0, 0);
GTEST_ASSERT_GE(1, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
"An expected failure");
GTEST_ASSERT_GT(1, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
"An expected failure");
EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
"An expected failure");
}
// Tests for internal utilities necessary for implementation of the universal
// printing.
class ConversionHelperBase {};
class ConversionHelperDerived : public ConversionHelperBase {};
struct HasDebugStringMethods {
std::string DebugString() const { return ""; }
std::string ShortDebugString() const { return ""; }
};
struct InheritsDebugStringMethods : public HasDebugStringMethods {};
struct WrongTypeDebugStringMethod {
std::string DebugString() const { return ""; }
int ShortDebugString() const { return 1; }
};
struct NotConstDebugStringMethod {
std::string DebugString() { return ""; }
std::string ShortDebugString() const { return ""; }
};
struct MissingDebugStringMethod {
std::string DebugString() { return ""; }
};
struct IncompleteType;
// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
// constant.
TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
GTEST_COMPILE_ASSERT_(
HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
const_true);
GTEST_COMPILE_ASSERT_(
HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
const_true);
GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
const InheritsDebugStringMethods>::value,
const_true);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
const_false);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
const_false);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
const_false);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
const_false);
}
// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
// needed methods.
TEST(HasDebugStringAndShortDebugStringTest,
ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
EXPECT_TRUE(
HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
}
// Tests that HasDebugStringAndShortDebugString<T>::value is false when T
// doesn't have needed methods.
TEST(HasDebugStringAndShortDebugStringTest,
ValueIsFalseWhenTypeIsNotAProtocolMessage) {
EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
EXPECT_FALSE(
HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
}
// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
template <typename T1, typename T2>
void TestGTestRemoveReferenceAndConst() {
static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
"GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
}
TEST(RemoveReferenceToConstTest, Works) {
TestGTestRemoveReferenceAndConst<int, int>();
TestGTestRemoveReferenceAndConst<double, double&>();
TestGTestRemoveReferenceAndConst<char, const char>();
TestGTestRemoveReferenceAndConst<char, const char&>();
TestGTestRemoveReferenceAndConst<const char*, const char*>();
}
// Tests GTEST_REFERENCE_TO_CONST_.
template <typename T1, typename T2>
void TestGTestReferenceToConst() {
static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
"GTEST_REFERENCE_TO_CONST_ failed.");
}
TEST(GTestReferenceToConstTest, Works) {
TestGTestReferenceToConst<const char&, char>();
TestGTestReferenceToConst<const int&, const int>();
TestGTestReferenceToConst<const double&, double>();
TestGTestReferenceToConst<const std::string&, const std::string&>();
}
// Tests IsContainerTest.
class NonContainer {};
TEST(IsContainerTestTest, WorksForNonContainer) {
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
}
TEST(IsContainerTestTest, WorksForContainer) {
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<std::vector<bool> >(0)));
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<std::map<int, double> >(0)));
}
struct ConstOnlyContainerWithPointerIterator {
using const_iterator = int*;
const_iterator begin() const;
const_iterator end() const;
};
struct ConstOnlyContainerWithClassIterator {
struct const_iterator {
const int& operator*() const;
const_iterator& operator++(/* pre-increment */);
};
const_iterator begin() const;
const_iterator end() const;
};
TEST(IsContainerTestTest, ConstOnlyContainer) {
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
}
// Tests IsHashTable.
struct AHashTable {
typedef void hasher;
};
struct NotReallyAHashTable {
typedef void hasher;
typedef void reverse_iterator;
};
TEST(IsHashTable, Basic) {
EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
}
// Tests ArrayEq().
TEST(ArrayEqTest, WorksForDegeneratedArrays) {
EXPECT_TRUE(ArrayEq(5, 5L));
EXPECT_FALSE(ArrayEq('a', 0));
}
TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
// Note that a and b are distinct but compatible types.
const int a[] = { 0, 1 };
long b[] = { 0, 1 };
EXPECT_TRUE(ArrayEq(a, b));
EXPECT_TRUE(ArrayEq(a, 2, b));
b[0] = 2;
EXPECT_FALSE(ArrayEq(a, b));
EXPECT_FALSE(ArrayEq(a, 1, b));
}
TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
const char a[][3] = { "hi", "lo" };
const char b[][3] = { "hi", "lo" };
const char c[][3] = { "hi", "li" };
EXPECT_TRUE(ArrayEq(a, b));
EXPECT_TRUE(ArrayEq(a, 2, b));
EXPECT_FALSE(ArrayEq(a, c));
EXPECT_FALSE(ArrayEq(a, 2, c));
}
// Tests ArrayAwareFind().
TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
const char a[] = "hello";
EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
}
TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
const int b[2] = { 2, 3 };
EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
const int c[2] = { 6, 7 };
EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
}
// Tests CopyArray().
TEST(CopyArrayTest, WorksForDegeneratedArrays) {
int n = 0;
CopyArray('a', &n);
EXPECT_EQ('a', n);
}
TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
const char a[3] = "hi";
int b[3];
#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
CopyArray(a, &b);
EXPECT_TRUE(ArrayEq(a, b));
#endif
int c[3];
CopyArray(a, 3, c);
EXPECT_TRUE(ArrayEq(a, c));
}
TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
int b[2][3];
#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
CopyArray(a, &b);
EXPECT_TRUE(ArrayEq(a, b));
#endif
int c[2][3];
CopyArray(a, 2, c);
EXPECT_TRUE(ArrayEq(a, c));
}
// Tests NativeArray.
TEST(NativeArrayTest, ConstructorFromArrayWorks) {
const int a[3] = { 0, 1, 2 };
NativeArray<int> na(a, 3, RelationToSourceReference());
EXPECT_EQ(3U, na.size());
EXPECT_EQ(a, na.begin());
}
TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
typedef int Array[2];
Array* a = new Array[1];
(*a)[0] = 0;
(*a)[1] = 1;
NativeArray<int> na(*a, 2, RelationToSourceCopy());
EXPECT_NE(*a, na.begin());
delete[] a;
EXPECT_EQ(0, na.begin()[0]);
EXPECT_EQ(1, na.begin()[1]);
// We rely on the heap checker to verify that na deletes the copy of
// array.
}
TEST(NativeArrayTest, TypeMembersAreCorrect) {
StaticAssertTypeEq<char, NativeArray<char>::value_type>();
StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
}
TEST(NativeArrayTest, MethodsWork) {
const int a[3] = { 0, 1, 2 };
NativeArray<int> na(a, 3, RelationToSourceCopy());
ASSERT_EQ(3U, na.size());
EXPECT_EQ(3, na.end() - na.begin());
NativeArray<int>::const_iterator it = na.begin();
EXPECT_EQ(0, *it);
++it;
EXPECT_EQ(1, *it);
it++;
EXPECT_EQ(2, *it);
++it;
EXPECT_EQ(na.end(), it);
EXPECT_TRUE(na == na);
NativeArray<int> na2(a, 3, RelationToSourceReference());
EXPECT_TRUE(na == na2);
const int b1[3] = { 0, 1, 1 };
const int b2[4] = { 0, 1, 2, 3 };
EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
}
TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
const char a[2][3] = { "hi", "lo" };
NativeArray<char[3]> na(a, 2, RelationToSourceReference());
ASSERT_EQ(2U, na.size());
EXPECT_EQ(a, na.begin());
}
// IndexSequence
TEST(IndexSequence, MakeIndexSequence) {
using testing::internal::IndexSequence;
using testing::internal::MakeIndexSequence;
EXPECT_TRUE(
(std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
EXPECT_TRUE(
(std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
EXPECT_TRUE(
(std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
EXPECT_TRUE((
std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
EXPECT_TRUE(
(std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
}
// ElemFromList
TEST(ElemFromList, Basic) {
using testing::internal::ElemFromList;
EXPECT_TRUE(
(std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
EXPECT_TRUE(
(std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
EXPECT_TRUE(
(std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
EXPECT_TRUE((
std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
char, int, int, int, int>::type>::value));
}
// FlatTuple
TEST(FlatTuple, Basic) {
using testing::internal::FlatTuple;
FlatTuple<int, double, const char*> tuple = {};
EXPECT_EQ(0, tuple.Get<0>());
EXPECT_EQ(0.0, tuple.Get<1>());
EXPECT_EQ(nullptr, tuple.Get<2>());
tuple = FlatTuple<int, double, const char*>(
testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
EXPECT_EQ(7, tuple.Get<0>());
EXPECT_EQ(3.2, tuple.Get<1>());
EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
tuple.Get<1>() = 5.1;
EXPECT_EQ(5.1, tuple.Get<1>());
}
namespace {
std::string AddIntToString(int i, const std::string& s) {
return s + std::to_string(i);
}
} // namespace
TEST(FlatTuple, Apply) {
using testing::internal::FlatTuple;
FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
5, "Hello"};
// Lambda.
EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
return i == static_cast<int>(s.size());
}));
// Function.
EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
// Mutating operations.
tuple.Apply([](int& i, std::string& s) {
++i;
s += s;
});
EXPECT_EQ(tuple.Get<0>(), 6);
EXPECT_EQ(tuple.Get<1>(), "HelloHello");
}
struct ConstructionCounting {
ConstructionCounting() { ++default_ctor_calls; }
~ConstructionCounting() { ++dtor_calls; }
ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
ConstructionCounting& operator=(const ConstructionCounting&) {
++copy_assignment_calls;
return *this;
}
ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
++move_assignment_calls;
return *this;
}
static void Reset() {
default_ctor_calls = 0;
dtor_calls = 0;
copy_ctor_calls = 0;
move_ctor_calls = 0;
copy_assignment_calls = 0;
move_assignment_calls = 0;
}
static int default_ctor_calls;
static int dtor_calls;
static int copy_ctor_calls;
static int move_ctor_calls;
static int copy_assignment_calls;
static int move_assignment_calls;
};
int ConstructionCounting::default_ctor_calls = 0;
int ConstructionCounting::dtor_calls = 0;
int ConstructionCounting::copy_ctor_calls = 0;
int ConstructionCounting::move_ctor_calls = 0;
int ConstructionCounting::copy_assignment_calls = 0;
int ConstructionCounting::move_assignment_calls = 0;
TEST(FlatTuple, ConstructorCalls) {
using testing::internal::FlatTuple;
// Default construction.
ConstructionCounting::Reset();
{ FlatTuple<ConstructionCounting> tuple; }
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Copy construction.
ConstructionCounting::Reset();
{
ConstructionCounting elem;
FlatTuple<ConstructionCounting> tuple{
testing::internal::FlatTupleConstructTag{}, elem};
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Move construction.
ConstructionCounting::Reset();
{
FlatTuple<ConstructionCounting> tuple{
testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Copy assignment.
// TODO(ofats): it should be testing assignment operator of FlatTuple, not its
// elements
ConstructionCounting::Reset();
{
FlatTuple<ConstructionCounting> tuple;
ConstructionCounting elem;
tuple.Get<0>() = elem;
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Move assignment.
// TODO(ofats): it should be testing assignment operator of FlatTuple, not its
// elements
ConstructionCounting::Reset();
{
FlatTuple<ConstructionCounting> tuple;
tuple.Get<0>() = ConstructionCounting{};
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
ConstructionCounting::Reset();
}
TEST(FlatTuple, ManyTypes) {
using testing::internal::FlatTuple;
// Instantiate FlatTuple with 257 ints.
// Tests show that we can do it with thousands of elements, but very long
// compile times makes it unusuitable for this test.
#define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
#define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
#define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
#define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
#define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
#define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
// Let's make sure that we can have a very long list of types without blowing
// up the template instantiation depth.
FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
tuple.Get<0>() = 7;
tuple.Get<99>() = 17;
tuple.Get<256>() = 1000;
EXPECT_EQ(7, tuple.Get<0>());
EXPECT_EQ(17, tuple.Get<99>());
EXPECT_EQ(1000, tuple.Get<256>());
}
// Tests SkipPrefix().
TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
const char* const str = "hello";
const char* p = str;
EXPECT_TRUE(SkipPrefix("", &p));
EXPECT_EQ(str, p);
p = str;
EXPECT_TRUE(SkipPrefix("hell", &p));
EXPECT_EQ(str + 4, p);
}
TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
const char* const str = "world";
const char* p = str;
EXPECT_FALSE(SkipPrefix("W", &p));
EXPECT_EQ(str, p);
p = str;
EXPECT_FALSE(SkipPrefix("world!", &p));
EXPECT_EQ(str, p);
}
// Tests ad_hoc_test_result().
TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
const testing::TestResult& test_result =
testing::UnitTest::GetInstance()->ad_hoc_test_result();
EXPECT_FALSE(test_result.Failed());
}
class DynamicUnitTestFixture : public testing::Test {};
class DynamicTest : public DynamicUnitTestFixture {
void TestBody() override { EXPECT_TRUE(true); }
};
auto* dynamic_test = testing::RegisterTest(
"DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
__LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
TEST(RegisterTest, WasRegistered) {
auto* unittest = testing::UnitTest::GetInstance();
for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
auto* tests = unittest->GetTestSuite(i);
if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
for (int j = 0; j < tests->total_test_count(); ++j) {
if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
// Found it.
EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
return;
}
}
FAIL() << "Didn't find the test!";
}
// Test that the pattern globbing algorithm is linear. If not, this test should
// time out.
TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {
std::string name(100, 'a'); // Construct the string (a^100)b
name.push_back('b');
std::string pattern; // Construct the string ((a*)^100)b
for (int i = 0; i < 100; ++i) {
pattern.append("a*");
}
pattern.push_back('b');
EXPECT_TRUE(
testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str()));
}
TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {
const std::string name = "aaaa";
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*"));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:"));
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab"));
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:"));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*"));
}
TEST(PatternGlobbingTest, MatchesFilterEdgeCases) {
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a"));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*"));
EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", ""));
EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", ""));
}
|
#ifndef BOOST_SMART_PTR_DETAIL_LWM_WIN32_CS_HPP_INCLUDED
#define BOOST_SMART_PTR_DETAIL_LWM_WIN32_CS_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// boost/detail/lwm_win32_cs.hpp
//
// Copyright (c) 2002, 2003 Peter Dimov
//
// 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)
//
#ifdef BOOST_USE_WINDOWS_H
# include <windows.h>
#endif
namespace boost
{
namespace detail
{
#ifndef BOOST_USE_WINDOWS_H
struct critical_section
{
struct critical_section_debug * DebugInfo;
long LockCount;
long RecursionCount;
void * OwningThread;
void * LockSemaphore;
#if defined(_WIN64)
unsigned __int64 SpinCount;
#else
unsigned long SpinCount;
#endif
};
extern "C" __declspec(dllimport) void __stdcall InitializeCriticalSection(critical_section *);
extern "C" __declspec(dllimport) void __stdcall InitializeCriticalSectionEx(critical_section *, unsigned long spinCount, unsigned long flags);
extern "C" __declspec(dllimport) void __stdcall EnterCriticalSection(critical_section *);
extern "C" __declspec(dllimport) void __stdcall LeaveCriticalSection(critical_section *);
extern "C" __declspec(dllimport) void __stdcall DeleteCriticalSection(critical_section *);
#else
typedef ::CRITICAL_SECTION critical_section;
#endif // #ifndef BOOST_USE_WINDOWS_H
class lightweight_mutex
{
private:
critical_section cs_;
lightweight_mutex(lightweight_mutex const &);
lightweight_mutex & operator=(lightweight_mutex const &);
public:
lightweight_mutex()
{
InitializeCriticalSectionEx(&cs_, 0, 0 );
}
~lightweight_mutex()
{
DeleteCriticalSection(&cs_);
}
class scoped_lock;
friend class scoped_lock;
class scoped_lock
{
private:
lightweight_mutex & m_;
scoped_lock(scoped_lock const &);
scoped_lock & operator=(scoped_lock const &);
public:
explicit scoped_lock(lightweight_mutex & m): m_(m)
{
EnterCriticalSection(&m_.cs_);
}
~scoped_lock()
{
LeaveCriticalSection(&m_.cs_);
}
};
};
} // namespace detail
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_DETAIL_LWM_WIN32_CS_HPP_INCLUDED
|
//--------------------------------------------------------------------------------------
// File: BreakableWall.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "BreakableWall.h"
//--------------------------------------------------------------------------------------
CBreakableWall::CBreakableWall()
{
m_bBroken = false;
}
//--------------------------------------------------------------------------------------
CBreakableWall::~CBreakableWall()
{
}
//--------------------------------------------------------------------------------------
void CBreakableWall::SetPosition( D3DXVECTOR3 vPosition )
{
m_BaseMesh.vPosition = vPosition;
for( UINT i = 0; i < NUM_CHUNKS; i++ )
{
m_ChunkMesh[i].vPosition = vPosition;
}
}
//--------------------------------------------------------------------------------------
void CBreakableWall::SetRotation( D3DXVECTOR3 vRotation )
{
m_BaseMesh.vRotation = vRotation;
m_BaseMesh.vRotationOrig = vRotation;
for( UINT i = 0; i < NUM_CHUNKS; i++ )
{
m_ChunkMesh[i].vRotation = vRotation;
m_ChunkMesh[i].vRotationOrig = vRotation;
}
}
//--------------------------------------------------------------------------------------
void CBreakableWall::SetBaseMesh( CDXUTSDKMesh* pMesh )
{
m_BaseMesh.pMesh = pMesh;
D3DXVECTOR3 vExtents = pMesh->GetMeshBBoxExtents( 0 );
m_BaseMesh.BS.vCenter = pMesh->GetMeshBBoxCenter( 0 );
m_BaseMesh.BS.fRadius = D3DXVec3Length( &vExtents );
m_BaseMesh.bVisible = true;
}
//--------------------------------------------------------------------------------------
void CBreakableWall::SetChunkMesh( UINT iChunk, CDXUTSDKMesh* pMesh, D3DXVECTOR3 vOffset, float fWallScale )
{
m_ChunkMesh[iChunk].pMesh = pMesh;
D3DXMATRIX mRot;
m_ChunkMesh[iChunk].vRotation = m_ChunkMesh[iChunk].vRotationOrig;
D3DXMatrixRotationYawPitchRoll( &mRot, m_ChunkMesh[iChunk].vRotation.y, m_ChunkMesh[iChunk].vRotation.x,
m_ChunkMesh[iChunk].vRotation.z );
vOffset *= fWallScale;
D3DXVECTOR3 vRotOffset;
D3DXVec3TransformNormal( &vRotOffset, &vOffset, &mRot );
m_ChunkMesh[iChunk].vPosition = m_BaseMesh.vPosition + vRotOffset;
D3DXVECTOR3 vExtents = pMesh->GetMeshBBoxExtents( 0 );
m_ChunkMesh[iChunk].BS.vCenter = pMesh->GetMeshBBoxCenter( 0 );
m_ChunkMesh[iChunk].BS.fRadius = D3DXVec3Length( &vExtents );
m_ChunkMesh[iChunk].bDynamic = false;
m_ChunkMesh[iChunk].bVisible = true;
}
//--------------------------------------------------------------------------------------
void CBreakableWall::RenderInstance( MESH_INSTANCE* pInstance, ID3D10Device* pd3dDevice,
ID3D10EffectTechnique* pTechnique, float fWallScale, D3DXMATRIX* pmViewProj,
ID3D10EffectMatrixVariable* pWVP, ID3D10EffectMatrixVariable* pWorld )
{
if( !pInstance->bVisible )
return;
D3DXMATRIX mWorld = GetMeshMatrix( pInstance, fWallScale );
D3DXMATRIX mWVP = mWorld * ( *pmViewProj );
pWVP->SetMatrix( ( float* )&mWVP );
pWorld->SetMatrix( ( float* )&mWorld );
pInstance->pMesh->Render( pd3dDevice, pTechnique );
}
//--------------------------------------------------------------------------------------
void CBreakableWall::Render( ID3D10Device* pd3dDevice, ID3D10EffectTechnique* pTechnique, float fWallScale,
D3DXMATRIX* pmViewProj, ID3D10EffectMatrixVariable* pWVP,
ID3D10EffectMatrixVariable* pWorld )
{
if( m_bBroken )
{
for( UINT i = 0; i < NUM_CHUNKS; i++ )
{
RenderInstance( &m_ChunkMesh[i], pd3dDevice, pTechnique, fWallScale, pmViewProj, pWVP, pWorld );
}
}
else
{
RenderInstance( &m_BaseMesh, pd3dDevice, pTechnique, fWallScale, pmViewProj, pWVP, pWorld );
}
}
//--------------------------------------------------------------------------------------
D3DXMATRIX CBreakableWall::GetMeshMatrix( MESH_INSTANCE* pInstance, float fWallScale )
{
D3DXMATRIX mScale;
D3DXMATRIX mRot;
D3DXMATRIX mTrans;
D3DXMatrixScaling( &mScale, fWallScale, fWallScale, fWallScale );
D3DXMatrixRotationYawPitchRoll( &mRot, pInstance->vRotation.y, pInstance->vRotation.x, pInstance->vRotation.z );
D3DXMatrixTranslation( &mTrans, pInstance->vPosition.x, pInstance->vPosition.y, pInstance->vPosition.z );
D3DXMATRIX mWorld = mScale * mRot * mTrans;
return mWorld;
}
//--------------------------------------------------------------------------------------
D3DXMATRIX CBreakableWall::GetBaseMeshMatrix( float fWallScale )
{
return GetMeshMatrix( &m_BaseMesh, fWallScale );
}
//--------------------------------------------------------------------------------------
D3DXMATRIX CBreakableWall::GetChunkMeshMatrix( UINT iChunk, float fWallScale )
{
return GetMeshMatrix( &m_ChunkMesh[iChunk], fWallScale );
}
//--------------------------------------------------------------------------------------
bool CBreakableWall::IsBaseMeshVisible()
{
return !m_bBroken;
}
//--------------------------------------------------------------------------------------
bool CBreakableWall::IsChunkMeshVisible( UINT iChunk )
{
return m_ChunkMesh[iChunk].bVisible;
}
//--------------------------------------------------------------------------------------
float RPercent();
void CBreakableWall::CreateExplosion( D3DXVECTOR3 vCenter, D3DXVECTOR3 vDirMul, float fRadius, float fMinPower,
float fMaxPower, float fWallScale )
{
D3DXVECTOR3 vDelta = vCenter - ( m_BaseMesh.vPosition + m_BaseMesh.BS.vCenter * fWallScale );
float fDist = D3DXVec3LengthSq( &vDelta );
float f2Rad = fRadius + m_BaseMesh.BS.fRadius * fWallScale;
if( fDist > f2Rad * f2Rad )
return;
// We're broken
m_bBroken = true;
for( UINT i = 0; i < NUM_CHUNKS; i++ )
{
// center of gravity
D3DXVECTOR3 vCOG = m_ChunkMesh[i].vPosition;// + m_ChunkMesh[i].BS.vCenter*fWallScale;
vDelta = vCOG - vCenter;
float fDist = D3DXVec3LengthSq( &vDelta );
float fChunkRad = m_ChunkMesh[i].BS.fRadius * fWallScale;
f2Rad = fRadius + fChunkRad;
if( fDist < f2Rad * f2Rad )
{
// We're in motion
m_ChunkMesh[i].bDynamic = true;
// Set velocity
D3DXVec3Normalize( &vDelta, &vDelta );
fDist -= fChunkRad * fChunkRad;
float fPowerLerp = fabs( RPercent() );
float fPower = ( fMaxPower * fPowerLerp + fMinPower * ( 1.0f - fPowerLerp ) );// / sqrt(fDist);
m_ChunkMesh[i].vVelocity = vDelta * fPower;
m_ChunkMesh[i].vVelocity.x *= vDirMul.x;
m_ChunkMesh[i].vVelocity.y *= vDirMul.y;
m_ChunkMesh[i].vVelocity.z *= vDirMul.z;
// Set rotation speed
float fRotationScalar = 3.0f;
m_ChunkMesh[i].vRotationSpeed.x = RPercent() * fRotationScalar;
m_ChunkMesh[i].vRotationSpeed.y = RPercent() * fRotationScalar;
m_ChunkMesh[i].vRotationSpeed.z = RPercent() * fRotationScalar;
}
}
}
//--------------------------------------------------------------------------------------
void CBreakableWall::AdvancePieces( float fElapsedTime, D3DXVECTOR3 vGravity )
{
if( !m_bBroken )
return;
for( UINT i = 0; i < NUM_CHUNKS; i++ )
{
if( m_ChunkMesh[i].bDynamic )
{
m_ChunkMesh[i].vVelocity += fElapsedTime * vGravity;
m_ChunkMesh[i].vPosition += fElapsedTime * m_ChunkMesh[i].vVelocity;
m_ChunkMesh[i].vRotation += fElapsedTime * m_ChunkMesh[i].vRotationSpeed;
if( m_ChunkMesh[i].vPosition.y < -10.0f )
m_ChunkMesh[i].bVisible = false;
}
}
}
//----------------------------------------------------
CBuilding::CBuilding()
{
m_WidthWalls = 0;
m_HeightWalls = 0;
m_DepthWalls = 0;
m_NumWalls = 0;
m_pWallList = NULL;
m_fWallScale = 1.0f;
}
//--------------------------------------------------------------------------------------
CBuilding::~CBuilding()
{
SAFE_DELETE_ARRAY( m_pWallList );
}
//--------------------------------------------------------------------------------------
bool CBuilding::CreateBuilding( D3DXVECTOR3 vCenter, float fWallScale, UINT WidthWalls, UINT HeightWalls,
UINT DepthWalls )
{
m_WidthWalls = WidthWalls;
m_HeightWalls = HeightWalls;
m_DepthWalls = DepthWalls;
m_fWallScale = fWallScale;
UINT NumNSWalls = WidthWalls * HeightWalls; // +z -z
UINT NumEWWalls = DepthWalls * HeightWalls; // +x -x
UINT NumRoofWalls = WidthWalls * DepthWalls;// +y
m_NumWalls = NumNSWalls * 2 + NumEWWalls * 2 + NumRoofWalls;
m_pWallList = new CBreakableWall[ m_NumWalls ];
float f90Degrees = D3DX_PI / 2.0f;
float f180Degrees = D3DX_PI;
float fWallSize = 2.0f * m_fWallScale;
float X, Y, Z;
D3DXVECTOR3 vRotations( 0,0,0 );
UINT index = 0;
// North wall
Z = ( fWallSize * m_DepthWalls ) / 2.0f;
Y = fWallSize / 2.0f;
for( UINT h = 0; h < m_HeightWalls; h++ )
{
X = -( fWallSize * m_WidthWalls - fWallSize ) / 2.0f;
for( UINT w = 0; w < m_WidthWalls; w++ )
{
m_pWallList[index].SetPosition( D3DXVECTOR3( X, Y, Z ) + vCenter );
m_pWallList[index].SetRotation( vRotations );
index ++;
X += fWallSize;
}
Y += fWallSize;
}
// South wall
vRotations.y = f180Degrees;
Z = -( fWallSize * m_DepthWalls ) / 2.0f;
Y = fWallSize / 2.0f;
for( UINT h = 0; h < m_HeightWalls; h++ )
{
X = -( fWallSize * m_WidthWalls - fWallSize ) / 2.0f;
for( UINT w = 0; w < m_WidthWalls; w++ )
{
m_pWallList[index].SetPosition( D3DXVECTOR3( X, Y, Z ) + vCenter );
m_pWallList[index].SetRotation( vRotations );
index ++;
X += fWallSize;
}
Y += fWallSize;
}
// East wall
vRotations.y = -f90Degrees;
X = ( fWallSize * m_WidthWalls ) / 2.0f;
Y = fWallSize / 2.0f;
for( UINT h = 0; h < m_HeightWalls; h++ )
{
Z = -( fWallSize * m_DepthWalls - fWallSize ) / 2.0f;
for( UINT w = 0; w < m_DepthWalls; w++ )
{
m_pWallList[index].SetPosition( D3DXVECTOR3( X, Y, Z ) + vCenter );
m_pWallList[index].SetRotation( vRotations );
index ++;
Z += fWallSize;
}
Y += fWallSize;
}
// West wall
vRotations.y = f90Degrees;
X = -( fWallSize * m_WidthWalls ) / 2.0f;
Y = fWallSize / 2.0f;
for( UINT h = 0; h < m_HeightWalls; h++ )
{
Z = -( fWallSize * m_DepthWalls - fWallSize ) / 2.0f;
for( UINT w = 0; w < m_DepthWalls; w++ )
{
m_pWallList[index].SetPosition( D3DXVECTOR3( X, Y, Z ) + vCenter );
m_pWallList[index].SetRotation( vRotations );
index ++;
Z += fWallSize;
}
Y += fWallSize;
}
// Roof wall
vRotations.y = 0;
vRotations.x = -f90Degrees;
Y = ( fWallSize * m_HeightWalls );
Z = -( fWallSize * m_DepthWalls - fWallSize ) / 2.0f;
for( UINT h = 0; h < m_DepthWalls; h++ )
{
X = -( fWallSize * m_WidthWalls - fWallSize ) / 2.0f;
for( UINT w = 0; w < m_WidthWalls; w++ )
{
m_pWallList[index].SetPosition( D3DXVECTOR3( X, Y, Z ) + vCenter );
m_pWallList[index].SetRotation( vRotations );
index ++;
X += fWallSize;
}
Z += fWallSize;
}
// Bounding sphere
m_BS.vCenter = vCenter;
m_BS.vCenter.y += ( fWallSize * m_HeightWalls ) / 2.0f;
D3DXVECTOR3 vCorner;
vCorner.x = ( fWallSize * m_WidthWalls + fWallSize ) / 2.0f;
vCorner.y = ( fWallSize * m_HeightWalls + fWallSize ) / 2.0f;
vCorner.z = ( fWallSize * m_DepthWalls + fWallSize ) / 2.0f;
m_BS.fRadius = D3DXVec3Length( &vCorner );
return true;
}
//--------------------------------------------------------------------------------------
void CBuilding::SetBaseMesh( CDXUTSDKMesh* pMesh )
{
for( UINT i = 0; i < m_NumWalls; i++ )
{
m_pWallList[i].SetBaseMesh( pMesh );
}
}
//--------------------------------------------------------------------------------------
void CBuilding::SetChunkMesh( UINT iChunk, CDXUTSDKMesh* pMesh, D3DXVECTOR3 vOffset )
{
for( UINT i = 0; i < m_NumWalls; i++ )
{
m_pWallList[i].SetChunkMesh( iChunk, pMesh, vOffset, m_fWallScale );
}
}
//--------------------------------------------------------------------------------------
void CBuilding::Render( ID3D10Device* pd3dDevice, ID3D10EffectTechnique* pTechnique, D3DXMATRIX* pmViewProj,
ID3D10EffectMatrixVariable* pWVP, ID3D10EffectMatrixVariable* pWorld )
{
for( UINT i = 0; i < m_NumWalls; i++ )
{
m_pWallList[i].Render( pd3dDevice, pTechnique, m_fWallScale, pmViewProj, pWVP, pWorld );
}
}
//--------------------------------------------------------------------------------------
void CBuilding::CollectBaseMeshMatrices( CGrowableArray <D3DXMATRIX>* pMatrixArray )
{
for( UINT i = 0; i < m_NumWalls; i++ )
{
if( m_pWallList[i].IsBaseMeshVisible() )
{
D3DXMATRIX m = m_pWallList[i].GetBaseMeshMatrix( m_fWallScale );
pMatrixArray->Add( m );
}
}
}
//--------------------------------------------------------------------------------------
void CBuilding::CollectChunkMeshMatrices( UINT iChunk, CGrowableArray <D3DXMATRIX>* pMatrixArray )
{
for( UINT i = 0; i < m_NumWalls; i++ )
{
if( !m_pWallList[i].IsBaseMeshVisible() && m_pWallList[i].IsChunkMeshVisible( iChunk ) )
{
D3DXMATRIX m = m_pWallList[i].GetChunkMeshMatrix( iChunk, m_fWallScale );
pMatrixArray->Add( m );
}
}
}
//--------------------------------------------------------------------------------------
void CBuilding::CreateExplosion( D3DXVECTOR3 vCenter, D3DXVECTOR3 vDirMul, float fRadius, float fMinPower,
float fMaxPower )
{
D3DXVECTOR3 vDelta = vCenter - m_BS.vCenter;
float fDist = D3DXVec3LengthSq( &vDelta );
float f2Rad = fRadius + m_BS.fRadius;
if( fDist > f2Rad * f2Rad )
return;
for( UINT i = 0; i < m_NumWalls; i++ )
{
m_pWallList[i].CreateExplosion( vCenter, vDirMul, fRadius, fMinPower, fMaxPower, m_fWallScale );
}
}
//--------------------------------------------------------------------------------------
void CBuilding::AdvancePieces( float fElapsedTime, D3DXVECTOR3 vGravity )
{
for( UINT i = 0; i < m_NumWalls; i++ )
{
m_pWallList[i].AdvancePieces( fElapsedTime, vGravity );
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.