text string | size int64 | token_count int64 |
|---|---|---|
/*
* Copyright (c) 2009-2011, NVIDIA Corporation
* 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 NVIDIA Corporation 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "gui/Window.hpp"
#include "base/Timer.hpp"
#include "base/Array.hpp"
#include "base/Hash.hpp"
namespace FW
{
//------------------------------------------------------------------------
class StateDump;
//------------------------------------------------------------------------
class CommonControls : public Window::Listener
{
public:
//------------------------------------------------------------------------
enum Feature
{
Feature_CloseOnEsc = 1 << 0,
Feature_CloseOnAltF4 = 1 << 1,
Feature_RepaintOnF5 = 1 << 2,
Feature_ShowFPSOnF9 = 1 << 3,
Feature_HideControlsOnF10 = 1 << 4,
Feature_FullScreenOnF11 = 1 << 5,
Feature_ScreenshotOnPrtScn = 1 << 6,
Feature_LoadStateOnNum = 1 << 7,
Feature_SaveStateOnAltNum = 1 << 8,
Feature_None = 0,
Feature_All = (1 << 9) - 1,
Feature_Default = Feature_All
};
//------------------------------------------------------------------------
class StateObject
{
public:
StateObject (void) {}
virtual ~StateObject (void) {}
virtual void readState (StateDump& d) = 0;
virtual void writeState (StateDump& d) const = 0;
};
private:
struct Key;
//------------------------------------------------------------------------
struct Message
{
String string;
String volatileID;
F32 highlightTime;
U32 abgr;
};
//------------------------------------------------------------------------
struct Toggle
{
bool* boolTarget;
S32* enumTarget;
S32 enumValue;
bool* dirtyNotify;
bool isButton;
bool isSeparator;
Key* key;
String title;
F32 highlightTime;
bool visible;
Vec2f pos;
Vec2f size;
};
//------------------------------------------------------------------------
struct Slider
{
F32* floatTarget;
S32* intTarget;
bool* dirtyNotify;
F32 slack;
F32 minValue;
F32 maxValue;
bool isExponential;
Key* increaseKey;
Key* decreaseKey;
String format;
F32 speed;
F32 highlightTime;
bool visible;
bool stackWithPrevious;
Vec2f pos;
Vec2f size;
Vec2f blockPos;
Vec2f blockSize;
};
//------------------------------------------------------------------------
struct Key
{
String id;
Array<Toggle*> toggles;
Array<Slider*> sliderIncrease;
Array<Slider*> sliderDecrease;
};
//------------------------------------------------------------------------
public:
CommonControls (U32 features = Feature_Default);
virtual ~CommonControls (void);
virtual bool handleEvent (const Window::Event& ev);
void message (const String& str, const String& volatileID = "", U32 abgr = 0xffffffffu);
void addToggle (bool* target, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(target, NULL, 0, false, key, title, dirtyNotify); }
void addToggle (S32* target, S32 value, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(NULL, target, value, false, key, title, dirtyNotify); }
void addButton (bool* target, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(target, NULL, 0, true, key, title, dirtyNotify); }
void addButton (S32* target, S32 value, const String& key, const String& title, bool* dirtyNotify = NULL) { FW_ASSERT(target); addToggle(NULL, target, value, true, key, title, dirtyNotify); }
void addSeparator (void) { addToggle(NULL, NULL, 0, false, "", "", NULL); }
void setControlVisibility(bool visible) { m_controlVisibility = visible; } // applies to next addXxx()
void addSlider (F32* target, F32 minValue, F32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed = 0.25f, bool* dirtyNotify = NULL) { addSlider(target, NULL, minValue, maxValue, isExponential, increaseKey, decreaseKey, format, speed, dirtyNotify); }
void addSlider (S32* target, S32 minValue, S32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed = 0.0f, bool* dirtyNotify = NULL) { addSlider(NULL, target, (F32)minValue, (F32)maxValue, isExponential, increaseKey, decreaseKey, format, speed, dirtyNotify); }
void beginSliderStack (void) { m_sliderStackBegun = true; m_sliderStackEmpty = true; }
void endSliderStack (void) { m_sliderStackBegun = false; }
void removeControl (const void* target);
void resetControls (void);
void setStateFilePrefix (const String& prefix) { m_stateFilePrefix = prefix; }
void setScreenshotFilePrefix(const String& prefix) { m_screenshotFilePrefix = prefix; }
String getStateFileName (int idx) const { return sprintf("%s%03d.dat", m_stateFilePrefix.getPtr(), idx); }
String getScreenshotFileName(void) const;
void addStateObject (StateObject* obj) { if (obj && !m_stateObjs.contains(obj)) m_stateObjs.add(obj); }
void removeStateObject (StateObject* obj) { m_stateObjs.removeItem(obj); }
bool loadState (const String& fileName);
bool saveState (const String& fileName);
bool loadStateDialog (void);
bool saveStateDialog (void);
void showControls (bool show) { m_showControls = show; }
void showFPS (bool show) { m_showFPS = show; }
bool getShowControls (void) const { return m_showControls; }
bool getShowFPS (void) const { return m_showFPS; }
F32 getKeyBoost (void) const;
void flashButtonTitles (void);
private:
bool hasFeature (Feature feature) { return ((m_features & feature) != 0); }
void render (GLContext* gl);
void addToggle (bool* boolTarget, S32* enumTarget, S32 enumValue, bool isButton, const String& key, const String& title, bool* dirtyNotify);
void addSlider (F32* floatTarget, S32* intTarget, F32 minValue, F32 maxValue, bool isExponential, const String& increaseKey, const String& decreaseKey, const String& format, F32 speed, bool* dirtyNotify);
Key* getKey (const String& id);
void layout (const Vec2f& viewSize, F32 fontHeight);
void clearActive (void);
void updateActive (const Vec2f& mousePos);
F32 updateHighlightFade (F32* highlightTime);
U32 fadeABGR (U32 abgr, F32 fade);
static void selectToggle (Toggle* t);
F32 getSliderY (const Slider* s, bool applySlack) const;
void setSliderY (Slider* s, F32 y);
static F32 getSliderValue (const Slider* s, bool applySlack);
static void setSliderValue (Slider* s, F32 v);
static String getSliderLabel (const Slider* s);
static void sliderKeyDown (Slider* s, int dir);
void enterSliderValue (Slider* s);
static void drawPanel (GLContext* gl, const Vec2f& pos, const Vec2f& size, U32 interiorABGR, U32 topLeftABGR, U32 bottomRightABGR);
private:
CommonControls (const CommonControls&); // forbidden
CommonControls& operator= (const CommonControls&); // forbidden
private:
const U32 m_features;
Window* m_window;
Timer m_timer;
bool m_showControls;
bool m_showFPS;
String m_stateFilePrefix;
String m_screenshotFilePrefix;
Array<Message> m_messages;
Array<Toggle*> m_toggles;
Array<Slider*> m_sliders;
Array<StateObject*> m_stateObjs;
Hash<String, Key*> m_keyHash;
bool m_sliderStackBegun;
bool m_sliderStackEmpty;
bool m_controlVisibility;
Vec2f m_viewSize;
F32 m_fontHeight;
F32 m_rightX;
S32 m_activeSlider;
S32 m_activeToggle;
bool m_dragging;
F32 m_avgFrameTime;
bool m_screenshot;
};
//------------------------------------------------------------------------
}
| 11,424 | 3,220 |
///////////////////////////////////////////////////////////////
// GraviArtifact.cpp
// GraviArtefact - ะณัะฐะฒะธัะฐัะธะพะฝะฝัะน ะฐััะตัะฐะบั, ะฟััะณะฐะตั ะฝะฐ ะผะตััะต
// ะธ ะฝะตัััะพะนัะธะฒะพ ะฟะฐัะธั ะฝะฐะด ะทะตะผะปะตะน
///////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GraviArtifact.h"
#include "PhysicsShell.h"
#include "level.h"
#include "xrmessages.h"
#include "game_cl_base.h"
#include "../Include/xrRender/Kinematics.h"
#include "phworld.h"
extern CPHWorld* ph_world;
#define CHOOSE_MAX(x,inst_x,y,inst_y,z,inst_z)\
if(x>y)\
if(x>z){inst_x;}\
else{inst_z;}\
else\
if(y>z){inst_y;}\
else{inst_z;}
CGraviArtefact::CGraviArtefact(void)
{
shedule.t_min = 20;
shedule.t_max = 50;
m_fJumpHeight = 0;
m_fEnergy = 1.f;
}
CGraviArtefact::~CGraviArtefact(void)
{
}
void CGraviArtefact::Load(LPCSTR section)
{
inherited::Load(section);
if(pSettings->line_exist(section, "jump_height")) m_fJumpHeight = pSettings->r_float(section,"jump_height");
// m_fEnergy = pSettings->r_float(section,"energy");
}
void CGraviArtefact::UpdateCLChild()
{
VERIFY(!ph_world->Processing());
if (getVisible() && m_pPhysicsShell) {
if (m_fJumpHeight) {
Fvector dir;
dir.set(0, -1.f, 0);
collide::rq_result RQ;
//ะฟัะพะฒะตัะธัั ะฒััะพัั ะฐััะธัะฐะบัะฐ
if(Level().ObjectSpace.RayPick(Position(), dir, m_fJumpHeight, collide::rqtBoth, RQ, this))
{
dir.y = 1.f;
m_pPhysicsShell->applyImpulse(dir,
30.f * Device.fTimeDelta *
m_pPhysicsShell->getMass());
}
}
} else
if(H_Parent())
{
XFORM().set(H_Parent()->XFORM());
};
} | 1,595 | 749 |
#include "stdafx.h"
#include "console_io_handler.h"
#include "messageSend.h"
#include "multiLingual.h"
#include "settings.h"
ConsoleQuit quit;
ConsoleHelp help;
ConsoleFileNew newFile;
ConsoleFileOpen openFile;
ConsoleFileClose closeFile;
ConsoleFileSave saveFile;
ConsoleFileSaveAs saveFileAs;
ConsoleMidiMakeEdit makeEdit;
ConsoleCrash crash;
ConsoleInfo info;
ConsoleSettingsAddLanguage addLanguage;
ConsolePrintTranslation printTranslation;
ConsoleMidiPattern pattern;
ConsoleInputHandler* input_handlers[NUM_HANDLERS] =
{
&help,
&quit,
&openFile,
&newFile,
&closeFile,
&saveFile,
&saveFileAs,
&crash, &info,
&makeEdit,
&addLanguage,
&printTranslation,
&pattern
};
void handleConsoleInput(std::string input, ConsoleInputHandler ** handlerList, int numHandlers)
{
std::string test;
std::istringstream iss{ input };
iss >> test;
std::ostringstream oss;
oss << iss.rdbuf();
std::string args = oss.str();
if (test == "") {
sendMessage(MESSAGE_NO_COMMAND_PROVIDED, "", MESSAGE_TYPE_ERROR);
return;
}
if(args != "") args = args.substr(1); // remove space from start of string
//remove command from rest of arguments for easier processing
bool foundCall = false; // bool for whether a handler was found
for (int i = 0; i <numHandlers; i++) {
if (handlerList[i]->getIdentifier() == test) {
handlerList[i]->call(args);
foundCall = 1;
break;
}
}
if (!foundCall) sendMessage(MESSAGE_NO_MATCHING_COMMAND, "", MESSAGE_TYPE_ERROR);
}
/***************************************/
//implement multi-layered console input handler
ConsoleInputHandler::ConsoleInputHandler()
{
identifier = "NULL";
description = CONSOLE_INPUT_HANDLER_DEFAULT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_DEFAULT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_DEFAULT_EXAMPLE_USAGE;
}
void ConsoleInputHandler::call(std::string args)
{
std::cout << "Test" << std::endl;
}
std::string ConsoleInputHandler::getIdentifier()
{
return identifier;
}
std::string ConsoleInputHandler::getDescription()
{
return translate(description);
}
std::string ConsoleInputHandler::getArguments()
{
return translate(arguments);
}
std::string ConsoleInputHandler::getExampleUsage()
{
std::string str = identifier + " " + translate(exampleUsage);
return str;
}
/***************************************/
// files
ConsoleFileOpen::ConsoleFileOpen()
{
identifier = "open";
description = CONSOLE_INPUT_HANDLER_FILE_OPEN_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_OPEN_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_OPEN_EXAMPLE_USAGE;
}
void ConsoleFileOpen::call(std::string args)
{
if (args == "") {
sendMessage(MESSAGE_NOT_VALID_FILENAME, "", MESSAGE_TYPE_ERROR);
return;
}
fileOpen(args);
return;
}
ConsoleFileClose::ConsoleFileClose()
{
identifier = "close";
description = CONSOLE_INPUT_HANDLER_FILE_CLOSE_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_CLOSE_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_CLOSE_EXAMPLE_USAGE;
}
void ConsoleFileClose::call(std::string args)
{
if (currentFile == NULL) // if file is not open
{
sendMessage(MESSAGE_NO_FILE_OPEN, "",MESSAGE_TYPE_ERROR);
return;
}
fileClose();
}
ConsoleFileSave::ConsoleFileSave()
{
identifier = "save";
description = CONSOLE_INPUT_HANDLER_FILE_SAVE_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_SAVE_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_SAVE_EXAMPLE_USAGE;
}
void ConsoleFileSave::call(std::string args)
{
if (currentFile == NULL) // if file is not open
{
sendMessage(MESSAGE_NO_FILE_OPEN, "", MESSAGE_TYPE_ERROR);
return;
}
if (args != "") currentFile->saveAs(args);
else currentFile->save();
}
ConsoleFileSaveAs::ConsoleFileSaveAs()
{
identifier = "saveAs";
description = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_SAVE_AS_EXAMPLE_USAGE;
}
void ConsoleFileSaveAs::call(std::string args)
{
if (currentFile == NULL) // if file is not open
{
sendMessage(MESSAGE_NO_FILE_OPEN, "",MESSAGE_TYPE_ERROR);
return;
}
if (args == "") { // if no file name provided
sendMessage(MESSAGE_NOT_VALID_FILENAME, "", MESSAGE_TYPE_ERROR);
return;
}
currentFile->saveAs(args);
}
ConsoleFileNew::ConsoleFileNew()
{
identifier = "new";
description = CONSOLE_INPUT_HANDLER_FILE_NEW_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_FILE_NEW_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_FILE_NEW_EXAMPLE_USAGE;
}
void ConsoleFileNew::call(std::string args)
{
fileNew();
}
// program functions
ConsoleQuit::ConsoleQuit()
{
identifier = "quit";
description = CONSOLE_INPUT_HANDLER_QUIT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_QUIT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_QUIT_EXAMPLE_USAGE;
}
void ConsoleQuit::call(std::string args)
{
quit();
}
ConsoleHelp::ConsoleHelp()
{
identifier = "help";
description = CONSOLE_INPUT_HANDLER_HELP_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_HELP_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_HELP_EXAMPLE_USAGE;
}
void ConsoleHelp::call(std::string args)
{
//set colour to green
HANDLE hConsole;
int colour = 2;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, colour);
//if no argument
if (args == "") {
std::cout << "Help:" << std::endl;
for (int i = 0; i < NUM_HANDLERS; i++) {
std::cout << input_handlers[i]->getIdentifier() << ": "
<< input_handlers[i]->getDescription() << std::endl;
}
}
//if argument provided
else {
bool foundCall = false; // bool for whether a handler was found
for (int i = 0; i < NUM_HANDLERS; i++) {
if (input_handlers[i]->getIdentifier() == args) {
std::cout << translate(STRING_HELP_FOR) << " " << input_handlers[i]->getIdentifier() << "\n"
<< input_handlers[i]->getDescription() << "\n"
<< input_handlers[i]->getArguments() << "\n" << input_handlers[i]->getExampleUsage() << std::endl;
foundCall = 1;
break;
}
}
if (!foundCall) sendMessage(MESSAGE_NO_MATCHING_COMMAND, "", MESSAGE_TYPE_ERROR);
}
SetConsoleTextAttribute(hConsole, 15);
}
ConsoleCrash::ConsoleCrash()
{
identifier = "crash";
description = CONSOLE_INPUT_HANDLER_CRASH_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_CRASH_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_CRASH_EXAMPLE_USAGE;
}
void ConsoleCrash::call(std::string args)
{
throw std::exception("Manually initiated crash", ERROR_CODE_MANUAL_CRASH);
}
ConsoleInfo::ConsoleInfo()
{
identifier = "info";
description = CONSOLE_INPUT_HANDLER_INFO_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_INFO_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_INFO_EXAMPLE_USAGE;
}
void ConsoleInfo::call(std::string args)
{
printAppInfo();
}
// midi functions
ConsoleMidiMakeEdit::ConsoleMidiMakeEdit()
{
identifier = "makeEdit";
description = CONSOLE_INPUT_HANDLER_MAKE_EDIT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MAKE_EDIT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MAKE_EDIT_EXAMPLE_USAGE;
}
void ConsoleMidiMakeEdit::call(std::string args)
{
currentFile->makeEdit();
}
ConsoleMidiTrack::ConsoleMidiTrack()
{
identifier = "track";
description = CONSOLE_INPUT_HANDLER_MIDI_TRACK_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MIDI_TRACK_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_TRACK_EXAMPLE_USAGE;
}
void ConsoleMidiTrack::call(std::string args)
{
// determine request type
// based on request type, perform action
}
ConsoleMidiSelect::ConsoleMidiSelect()
{
identifier = "select";
description = CONSOLE_INPUT_HANDLER_MIDI_SELECT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MIDI_SELECT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_SELECT_EXAMPLE_USAGE;
}
void ConsoleMidiSelect::call(std::string args)
{
// use arguments to determine what to select, then select it
}
ConsoleMidiSelection::ConsoleMidiSelection()
{
identifier = "selection";
description = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_MIDI_SELECTION_EXAMPLE_USAGE;
}
void ConsoleMidiSelection::call(std::string args)
{
// determine action to perform based on arguments
}
ConsoleSettingsAddLanguage::ConsoleSettingsAddLanguage()
{
identifier = "addLanguage";
description = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_SETTINGS_ADD_LANGUAGE_EXAMPLE_USAGE;
}
void ConsoleSettingsAddLanguage::call(std::string args)
{
settings->addLanguage(args);
}
ConsolePrintTranslation::ConsolePrintTranslation()
{
identifier = "printTranslation";
description = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_PRINT_TRANSLATION_EXAMPLE_USAGE;
}
void ConsolePrintTranslation::call(std::string args)
{
std::stringstream ss(args);
int i;
ss >> i;
sendMessage(STRING_TRANSLATION, translate(i));
}
ConsoleRunScript::ConsoleRunScript()
{
identifier = "run";
description = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_DESCRIPTION;
arguments = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_ARGUMENTS;
exampleUsage = CONSOLE_INPUT_HANDLER_RUN_SCRIPT_EXAMPLE_USAGE;
}
void ConsoleRunScript::call(std::string args) {
}
| 9,387 | 3,668 |
// LAF OS Library
// Copyright (C) 2016-2018 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "os/x11/event_queue.h"
#include "os/x11/window.h"
#include <X11/Xlib.h>
#define EV_TRACE(...)
namespace os {
#if !defined(NDEBUG)
namespace {
const char* get_event_name(XEvent& event)
{
switch (event.type) {
case KeyPress: return "KeyPress";
case KeyRelease: return "KeyRelease";
case ButtonPress: return "ButtonPress";
case ButtonRelease: return "ButtonRelease";
case MotionNotify: return "MotionNotify";
case EnterNotify: return "EnterNotify";
case LeaveNotify: return "LeaveNotify";
case FocusIn: return "FocusIn";
case FocusOut: return "FocusOut";
case KeymapNotify: return "KeymapNotify";
case Expose: return "Expose";
case GraphicsExpose: return "GraphicsExpose";
case NoExpose: return "NoExpose";
case VisibilityNotify: return "VisibilityNotify";
case CreateNotify: return "CreateNotify";
case DestroyNotify: return "DestroyNotify";
case UnmapNotify: return "UnmapNotify";
case MapNotify: return "MapNotify";
case MapRequest: return "MapRequest";
case ReparentNotify: return "ReparentNotify";
case ConfigureNotify: return "ConfigureNotify";
case ConfigureRequest: return "ConfigureRequest";
case GravityNotify: return "GravityNotify";
case ResizeRequest: return "ResizeRequest";
case CirculateNotify: return "CirculateNotify";
case CirculateRequest: return "CirculateRequest";
case PropertyNotify: return "PropertyNotify";
case SelectionClear: return "SelectionClear";
case SelectionRequest: return "SelectionRequest";
case SelectionNotify: return "SelectionNotify";
case ColormapNotify: return "ColormapNotify";
case ClientMessage: return "ClientMessage";
case MappingNotify: return "MappingNotify";
case GenericEvent: return "GenericEvent";
}
return "Unknown";
}
} // anonymous namespace
#endif
void X11EventQueue::getEvent(Event& ev, bool canWait)
{
checkResizeDisplayEventEvent(canWait);
::Display* display = X11::instance()->display();
XSync(display, False);
XEvent event;
int events = XEventsQueued(display, QueuedAlready);
if (events == 0 && canWait)
events = 1;
for (int i=0; i<events; ++i) {
XNextEvent(display, &event);
processX11Event(event);
}
if (m_events.empty()) {
#pragma push_macro("None")
#undef None // Undefine the X11 None macro
ev.setType(Event::None);
#pragma pop_macro("None")
}
else {
ev = m_events.front();
m_events.pop();
}
}
void X11EventQueue::processX11Event(XEvent& event)
{
EV_TRACE("XEvent: %s (%d)\n", get_event_name(event), event.type);
X11Window* window = X11Window::getPointerFromHandle(event.xany.window);
// In MappingNotify the window can be nullptr
if (window)
window->processX11Event(event);
}
} // namespace os
| 3,002 | 1,005 |
// Copyright 2020 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/chromeos/net/network_diagnostics/fake_tcp_connected_socket.h"
#include <utility>
#include "base/callback.h"
#include "base/logging.h"
#include "base/optional.h"
#include "mojo/public/cpp/system/data_pipe.h"
FakeTCPConnectedSocket::FakeTCPConnectedSocket() = default;
FakeTCPConnectedSocket::~FakeTCPConnectedSocket() = default;
void FakeTCPConnectedSocket::UpgradeToTLS(
const net::HostPortPair& host_port_pair,
network::mojom::TLSClientSocketOptionsPtr socket_options,
const net::MutableNetworkTrafficAnnotationTag& traffic_annotation,
mojo::PendingReceiver<network::mojom::TLSClientSocket> receiver,
mojo::PendingRemote<network::mojom::SocketObserver> observer,
network::mojom::TCPConnectedSocket::UpgradeToTLSCallback callback) {
if (disconnect_) {
receiver_.reset();
return;
}
// Only during no disconnects will |callback| be invoked.
std::move(callback).Run(tls_upgrade_code_,
mojo::ScopedDataPipeConsumerHandle(),
mojo::ScopedDataPipeProducerHandle(),
/*ssl_info=*/base::nullopt);
}
void FakeTCPConnectedSocket::SetSendBufferSize(
int32_t send_buffer_size,
SetSendBufferSizeCallback callback) {
std::move(callback).Run(0);
}
void FakeTCPConnectedSocket::SetReceiveBufferSize(
int32_t receive_buffer_size,
SetReceiveBufferSizeCallback callback) {
std::move(callback).Run(0);
}
void FakeTCPConnectedSocket::SetNoDelay(bool no_delay,
SetNoDelayCallback callback) {
std::move(callback).Run(false);
}
void FakeTCPConnectedSocket::SetKeepAlive(bool enable,
int32_t delay_secs,
SetKeepAliveCallback callback) {
std::move(callback).Run(0);
}
void FakeTCPConnectedSocket::BindReceiver(
mojo::PendingReceiver<network::mojom::TCPConnectedSocket> socket) {
DCHECK(!receiver_.is_bound());
receiver_.Bind(std::move(socket));
}
| 2,194 | 694 |
#pragma once
#include "core/Implementation.hpp"
#include <map>
BRAINFUCPPK_BEGIN
enum class StandardToken : char
{
IncrementPointer = '>',
DecrementPointer = '<',
IncrementValue = '+',
DecrementValue = '-',
Write = '.',
Read = ',',
BeginLoop = '[',
EndLoop = ']',
End,
};
class StandardImplementation : public Implementation
{
public:
StandardImplementation(const WarpableIterator<unsigned char>& pointer, std::ostream& output, std::istream& input);
protected:
virtual bool ResolveToken(const std::string& source, std::size_t& index) noexcept(false) override;
private:
void IncrementPointer(const std::string& source, std::size_t& index);
void DecrementPointer(const std::string& source, std::size_t& index);
void IncrementValue(const std::string& source, std::size_t& index);
void DecrementValue(const std::string& source, std::size_t& index);
void Write(const std::string& source, std::size_t& index);
void Read(const std::string& source, std::size_t& index);
void BeginLoop(const std::string& source, std::size_t& index);
void EndLoop(const std::string& source, std::size_t& index);
private:
/* The code isn't ready for that kind of thing yet. */
// bool IsThisLoopInfinite(const std::string& source, const std::size_t bracketPosition) const;
private:
std::map<std::size_t, std::size_t> m_LoopsPositions;
};
BRAINFUCPPK_END
| 1,469 | 468 |
/****************************
* Author: Sanghyeb(Sam) Lee
* Date: Jan/2013
* email: drminix@gmail.com
* Copyright 2013 Sang hyeb(Sam) Lee MIT License
*
* X-ray CT simulation & reconstruction
*****************************/
#include "SirtThread.h"
SirtThread::SirtThread(QObject *parent) :
QThread(parent)
{
}
SirtThread::SirtThread(drawingarea* tarea,int tsweeps,double trelaxation, int twhentoshow) :
maindrawingarea(tarea), sweeps(tsweeps), relaxation(trelaxation), whentoshow(twhentoshow) {
A = maindrawingarea->A; //A
x = new double[maindrawingarea->A_size.width()];
b = new double[maindrawingarea->sinogram_size.width()*maindrawingarea->sinogram_size.height()];
//setup it to running
running = true;
}
inline void swap(double** x1,double** x2) {
double* x_temp;
x_temp = *x1;
*x1 = *x2;
*x2 = x_temp;
}
void SirtThread::setupReturnBuffer(double **pBuffer) {
pX = pBuffer;
}
//perform art.
void SirtThread::run() {
//Ax = b
int a_row = this->maindrawingarea->A_size.height();
int a_column = this->maindrawingarea->A_size.width();
int x_row = a_column;
int b_row = a_row;
std::cout<<"SirtThread: started."<<std::endl;
int sino_width = maindrawingarea->sinogram_size.width();
int sino_height = maindrawingarea->sinogram_size.height();
//initialize x(estimate image) to zero
memset(x,0,sizeof(double)*x_row);
for(int i=0;i<sino_width;i++) {
//memcpy(dest,src, number of bytes)*/
memcpy(b+(sino_height*i),this->maindrawingarea->sinogram[i],sizeof(double)*sino_height);
}
//now perform ART
//main iteration.
double rs; //residual
double* diff = new double[a_row];
double Ax;
double* x_prev = new double[a_column];
for(int main_iterator=0;main_iterator<sweeps&&running==true;main_iterator++) {
//after this command, x_prev points to x, x point to new area
swap(&x_prev,&x);
for(int i=0;i<a_row;i++) {
//calculate Ax
Ax=0; //Ax
for(int j=0;j<a_column;j++) {
Ax+=A[i][j] * x_prev[j]; //Ax = Row(M) *1
}
diff[i]=b[i]-Ax; //Ax-b = Row(M)*1
}
for(int i=0;i<a_column;i++) {
double AtAx_B=0;
for(int j=0;j<a_row;j++) {
AtAx_B += A[j][i] * diff[j];
}
x[i]=x_prev[i]+(relaxation * AtAx_B);
}
//inform main window for availability
if(((main_iterator+1)%this->whentoshow)==0) {
if(*pX==NULL) { //if it is empty create it first
*pX = new double[a_column];
}
//copy the image value
memcpy(*pX,x,sizeof(double)*x_row);
//notify the main window
emit updateReady(main_iterator+1);
}
//work out residual.
rs=0;
for(int z=0;z<x_row;z++) {
rs +=fabs(this->maindrawingarea->matrix[z] -
x[z]);
}
emit singleiteration(main_iterator+1,rs);
}
}
| 3,078 | 1,127 |
#include <cassert>
#include <cstdio>
#include "DreamDaqEventUnpacker.hh"
#include "DreamDaqEvent.h"
#include "DaqModuleUnpackers.hh"
#include "myFIFO-IOp.h"
#include "myRawFile.h"
DreamDaqEventUnpacker::DreamDaqEventUnpacker() :
event_(0)
{
}
DreamDaqEventUnpacker::DreamDaqEventUnpacker(DreamDaqEvent* event) :
event_(0)
{
setDreamDaqEvent(event);
}
DreamDaqEventUnpacker::~DreamDaqEventUnpacker()
{
}
void DreamDaqEventUnpacker::setDreamDaqEvent(DreamDaqEvent* event)
{
packSeq_.clear();
if (event)
{
// The sequence of unpackers does not matter.
// The sequence of packers can be made correct
// by calling the "setPackingSequence" method.
packSeq_.push_back(std::make_pair(&event->TDC_0, &LeCroy1176_));
packSeq_.push_back(std::make_pair(&event->ADC_C1, &CaenV792_));
packSeq_.push_back(std::make_pair(&event->ADC_C2, &CaenV792_));
packSeq_.push_back(std::make_pair(&event->ADC_L, &LeCroy1182_));
packSeq_.push_back(std::make_pair(&event->SCA_0, &CaenV260_));
packSeq_.push_back(std::make_pair(&event->SCOPE_0, &TDS7254B_));
packSeq_.push_back(std::make_pair(&event->TSENS, &TemperatureSensors_));
}
event_ = event;
}
int DreamDaqEventUnpacker::setPackingSequence(
const unsigned *subEventIds, unsigned nIds)
{
UnpakerSequence ordered;
const unsigned n_packers = packSeq_.size();
int missing_packer = 0;
for (unsigned i=0; i<nIds; ++i)
{
const unsigned id = subEventIds[i];
unsigned packer_found = 0;
for (unsigned j=0; j<n_packers; ++j)
{
DreamDaqModule *module = packSeq_[j].first;
if (module->subEventId() == id)
{
packer_found = 1;
ordered.push_back(packSeq_[j]);
break;
}
}
if (!packer_found)
{
fprintf(stderr, "Failed to find unpacker for sub event id 0x%08x\n", id);
fflush(stderr);
missing_packer++;
}
}
packSeq_ = ordered;
return missing_packer;
}
int DreamDaqEventUnpacker::unpack(unsigned *eventData) const
{
int status = 0;
for (unsigned i=0; i<packSeq_.size(); ++i)
{
DreamDaqModule *module = packSeq_[i].first;
const int ustat = packSeq_[i].second->unpack(
event_->formatVersion, module, eventData);
if (ustat == NODATA)
module->setEnabled(false);
else
{
module->setEnabled(true);
if (ustat)
status = 1;
}
}
return status;
}
int DreamDaqEventUnpacker::pack(unsigned *buf, unsigned buflen) const
{
// Create the event header
EventHeader evh;
evh.evmark = EVENTMARKER;
evh.evhsiz = sizeof(EventHeader);
evh.evnum = event_->eventNumber;
evh.spill = event_->spillNumber;
evh.tsec = event_->timeSec;
evh.tusec = event_->timeUSec;
// Pack the event header
int wordcount = sizeof(EventHeader)/sizeof(unsigned);
assert(buflen > (unsigned)wordcount);
memcpy(buf, &evh, sizeof(EventHeader));
// Pack the modules
for (unsigned i=0; i<packSeq_.size(); ++i)
{
DreamDaqModule *module = packSeq_[i].first;
if (module->enabled())
{
int sz = packSeq_[i].second->pack(
event_->formatVersion, module,
buf+wordcount, buflen-wordcount);
if (sz < 0)
return sz;
else
wordcount += sz;
}
}
// Set the correct event size (in bytes)
buf[offsetof(EventHeader, evsiz)/sizeof(unsigned)] =
wordcount*sizeof(unsigned);
return wordcount;
}
| 3,743 | 1,305 |
/*
* NAppGUI Cross-platform C SDK
* 2015-2021 Francisco Garcia Collado
* MIT Licence
* https://nappgui.com/en/legal/license.html
*
* File: setst.hpp
*
*/
/* Set of structures */
#ifndef __SETST_HPP__
#define __SETST_HPP__
#include "bstd.h"
#include "nowarn.hxx"
#include <typeinfo>
#include "warn.hxx"
template<class type>
struct SetSt
{
static SetSt<type>* create(int(func_compare)(const type*, const type*));
static void destroy(SetSt<type> **set, void(*func_remove)(type*));
static uint32_t size(const SetSt<type> *set);
static type* get(SetSt<type> *set, const type *key);
static const type* get(const SetSt<type> *set, const type *key);
static bool_t ddelete(SetSt<type> *set, const type *key, void(*func_remove)(type*));
static type* first(SetSt<type> *set);
static const type* first(const SetSt<type> *set);
static type* last(SetSt<type> *set);
static const type* last(const SetSt<type> *set);
static type* next(SetSt<type> *set);
static const type* next(const SetSt<type> *set);
static type* prev(SetSt<type> *set);
static const type* prev(const SetSt<type> *set);
#if defined __ASSERTS__
// Only for debuggers inspector (non used)
template<class ttype>
struct TypeNode
{
uint32_t rb;
struct TypeNode<ttype> *left;
struct TypeNode<ttype> *right;
ttype data;
};
uint32_t elems;
uint16_t esize;
uint16_t ksize;
TypeNode<type> *root;
FPtr_compare func_compare;
#endif
};
/*---------------------------------------------------------------------------*/
template<typename type>
static const char_t* i_settype(void)
{
static char_t dtype[64];
bstd_sprintf(dtype, sizeof(dtype), "SetSt<%s>", typeid(type).name());
return dtype;
}
/*---------------------------------------------------------------------------*/
template<typename type>
SetSt<type>* SetSt<type>::create(int(func_compare)(const type*, const type*))
{
return (SetSt<type>*)rbtree_create((FPtr_compare)func_compare, (uint16_t)sizeof(type), 0, i_settype<type>());
}
/*---------------------------------------------------------------------------*/
template<typename type>
void SetSt<type>::destroy(SetSt<type> **set, void(*func_remove)(type*))
{
rbtree_destroy((RBTree**)set, (FPtr_remove)func_remove, NULL, i_settype<type>());
}
/*---------------------------------------------------------------------------*/
template<typename type>
uint32_t SetSt<type>::size(const SetSt<type> *set)
{
return rbtree_size((const RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::get(SetSt<type> *set, const type *key)
{
return (type*)rbtree_get((RBTree*)set, (const void*)key, FALSE);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::get(const SetSt<type> *set, const type *key)
{
return (const type*)rbtree_get((RBTree*)set, (const void*)key, FALSE);
}
/*---------------------------------------------------------------------------*/
template<typename type>
bool_t SetSt<type>::ddelete(SetSt<type> *set, const type *key, void(*func_remove)(type*))
{
return rbtree_delete((RBTree*)set, (const void*)key, (FPtr_remove)func_remove, NULL);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::first(SetSt<type> *set)
{
return (type*)rbtree_first((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::first(const SetSt<type> *set)
{
return (const type*)rbtree_first((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::last(SetSt<type> *set)
{
return (type*)rbtree_last((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::last(const SetSt<type> *set)
{
return (const type*)rbtree_last((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::next(SetSt<type> *set)
{
return (type*)rbtree_next((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::next(const SetSt<type> *set)
{
return (const type*)rbtree_next((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
type* SetSt<type>::prev(SetSt<type> *set)
{
return (type*)rbtree_prev((RBTree*)set);
}
/*---------------------------------------------------------------------------*/
template<typename type>
const type* SetSt<type>::prev(const SetSt<type> *set)
{
return (const type*)rbtree_prev((RBTree*)set);
}
#endif
| 4,904 | 1,607 |
/*
# g++ --std=c++20 -pthread -o ../_build/cpp/types_is_pointer_interconvertible_with_class.exe ./cpp/types_is_pointer_interconvertible_with_class.cpp && (cd ../_build/cpp/;./types_is_pointer_interconvertible_with_class.exe)
https://en.cppreference.com/w/cpp/types/is_pointer_interconvertible_with_class
*/
#include <type_traits>
#include <iostream>
struct Foo { int x; };
struct Bar { int y; };
struct Baz : Foo, Bar {}; // not standard-layout
int main()
{
std::cout << std::boolalpha
<< std::is_same_v<decltype(&Baz::x), int Baz::*>
<< std::is_pointer_interconvertible_with_class(&Baz::x) << '\n'
<< std::is_pointer_interconvertible_with_class<Baz>(&Baz::x) << '\n';
}
| 700 | 259 |
#include "stdafx.h"
using namespace MisakaTool;
//extracts all files into the CWD
void MisakaArchive::extractAllFiles(std::vector<short> &index, std::vector<char> &buffer, bool uncompress_images ){
int prev = 0;
for (auto i : index){
auto pos = std::lower_bound(index.begin(), index.end(), i);
pos++;
int size = (*pos - i) * block_size;
using of = std::ofstream;
//fout.write(&buffer[i*block_size], size);
std::vector<char> file_compressed(buffer.begin() + i*block_size, buffer.begin() + i*block_size + size + 1);
std::vector<char> file_uncompressed = decodeRLE2(file_compressed);
std::string extension(&file_uncompressed[0], &file_uncompressed[3]);
std::stringstream name;
name << i << "." << extension;
std::ofstream fout(name.str(), of::binary | of::out);
fout.write(&file_uncompressed[0], file_uncompressed.size());
fout.flush();
fout.close();
if (extension.compare("SHT") == 0){
name << ".ppm";
writePNM(file_uncompressed, name.str());
}
}
}
std::vector<char> MisakaArchive::readFullFile(std::string name){
std::ifstream is(name, std::ifstream::binary);
std::vector<char> buffer;
if (is) {
// get length of file:
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(0, is.beg);
std::cout << "Reading " << length << " characters... " << std::endl;
// read data as a block:
buffer.resize(length);
is.read(&(buffer[0]), length);
if (is)
std::cout << "all characters read successfully." << std::endl;
else
std::cout << "error: only " << is.gcount() << " could be read" << std::endl;
is.close();
}
return buffer;
}
//returns an index of files. The index contains the sector numbers at which the files start
std::vector<short> MisakaArchive::getFiles(char *buffer){
int files = reinterpret_cast<int &>(buffer[0]);
std::vector<short> vec(files);
for (int i = 0; i < files; i++){
vec[i] = reinterpret_cast<short&>(buffer[file_table_offset + file_table_entry_width * i]);
}
return vec;
}
//decode the custom RLE CONTAINS ERRORS ATM
std::vector<char> MisakaArchive::decodeRLE(std::vector<char> buffer)
{
const char BACK_FLAG = 0x80;
const char REPEAT_FLAG = 0x40;
const char LHDR_FLAG = 0x20;
std::vector<char> result;
int cur_src = 0;
int cur_dst = 0;
int cur_bck = 0;
while (cur_src < buffer.size()){
char src = buffer[cur_src++];
int amt = 0;
if (src & BACK_FLAG){
amt = (src & 0x60) >> 5;
amt += 4;
cur_bck = (src & 0x1F) << 8 | reinterpret_cast<unsigned char &>(buffer[cur_src++]);
assert(cur_bck>0);
cur_bck = cur_dst - cur_bck;
int subcopy = amt;
while (cur_dst - cur_bck < subcopy){
int subcopy_amt = (cur_dst - cur_bck);
copy_data(result, result, cur_dst, cur_bck, subcopy_amt);
subcopy -= subcopy_amt;
cur_bck += subcopy_amt;
cur_dst += subcopy_amt;
}
copy_data(result, result, cur_dst, cur_bck, subcopy);
cur_bck += subcopy;
cur_dst += subcopy;
}
else if ((src & 0xE0) == 0x60)
{
amt = src & 0x1F;
amt += 4;
assert(cur_dst > cur_bck);
int subcopy = amt;
while (cur_dst - cur_bck < subcopy){
int subcopy_amt = (cur_dst - cur_bck);
copy_data(result, result, cur_dst, cur_bck, subcopy_amt);
subcopy -= subcopy_amt;
cur_bck += subcopy_amt;
cur_dst += subcopy_amt;
}
copy_data(result, result, cur_dst, cur_bck, subcopy);
cur_bck += subcopy;
cur_dst += subcopy;
}
else if (src & REPEAT_FLAG){
amt = (src & 0x10) ? (src & 0x0F) << 8 | reinterpret_cast<unsigned char &>(buffer[cur_src++]) : src & 0x1F;
amt += 4;
result.insert(result.begin() + cur_dst, amt, buffer[cur_src++]);
cur_dst += amt;
}
else if (src & LHDR_FLAG){
amt = ((src & 0x1F) << 8) | reinterpret_cast<unsigned char &>(buffer[cur_src++]);
copy_data(result, buffer, cur_dst, cur_src, amt);
cur_src += amt;
cur_dst += amt;
}
else if (src == 0x00){
break;
}
else
{
amt = src & 0x1F;
copy_data(result, buffer, cur_dst, cur_src, amt);
cur_src += amt;
cur_dst += amt;
}
}
return result;
}
//decode the custom RLE, one to one translation of the MIPS code
std::vector<char> MisakaArchive::decodeRLE2(std::vector<char> &buff){
MipsCpy mips;
std::vector<char> result;
//result.resize(buff.size()*20);
long a0, a1, a2, a3, v0, v1, t0, t1, t2;
bool cond;
a0 = 0;//reinterpret_cast<long>(&(buff[0]));//position in src
a1 = 0x40000000;//reinterpret_cast<long>(&(result[0]));//position in target
mips.container = &result;
mips.container2 = &buff;
// move a2,a0
a2 = a0;
// lbu a0,0x0(a2)
a0 = mips.lbu(a2);
// move a3,a1
a3 = a1;
// li t2,0x60
t2 = 0x60;
// beq zero,a0,jmp1
cond = (a0 == 0);
// addiu t0,a2,0x1
t0 = a2 + 1; if (cond) goto jmp1;
//jmp7: seb v0,a0
jmp7:
v0 = a0 & 0x80;
// bltz v0,jmp2
cond = (v0);
// andi v0,a0,0x40
v0 = a0 & 0x40; if (cond) goto jmp2;
// beql zero,v0,jmp3
cond = (v0 == 0);
// andi v0,a0,0x20
v0 = a0 & 0x20; if (cond) goto jmp3;
// andi v0,a0,0xF
v0 = a0 & 0xF;
// andi v1,a0,0x10
v1 = a0 & 0x10;
// beq zero,v1,jmp4
cond = (v1 == 0);
// addiu v0,v0,0x4
v0 = v0 + 0x4; if (cond) goto jmp4;
// lbu v1,0x1(a2)
v1 = mips.lbu(a2 + 1);
// andi v0,a0,0xF
v0 = a0 & 0xF;
// sll v0,v0,0x8
v0 = v0 << 0x8;
// or v1,v1,v0
v1 = v1 | v0;
// addiu t0,a2,0x2
t0 = a2 + 0x2;
// addiu v0,v1,0x4
v0 = v1 + 0x4;
//jmp4: lbu v1,0x0(t0)
jmp4:
v1 = mips.lbu(t0);
// blez v0,jmp5
cond = (v0 == 0);
// addiu t0,t0,0x1
t0 = t0 + 1; if (cond) goto jmp5;
// move a0,a3
a0 = a3;
// addu v0,v0,a3
v0 = v0 + a3;
// sb v1,0x0(a0)
mips.sb(v1, a0);
//jmp6: addiu a0,a0,0x1
jmp6:
a0 = a0 + 1;
// bnel v0,a0,jmp6
cond = (v0 != a0);
// sb v1,0x0(a0)
mips.sb(v1, a0); if (cond) goto jmp6;
// move a3,a0
a3 = a0;
//jmp5: move a2,t0
jmp5:
a2 = t0;
//jmp10: lbu a0,0x0(a2)
jmp10:
a0 = mips.lbu(a2);
// bne zero,a0,jmp7
cond = (a0 != 0);
// addiu t0,a2,0x1
t0 = a2 + 1; if (cond) goto jmp7;
//jmp1: lui v0,0x89E
jmp1:
v0 = 0x89E << 16;
// subu a0,a3,a1
a0 = a3 - a1;
// sw t0,-0x44F0(v0)
//sw(t0, v0 - 0x44F0);//--------------------------------------------------------------
// lui v1,0x89E
v1 = 0x89E;
// lui v0,0x89E
v0 = 0x89E;
// sw a0,-0x44F8(v1)
//sw(a0, v1 - 0x44F8);//----------------------------------------------------------------
// jr ra
// sw a3,-0x44F4(v0)
//sw(a3, v0 - 0x44F4);//-----------------------------------------------------------------
result.resize(a0);
return result;
//jmp3: beq zero,v0,jmp8
jmp3:
cond = (v0 == 0);
// andi v1,a0,0x1F
v1 = a0 & 0x1F; if (cond) goto jmp8;
// lbu v1,0x1(a2)
v1 = mips.lbu(a2 + 1);
// andi v0,a0,0x1F
v0 = a0 & 0x1F;
// sll v0,v0,0x8
v0 = v0 << 8;
// or v1,v1,v0
v1 = v1 | v0;
// addiu t0,a2,0x2
t0 = a2 + 2;
//jmp8: move a2,a3
jmp8:
a2 = a3;
// blez v1,jmp5
cond = (v1 <= 0);
// addu t1,v1,a3
t1 = v1 + a3; if (cond) goto jmp5;
//jmp9: lbu v0,0x0(t0)
jmp9:
v0 = mips.lbu(t0);
// sb v0,0x0(a2)
mips.sb(v0, a2);
// addiu a2,a2,0x1
a2 = a2 + 1;
// bne a2,t1,jmp9
cond = (a2 != t1);
// addiu t0,t0,0x1
t0 = t0 + 1; if (cond) goto jmp9;
// move a3,t1
a3 = t1;
// j jmp10
cond = true;
// move a2,t0
a2 = t0; if (cond) goto jmp10;
//jmp2: lbu v0,0x1(a2)
jmp2:
v0 = mips.lbu(a2 + 1);
// andi v1,a0,0x1F
v1 = a0 & 0x1F;
// sll v1,v1,0x8
v1 = v1 << 8;
// ext a0,a0,0x5,0x2
a0 = (a0 & 0x60) >> 5;
// or v0,v0,v1
v0 = v0 | v1;
// addiu v1,a0,0x4
v1 = a0 + 0x4;
// addiu t0,a2,0x2
t0 = a2 + 0x2;
// blez v1,jmp11
cond = (v1 <= 0);
// subu a2,a3,v0
a2 = a3 - v0; if (cond) goto jmp11;
// move a0,a3
a0 = a3;
// addu v1,v1,a3
v1 = v1 + a3;
//jmp12: lbu v0,0x0(a2)
jmp12:
v0 = mips.lbu(a2);
// sb v0,0x0(a0)
mips.sb(v0, a0);
// addiu a0,a0,0x1
a0 = a0 + 1;
// bne v1,a0,jmp12:
cond = (v1 != a0);
// addiu a2,a2,0x1
a2 = a2 + 1; if (cond) goto jmp12;
// move a3,a0
a3 = a0;
//jmp11: lbu v1,0x0(t0)
jmp11:
v1 = mips.lbu(t0);
// andi v0,v1,0xE0
v0 = v1 & 0xE0;
// bne t2,v0,jmp5
cond = (t2 != v0);
// andi v0,v1,0x1F
v0 = v1 & 0x1F; if (cond) goto jmp5;
// blez v0,jmp11
cond = (v0 <= 0);
// addiu t0,t0,0x1
t0 = t0 + 1; if (cond) goto jmp11;
// move v1,a2
v1 = a2;
// addu a0,a2,v0
a0 = a2 + v0;
//jmp13: lbu v0,0x0(v1)
jmp13:
v0 = mips.lbu(v1);
// addiu v1,v1,0x1
v1 = v1 + 1;
// sb v0,0x0(a3)
mips.sb(v0, a3);
// bne a0,v1,jmp13
cond = (a0 != v1);
// addiu a3,a3,0x1
a3 = a3 + 1; if (cond) goto jmp13;
// j jmp11
cond = true;
// move a2,v1
a2 = v1; if (cond) goto jmp11;
return result;
} | 8,565 | 4,922 |
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file was generated by Djinni from my_record.djinni
#include <iostream> // for debugging
#include <cassert>
#include "djinni/cwrapper/wrapper_marshal.hpp"
#include "../cpp-headers/my_record.hpp"
#include "dh__map_string_int32_t.hpp"
#include "dh__my_record.hpp"
#include "dh__set_string.hpp"
static void(*s_callback_map_string_int32_t___delete)(DjinniObjectHandle *);
void map_string_int32_t_add_callback___delete(void(* ptr)(DjinniObjectHandle *)) {
s_callback_map_string_int32_t___delete = ptr;
}
void map_string_int32_t___delete(DjinniObjectHandle * drh) {
s_callback_map_string_int32_t___delete(drh);
}
void optional_map_string_int32_t___delete(DjinniOptionalObjectHandle * drh) {
s_callback_map_string_int32_t___delete((DjinniObjectHandle *) drh);
}
static int32_t ( * s_callback_map_string_int32_t__get_value)(DjinniObjectHandle *, DjinniString *);
void map_string_int32_t_add_callback__get_value(int32_t( * ptr)(DjinniObjectHandle *, DjinniString *)) {
s_callback_map_string_int32_t__get_value = ptr;
}
static size_t ( * s_callback_map_string_int32_t__get_size)(DjinniObjectHandle *);
void map_string_int32_t_add_callback__get_size(size_t( * ptr)(DjinniObjectHandle *)) {
s_callback_map_string_int32_t__get_size = ptr;
}
static DjinniObjectHandle * ( * s_callback_map_string_int32_t__create)(void);
void map_string_int32_t_add_callback__create(DjinniObjectHandle *( * ptr)(void)) {
s_callback_map_string_int32_t__create = ptr;
}
static void ( * s_callback_map_string_int32_t__add)(DjinniObjectHandle *, DjinniString *, int32_t);
void map_string_int32_t_add_callback__add(void( * ptr)(DjinniObjectHandle *, DjinniString *, int32_t)) {
s_callback_map_string_int32_t__add = ptr;
}
static DjinniString * ( * s_callback_map_string_int32_t__next)(DjinniObjectHandle *);
void map_string_int32_t_add_callback__next(DjinniString *( * ptr)(DjinniObjectHandle *)) {
s_callback_map_string_int32_t__next = ptr;
}
djinni::Handle<DjinniObjectHandle> DjinniMapStringInt32T::fromCpp(const std::unordered_map<std::string, int32_t> & dc) {
djinni::Handle<DjinniObjectHandle> _handle(s_callback_map_string_int32_t__create(), & map_string_int32_t___delete);
for (const auto & it : dc) {
auto _key = DjinniString::fromCpp(it.first);
s_callback_map_string_int32_t__add(_handle.get(), _key.release(), it.second);
}
return _handle;
}
std::unordered_map<std::string, int32_t> DjinniMapStringInt32T::toCpp(djinni::Handle<DjinniObjectHandle> dh) {
std::unordered_map<std::string, int32_t>_ret;
size_t size = s_callback_map_string_int32_t__get_size(dh.get());
for (int i = 0; i < size; i++) {
auto _key_c = std::unique_ptr<DjinniString>(s_callback_map_string_int32_t__next(dh.get())); // key that would potentially be surrounded by unique pointer
auto _val = s_callback_map_string_int32_t__get_value(dh.get(), _key_c.get());
auto _key = DjinniString::toCpp(std::move(_key_c));
_ret.emplace(std::move(_key), std::move(_val));
}
return _ret;
}
djinni::Handle<DjinniOptionalObjectHandle> DjinniMapStringInt32T::fromCpp(std::optional<std::unordered_map<std::string, int32_t>> dc) {
if (!dc) {
return nullptr;
}
return djinni::optionals::toOptionalHandle(DjinniMapStringInt32T::fromCpp(std::move(* dc)), optional_map_string_int32_t___delete);
}
std::optional<std::unordered_map<std::string, int32_t>>DjinniMapStringInt32T::toCpp(djinni::Handle<DjinniOptionalObjectHandle> dh) {
if (dh) {
return std::optional<std::unordered_map<std::string, int32_t>>(DjinniMapStringInt32T::toCpp(djinni::optionals::fromOptionalHandle(std::move(dh), map_string_int32_t___delete)));
}
return {};
}
| 3,779 | 1,486 |
#include "swSphere.h"
bool solveQuadratic(float A, float B, float C, float &t0, float &t1) {
float d = B * B - 4.0f * A * C;
if (d < 0.0f) return false;
d = std::sqrt(d);
t0 = (-B - d) / (2.0f * A);
t1 = (-B + d) / (2.0f * A);
return true;
}
bool swSphere::intersect(const swRay &r, swIntersection &isect) {
swVec3 o = r.orig - mCenter;
swVec3 d = r.dir; // - sphere.mCenter;
// Compute polynom coefficients.
float A = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; // d dot d ?
float B =
2.0f * (d[0] * o[0] + d[1] * o[1] + d[2] * o[2]); // isn't this d dot o ?
float C = o[0] * o[0] + o[1] * o[1] + o[2] * o[2] -
mRadius * mRadius; // and o dot o ?
// Solve quadratic equation for ray enter/exit point t0,t1 respectively.
float t0, t1;
if (!solveQuadratic(A, B, C, t0, t1))
return false; // no real solutions -> ray missed
if (t0 > r.maxT || t1 < r.minT) {
return false; // sphere before/after ray
}
if (t0 < r.minT && t1 > r.maxT) return false; // ray inside sphere
isect.mHitTime = t0 < r.minT ? t1 : t0;
isect.mNormal = (o + (isect.mHitTime) * d) * (1.0f / mRadius);
isect.mNormal.normalize();
isect.mFrontFacing = (-d * isect.mNormal) > 0.0f;
if (!isect.mFrontFacing) isect.mNormal = -isect.mNormal;
isect.mPosition = o + (isect.mHitTime) * d + mCenter;
isect.mMaterial = mMaterial;
isect.mRay = r;
return true;
}
| 1,464 | 636 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
// RenderSystem implementation
// Note that most of this class is abstract since
// we cannot know how to implement the behaviour without
// being aware of the 3D API. However there are a few
// simple functions which can have a base implementation
#include "OgreRenderSystem.h"
#include "Compositor/OgreCompositorManager2.h"
#include "Compositor/OgreCompositorWorkspace.h"
#include "OgreDepthBuffer.h"
#include "OgreDescriptorSetUav.h"
#include "OgreException.h"
#include "OgreHardwareOcclusionQuery.h"
#include "OgreHlmsPso.h"
#include "OgreIteratorWrappers.h"
#include "OgreLogManager.h"
#include "OgreLwString.h"
#include "OgreMaterialManager.h"
#include "OgreProfiler.h"
#include "OgreRoot.h"
#include "OgreTextureGpuManager.h"
#include "OgreViewport.h"
#include "OgreWindow.h"
#include "Vao/OgreUavBufferPacked.h"
#include "Vao/OgreVaoManager.h"
#include "Vao/OgreVertexArrayObject.h"
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
# include "renderdoc/renderdoc_app.h"
# if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
# define WIN32_LEAN_AND_MEAN
# define VC_EXTRALEAN
# define NOMINMAX
# include <windows.h>
# endif
#endif
namespace Ogre
{
RenderSystem::ListenerList RenderSystem::msSharedEventListeners;
//-----------------------------------------------------------------------
RenderSystem::RenderSystem() :
mCurrentRenderPassDescriptor( 0 ),
mMaxBoundViewports( 16u ),
mVaoManager( 0 ),
mTextureGpuManager( 0 )
#if OGRE_DEBUG_MODE >= OGRE_DEBUG_HIGH
,
mDebugShaders( true )
#else
,
mDebugShaders( false )
#endif
,
mWBuffer( false ),
mInvertVertexWinding( false ),
mDisabledTexUnitsFrom( 0 ),
mCurrentPassIterationCount( 0 ),
mCurrentPassIterationNum( 0 ),
mDerivedDepthBias( false ),
mDerivedDepthBiasBase( 0.0f ),
mDerivedDepthBiasMultiplier( 0.0f ),
mDerivedDepthBiasSlopeScale( 0.0f ),
mUavRenderingDirty( false ),
mUavStartingSlot( 1 ),
mUavRenderingDescSet( 0 ),
mGlobalInstanceVertexBufferVertexDeclaration( NULL ),
mGlobalNumberOfInstances( 1 ),
mRenderDocApi( 0 ),
mVertexProgramBound( false ),
mGeometryProgramBound( false ),
mFragmentProgramBound( false ),
mTessellationHullProgramBound( false ),
mTessellationDomainProgramBound( false ),
mComputeProgramBound( false ),
mClipPlanesDirty( true ),
mRealCapabilities( 0 ),
mCurrentCapabilities( 0 ),
mUseCustomCapabilities( false ),
mNativeShadingLanguageVersion( 0 ),
mTexProjRelative( false ),
mTexProjRelativeOrigin( Vector3::ZERO ),
mReverseDepth( true ),
mInvertedClipSpaceY( false )
{
mEventNames.push_back( "RenderSystemCapabilitiesCreated" );
}
//-----------------------------------------------------------------------
RenderSystem::~RenderSystem()
{
shutdown();
OGRE_DELETE mRealCapabilities;
mRealCapabilities = 0;
// Current capabilities managed externally
mCurrentCapabilities = 0;
}
//-----------------------------------------------------------------------
Window *RenderSystem::_initialise( bool autoCreateWindow, const String &windowTitle )
{
// Have I been registered by call to Root::setRenderSystem?
/** Don't do this anymore, just allow via Root
RenderSystem* regPtr = Root::getSingleton().getRenderSystem();
if (!regPtr || regPtr != this)
// Register self - library user has come to me direct
Root::getSingleton().setRenderSystem(this);
*/
// Subclasses should take it from here
// They should ALL call this superclass method from
// their own initialise() implementations.
mVertexProgramBound = false;
mGeometryProgramBound = false;
mFragmentProgramBound = false;
mTessellationHullProgramBound = false;
mTessellationDomainProgramBound = false;
mComputeProgramBound = false;
return 0;
}
//---------------------------------------------------------------------------------------------
void RenderSystem::useCustomRenderSystemCapabilities( RenderSystemCapabilities *capabilities )
{
if( mRealCapabilities != 0 )
{
OGRE_EXCEPT(
Exception::ERR_INTERNAL_ERROR,
"Custom render capabilities must be set before the RenderSystem is initialised.",
"RenderSystem::useCustomRenderSystemCapabilities" );
}
mCurrentCapabilities = capabilities;
mUseCustomCapabilities = true;
}
//---------------------------------------------------------------------------------------------
bool RenderSystem::_createRenderWindows( const RenderWindowDescriptionList &renderWindowDescriptions,
WindowList &createdWindows )
{
unsigned int fullscreenWindowsCount = 0;
// Grab some information and avoid duplicate render windows.
for( unsigned int nWindow = 0; nWindow < renderWindowDescriptions.size(); ++nWindow )
{
const RenderWindowDescription *curDesc = &renderWindowDescriptions[nWindow];
// Count full screen windows.
if( curDesc->useFullScreen )
fullscreenWindowsCount++;
bool renderWindowFound = false;
for( unsigned int nSecWindow = nWindow + 1; nSecWindow < renderWindowDescriptions.size();
++nSecWindow )
{
if( curDesc->name == renderWindowDescriptions[nSecWindow].name )
{
renderWindowFound = true;
break;
}
}
// Make sure we don't already have a render target of the
// same name as the one supplied
if( renderWindowFound )
{
String msg;
msg = "A render target of the same name '" + String( curDesc->name ) +
"' already "
"exists. You cannot create a new window with this name.";
OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, msg, "RenderSystem::createRenderWindow" );
}
}
// Case we have to create some full screen rendering windows.
if( fullscreenWindowsCount > 0 )
{
// Can not mix full screen and windowed rendering windows.
if( fullscreenWindowsCount != renderWindowDescriptions.size() )
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
"Can not create mix of full screen and windowed rendering windows",
"RenderSystem::createRenderWindows" );
}
}
return true;
}
//---------------------------------------------------------------------------------------------
void RenderSystem::destroyRenderWindow( Window *window )
{
WindowSet::iterator itor = mWindows.find( window );
if( itor == mWindows.end() )
{
OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND,
"Window does not belong to us or is already deleted!",
"RenderSystem::destroyRenderWindow" );
}
mWindows.erase( window );
OGRE_DELETE window;
}
//-----------------------------------------------------------------------
void RenderSystem::_setPipelineStateObject( const HlmsPso *pso )
{
assert( ( !pso || pso->rsData ) &&
"The PipelineStateObject must have been created via "
"RenderSystem::_hlmsPipelineStateObjectCreated!" );
// Disable previous state
mActiveVertexGpuProgramParameters.reset();
mActiveGeometryGpuProgramParameters.reset();
mActiveTessellationHullGpuProgramParameters.reset();
mActiveTessellationDomainGpuProgramParameters.reset();
mActiveFragmentGpuProgramParameters.reset();
mActiveComputeGpuProgramParameters.reset();
if( mVertexProgramBound && !mClipPlanes.empty() )
mClipPlanesDirty = true;
mVertexProgramBound = false;
mGeometryProgramBound = false;
mFragmentProgramBound = false;
mTessellationHullProgramBound = false;
mTessellationDomainProgramBound = false;
mComputeProgramBound = false;
// Derived class must set new state
}
//-----------------------------------------------------------------------
void RenderSystem::_setTextureUnitSettings( size_t texUnit, TextureUnitState &tl )
{
// This method is only ever called to set a texture unit to valid details
// The method _disableTextureUnit is called to turn a unit off
TextureGpu *tex = tl._getTexturePtr();
bool isValidBinding = false;
if( mCurrentCapabilities->hasCapability( RSC_COMPLETE_TEXTURE_BINDING ) )
_setBindingType( tl.getBindingType() );
// Vertex texture binding?
if( mCurrentCapabilities->hasCapability( RSC_VERTEX_TEXTURE_FETCH ) &&
!mCurrentCapabilities->getVertexTextureUnitsShared() )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_VERTEX )
{
// Bind vertex texture
_setVertexTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setVertexTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( mCurrentCapabilities->hasCapability( RSC_GEOMETRY_PROGRAM ) )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_GEOMETRY )
{
// Bind vertex texture
_setGeometryTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setGeometryTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( mCurrentCapabilities->hasCapability( RSC_TESSELLATION_DOMAIN_PROGRAM ) )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_TESSELLATION_DOMAIN )
{
// Bind vertex texture
_setTessellationDomainTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setTessellationDomainTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( mCurrentCapabilities->hasCapability( RSC_TESSELLATION_HULL_PROGRAM ) )
{
isValidBinding = true;
if( tl.getBindingType() == TextureUnitState::BT_TESSELLATION_HULL )
{
// Bind vertex texture
_setTessellationHullTexture( texUnit, tex );
// bind nothing to fragment unit (hardware isn't shared but fragment
// unit can't be using the same index
_setTexture( texUnit, 0, false );
}
else
{
// vice versa
_setTessellationHullTexture( texUnit, 0 );
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
}
if( !isValidBinding )
{
// Shared vertex / fragment textures or no vertex texture support
// Bind texture (may be blank)
_setTexture( texUnit, tex,
mCurrentRenderPassDescriptor->mDepth.texture &&
mCurrentRenderPassDescriptor->mDepth.texture == tex );
}
_setHlmsSamplerblock( (uint8)texUnit, tl.getSamplerblock() );
// Set blend modes
// Note, colour before alpha is important
_setTextureBlendMode( texUnit, tl.getColourBlendMode() );
_setTextureBlendMode( texUnit, tl.getAlphaBlendMode() );
// Set texture effects
TextureUnitState::EffectMap::iterator effi;
// Iterate over new effects
bool anyCalcs = false;
for( effi = tl.mEffects.begin(); effi != tl.mEffects.end(); ++effi )
{
switch( effi->second.type )
{
case TextureUnitState::ET_ENVIRONMENT_MAP:
if( effi->second.subtype == TextureUnitState::ENV_CURVED )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP );
anyCalcs = true;
}
else if( effi->second.subtype == TextureUnitState::ENV_PLANAR )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_PLANAR );
anyCalcs = true;
}
else if( effi->second.subtype == TextureUnitState::ENV_REFLECTION )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_REFLECTION );
anyCalcs = true;
}
else if( effi->second.subtype == TextureUnitState::ENV_NORMAL )
{
_setTextureCoordCalculation( texUnit, TEXCALC_ENVIRONMENT_MAP_NORMAL );
anyCalcs = true;
}
break;
case TextureUnitState::ET_UVSCROLL:
case TextureUnitState::ET_USCROLL:
case TextureUnitState::ET_VSCROLL:
case TextureUnitState::ET_ROTATE:
case TextureUnitState::ET_TRANSFORM:
break;
case TextureUnitState::ET_PROJECTIVE_TEXTURE:
_setTextureCoordCalculation( texUnit, TEXCALC_PROJECTIVE_TEXTURE, effi->second.frustum );
anyCalcs = true;
break;
}
}
// Ensure any previous texcoord calc settings are reset if there are now none
if( !anyCalcs )
{
_setTextureCoordCalculation( texUnit, TEXCALC_NONE );
}
// Change tetxure matrix
_setTextureMatrix( texUnit, tl.getTextureTransform() );
}
//-----------------------------------------------------------------------
void RenderSystem::_setBindingType( TextureUnitState::BindingType bindingType )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support binding texture to other shaders then fragment",
"RenderSystem::_setBindingType" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setVertexTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate vertex texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setVertexTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setGeometryTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate geometry texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setGeometryTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setTessellationHullTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate tessellation hull texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setTessellationHullTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::_setTessellationDomainTexture( size_t unit, TextureGpu *tex )
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"This rendersystem does not support separate tessellation domain texture samplers, "
"you should use the regular texture samplers which are shared between "
"the vertex and fragment units.",
"RenderSystem::_setTessellationDomainTexture" );
}
//-----------------------------------------------------------------------
void RenderSystem::destroyRenderPassDescriptor( RenderPassDescriptor *renderPassDesc )
{
RenderPassDescriptorSet::iterator itor = mRenderPassDescs.find( renderPassDesc );
assert( itor != mRenderPassDescs.end() && "Already destroyed?" );
if( itor != mRenderPassDescs.end() )
mRenderPassDescs.erase( itor );
if( renderPassDesc->mDepth.texture )
{
_dereferenceSharedDepthBuffer( renderPassDesc->mDepth.texture );
if( renderPassDesc->mStencil.texture &&
renderPassDesc->mStencil.texture == renderPassDesc->mDepth.texture )
{
_dereferenceSharedDepthBuffer( renderPassDesc->mStencil.texture );
renderPassDesc->mStencil.texture = 0;
}
}
if( renderPassDesc->mStencil.texture )
{
_dereferenceSharedDepthBuffer( renderPassDesc->mStencil.texture );
renderPassDesc->mStencil.texture = 0;
}
delete renderPassDesc;
}
//---------------------------------------------------------------------
void RenderSystem::destroyAllRenderPassDescriptors()
{
RenderPassDescriptorSet::const_iterator itor = mRenderPassDescs.begin();
RenderPassDescriptorSet::const_iterator endt = mRenderPassDescs.end();
while( itor != endt )
delete *itor++;
mRenderPassDescs.clear();
}
//---------------------------------------------------------------------
void RenderSystem::beginRenderPassDescriptor( RenderPassDescriptor *desc, TextureGpu *anyTarget,
uint8 mipLevel, const Vector4 *viewportSizes,
const Vector4 *scissors, uint32 numViewports,
bool overlaysEnabled, bool warnIfRtvWasFlushed )
{
assert( anyTarget );
mCurrentRenderPassDescriptor = desc;
for( size_t i = 0; i < numViewports; ++i )
{
mCurrentRenderViewport[i].setDimensions( anyTarget, viewportSizes[i], scissors[i],
mipLevel );
mCurrentRenderViewport[i].setOverlaysEnabled( overlaysEnabled );
}
mMaxBoundViewports = numViewports;
}
//---------------------------------------------------------------------
void RenderSystem::executeRenderPassDescriptorDelayedActions() {}
//---------------------------------------------------------------------
void RenderSystem::endRenderPassDescriptor()
{
mCurrentRenderPassDescriptor = 0;
const size_t maxBoundViewports = mMaxBoundViewports;
for( size_t i = 0; i < maxBoundViewports; ++i )
mCurrentRenderViewport[i].setDimensions( 0, Vector4::ZERO, Vector4::ZERO, 0u );
mMaxBoundViewports = 1u;
// Where graphics ends, compute may start, or a new frame.
// Very likely we'll have to flush the UAVs again, so assume we need.
mUavRenderingDirty = true;
}
//---------------------------------------------------------------------
void RenderSystem::destroySharedDepthBuffer( TextureGpu *depthBuffer )
{
TextureGpuVec &bufferVec = mDepthBufferPool2[depthBuffer->getDepthBufferPoolId()];
TextureGpuVec::iterator itor = std::find( bufferVec.begin(), bufferVec.end(), depthBuffer );
if( itor != bufferVec.end() )
{
efficientVectorRemove( bufferVec, itor );
mTextureGpuManager->destroyTexture( depthBuffer );
}
}
//---------------------------------------------------------------------
void RenderSystem::_cleanupDepthBuffers()
{
TextureGpuSet::const_iterator itor = mSharedDepthBufferZeroRefCandidates.begin();
TextureGpuSet::const_iterator endt = mSharedDepthBufferZeroRefCandidates.end();
while( itor != endt )
{
// When a shared depth buffer ends up in mSharedDepthBufferZeroRefCandidates,
// it's because its ref. count reached 0. However it may have been reacquired.
// We need to check its reference count is still 0 before deleting it.
DepthBufferRefMap::iterator itMap = mSharedDepthBufferRefs.find( *itor );
if( itMap != mSharedDepthBufferRefs.end() && itMap->second == 0u )
{
destroySharedDepthBuffer( *itor );
mSharedDepthBufferRefs.erase( itMap );
}
++itor;
}
mSharedDepthBufferZeroRefCandidates.clear();
}
//---------------------------------------------------------------------
void RenderSystem::referenceSharedDepthBuffer( TextureGpu *depthBuffer )
{
OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() == TextureSourceType::SharedDepthBuffer );
OGRE_ASSERT_MEDIUM( mSharedDepthBufferRefs.find( depthBuffer ) != mSharedDepthBufferRefs.end() );
++mSharedDepthBufferRefs[depthBuffer];
}
//---------------------------------------------------------------------
void RenderSystem::_dereferenceSharedDepthBuffer( TextureGpu *depthBuffer )
{
if( !depthBuffer )
return;
DepthBufferRefMap::iterator itor = mSharedDepthBufferRefs.find( depthBuffer );
if( itor != mSharedDepthBufferRefs.end() )
{
OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() == TextureSourceType::SharedDepthBuffer );
OGRE_ASSERT_LOW( itor->second > 0u && "Releasing a shared depth buffer too much" );
--itor->second;
if( itor->second == 0u )
mSharedDepthBufferZeroRefCandidates.insert( depthBuffer );
}
else
{
// This is not a shared depth buffer (e.g. one created by the user)
OGRE_ASSERT_MEDIUM( depthBuffer->getSourceType() != TextureSourceType::SharedDepthBuffer );
}
}
//---------------------------------------------------------------------
void RenderSystem::selectDepthBufferFormat( const uint8 supportedFormats )
{
if( ( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_D32 ) &&
( supportedFormats & DepthBuffer::DFM_D32 ) )
{
if( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_S8 )
DepthBuffer::DefaultDepthBufferFormat = PFG_D32_FLOAT_S8X24_UINT;
else
DepthBuffer::DefaultDepthBufferFormat = PFG_D32_FLOAT;
}
else if( DepthBuffer::AvailableDepthFormats & ( DepthBuffer::DFM_D32 | DepthBuffer::DFM_D24 ) &&
( supportedFormats & DepthBuffer::DFM_D24 ) )
{
if( DepthBuffer::AvailableDepthFormats & DepthBuffer::DFM_S8 )
DepthBuffer::DefaultDepthBufferFormat = PFG_D24_UNORM_S8_UINT;
else
DepthBuffer::DefaultDepthBufferFormat = PFG_D24_UNORM;
}
else if( DepthBuffer::AvailableDepthFormats &
( DepthBuffer::DFM_D32 | DepthBuffer::DFM_D24 | DepthBuffer::DFM_D16 ) &&
( supportedFormats & DepthBuffer::DFM_D16 ) )
{
DepthBuffer::DefaultDepthBufferFormat = PFG_D16_UNORM;
}
else
DepthBuffer::DefaultDepthBufferFormat = PFG_NULL;
}
//---------------------------------------------------------------------
TextureGpu *RenderSystem::createDepthBufferFor( TextureGpu *colourTexture, bool preferDepthTexture,
PixelFormatGpu depthBufferFormat, uint16 poolId )
{
uint32 textureFlags = TextureFlags::RenderToTexture;
if( !preferDepthTexture )
textureFlags |= TextureFlags::NotTexture | TextureFlags::DiscardableContent;
char tmpBuffer[64];
LwString depthBufferName( LwString::FromEmptyPointer( tmpBuffer, sizeof( tmpBuffer ) ) );
depthBufferName.a( "DepthBuffer_", Id::generateNewId<TextureGpu>() );
TextureGpu *retVal = mTextureGpuManager->createTexture(
depthBufferName.c_str(), GpuPageOutStrategy::Discard, textureFlags, TextureTypes::Type2D );
retVal->setResolution( colourTexture->getInternalWidth(), colourTexture->getInternalHeight() );
retVal->setPixelFormat( depthBufferFormat );
retVal->_setDepthBufferDefaults( poolId, preferDepthTexture, depthBufferFormat );
retVal->_setSourceType( TextureSourceType::SharedDepthBuffer );
retVal->setSampleDescription( colourTexture->getRequestedSampleDescription() );
retVal->_transitionTo( GpuResidency::Resident, (uint8 *)0 );
// Start reference count on the depth buffer here
mSharedDepthBufferRefs[retVal] = 1u;
return retVal;
}
//---------------------------------------------------------------------
TextureGpu *RenderSystem::getDepthBufferFor( TextureGpu *colourTexture, uint16 poolId,
bool preferDepthTexture,
PixelFormatGpu depthBufferFormat )
{
if( poolId == DepthBuffer::POOL_NO_DEPTH || depthBufferFormat == PFG_NULL )
return 0; // RenderTarget explicitly requested no depth buffer
if( colourTexture->isRenderWindowSpecific() )
{
Window *window;
colourTexture->getCustomAttribute( "Window", &window );
return window->getDepthBuffer();
}
if( poolId == DepthBuffer::POOL_NON_SHAREABLE )
{
TextureGpu *retVal =
createDepthBufferFor( colourTexture, preferDepthTexture, depthBufferFormat, poolId );
return retVal;
}
// Find a depth buffer in the pool
TextureGpuVec::const_iterator itor = mDepthBufferPool2[poolId].begin();
TextureGpuVec::const_iterator endt = mDepthBufferPool2[poolId].end();
TextureGpu *retVal = 0;
while( itor != endt && !retVal )
{
if( preferDepthTexture == ( *itor )->isTexture() &&
( depthBufferFormat == PFG_UNKNOWN ||
depthBufferFormat == ( *itor )->getPixelFormat() ) &&
( *itor )->supportsAsDepthBufferFor( colourTexture ) )
{
retVal = *itor;
referenceSharedDepthBuffer( retVal );
}
else
{
retVal = 0;
}
++itor;
}
// Not found yet? Create a new one!
if( !retVal )
{
retVal =
createDepthBufferFor( colourTexture, preferDepthTexture, depthBufferFormat, poolId );
mDepthBufferPool2[poolId].push_back( retVal );
if( !retVal )
{
LogManager::getSingleton().logMessage(
"WARNING: Couldn't create a suited "
"DepthBuffer for RTT: " +
colourTexture->getNameStr(),
LML_CRITICAL );
}
}
return retVal;
}
//---------------------------------------------------------------------
void RenderSystem::setUavStartingSlot( uint32 startingSlot )
{
mUavStartingSlot = startingSlot;
mUavRenderingDirty = true;
}
//---------------------------------------------------------------------
void RenderSystem::queueBindUAVs( const DescriptorSetUav *descSetUav )
{
if( mUavRenderingDescSet != descSetUav )
{
mUavRenderingDescSet = descSetUav;
mUavRenderingDirty = true;
}
}
//-----------------------------------------------------------------------
BoundUav RenderSystem::getBoundUav( size_t slot ) const
{
BoundUav retVal;
memset( &retVal, 0, sizeof( retVal ) );
if( mUavRenderingDescSet )
{
if( slot < mUavRenderingDescSet->mUavs.size() )
{
if( mUavRenderingDescSet->mUavs[slot].isTexture() )
{
retVal.rttOrBuffer = mUavRenderingDescSet->mUavs[slot].getTexture().texture;
retVal.boundAccess = mUavRenderingDescSet->mUavs[slot].getTexture().access;
}
else
{
retVal.rttOrBuffer = mUavRenderingDescSet->mUavs[slot].getBuffer().buffer;
retVal.boundAccess = mUavRenderingDescSet->mUavs[slot].getBuffer().access;
}
}
}
return retVal;
}
//-----------------------------------------------------------------------
void RenderSystem::_beginFrameOnce() { mVaoManager->_beginFrame(); }
//-----------------------------------------------------------------------
void RenderSystem::_endFrameOnce() { queueBindUAVs( 0 ); }
//-----------------------------------------------------------------------
bool RenderSystem::getWBufferEnabled() const { return mWBuffer; }
//-----------------------------------------------------------------------
void RenderSystem::setWBufferEnabled( bool enabled ) { mWBuffer = enabled; }
//-----------------------------------------------------------------------
SampleDescription RenderSystem::validateSampleDescription( const SampleDescription &sampleDesc,
PixelFormatGpu format )
{
SampleDescription retVal( sampleDesc.getMaxSamples(), sampleDesc.getMsaaPattern() );
return retVal;
}
//-----------------------------------------------------------------------
void RenderSystem::shutdown()
{
// Remove occlusion queries
for( HardwareOcclusionQueryList::iterator i = mHwOcclusionQueries.begin();
i != mHwOcclusionQueries.end(); ++i )
{
OGRE_DELETE *i;
}
mHwOcclusionQueries.clear();
destroyAllRenderPassDescriptors();
_cleanupDepthBuffers();
OGRE_ASSERT_LOW( mSharedDepthBufferRefs.empty() &&
"destroyAllRenderPassDescriptors followed by _cleanupDepthBuffers should've "
"emptied mSharedDepthBufferRefs. Please report this bug to "
"https://github.com/OGRECave/ogre-next/issues/" );
OGRE_DELETE mTextureGpuManager;
mTextureGpuManager = 0;
OGRE_DELETE mVaoManager;
mVaoManager = 0;
{
// Remove all windows.
// (destroy primary window last since others may depend on it)
Window *primary = 0;
WindowSet::const_iterator itor = mWindows.begin();
WindowSet::const_iterator endt = mWindows.end();
while( itor != endt )
{
// Set mTextureManager to 0 as it is no longer valid on shutdown
if( ( *itor )->getTexture() )
( *itor )->getTexture()->_resetTextureManager();
if( ( *itor )->getDepthBuffer() )
( *itor )->getDepthBuffer()->_resetTextureManager();
if( ( *itor )->getStencilBuffer() )
( *itor )->getStencilBuffer()->_resetTextureManager();
if( !primary && ( *itor )->isPrimary() )
primary = *itor;
else
OGRE_DELETE *itor;
++itor;
}
OGRE_DELETE primary;
mWindows.clear();
}
}
//-----------------------------------------------------------------------
void RenderSystem::_resetMetrics()
{
const bool oldValue = mMetrics.mIsRecordingMetrics;
mMetrics = RenderingMetrics();
mMetrics.mIsRecordingMetrics = oldValue;
}
//-----------------------------------------------------------------------
void RenderSystem::_addMetrics( const RenderingMetrics &newMetrics )
{
if( mMetrics.mIsRecordingMetrics )
{
mMetrics.mBatchCount += newMetrics.mBatchCount;
mMetrics.mFaceCount += newMetrics.mFaceCount;
mMetrics.mVertexCount += newMetrics.mVertexCount;
mMetrics.mDrawCount += newMetrics.mDrawCount;
mMetrics.mInstanceCount += newMetrics.mInstanceCount;
}
}
//-----------------------------------------------------------------------
void RenderSystem::setMetricsRecordingEnabled( bool bEnable )
{
mMetrics.mIsRecordingMetrics = bEnable;
}
//-----------------------------------------------------------------------
const RenderingMetrics &RenderSystem::getMetrics() const { return mMetrics; }
//-----------------------------------------------------------------------
void RenderSystem::convertColourValue( const ColourValue &colour, uint32 *pDest )
{
*pDest = v1::VertexElement::convertColourValue( colour, getColourVertexElementType() );
}
//-----------------------------------------------------------------------
CompareFunction RenderSystem::reverseCompareFunction( CompareFunction depthFunc )
{
switch( depthFunc )
{
case CMPF_LESS:
return CMPF_GREATER;
case CMPF_LESS_EQUAL:
return CMPF_GREATER_EQUAL;
case CMPF_GREATER_EQUAL:
return CMPF_LESS_EQUAL;
case CMPF_GREATER:
return CMPF_LESS;
default:
return depthFunc;
}
return depthFunc;
}
//-----------------------------------------------------------------------
void RenderSystem::_makeRsProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest, Real nearPlane,
Real farPlane, ProjectionType projectionType )
{
dest = matrix;
Real inv_d = 1 / ( farPlane - nearPlane );
Real q, qn;
if( mReverseDepth )
{
if( projectionType == PT_PERSPECTIVE )
{
if( farPlane == 0 )
{
// Infinite far plane
// q = limit( near / (far - near), far, inf );
// qn = limit( (far * near) / (far - near), far, inf );
q = 0;
qn = nearPlane;
}
else
{
// Standard Z for range [-1; 1]
// q = - (far + near) / (far - near)
// qn = - 2 * (far * near) / (far - near)
//
// Standard Z for range [0; 1]
// q = - far / (far - near)
// qn = - (far * near) / (far - near)
//
// Reverse Z for range [1; 0]:
// [ 1 0 0 0 ] [ A 0 C 0 ]
// [ 0 1 0 0 ] X [ 0 B D 0 ]
// [ 0 0 -1 1 ] [ 0 0 q qn ]
// [ 0 0 0 1 ] [ 0 0 -1 0 ]
//
// [ A 0 C 0 ]
// [ 0 B D 0 ]
// [ 0 0 -q-1 -qn ]
// [ 0 0 -1 0 ]
//
// q' = -q - 1
// = far / (far - near) - 1
// = ( far - (far - near) ) / (far - near)
// q' = near / (far - near)
// qn'= -qn
q = nearPlane * inv_d;
qn = ( farPlane * nearPlane ) * inv_d;
}
}
else
{
if( farPlane == 0 )
{
// Can not do infinite far plane here, avoid divided zero only
q = Frustum::INFINITE_FAR_PLANE_ADJUST / nearPlane;
qn = Frustum::INFINITE_FAR_PLANE_ADJUST + 1;
}
else
{
// Standard Z for range [-1; 1]
// q = - 2 / (far - near)
// qn = -(far + near) / (far - near)
//
// Standard Z for range [0; 1]
// q = - 1 / (far - near)
// qn = - near / (far - near)
//
// Reverse Z for range [1; 0]:
// q' = 1 / (far - near)
// qn'= far / (far - near)
q = inv_d;
qn = farPlane * inv_d;
}
}
}
else
{
if( projectionType == PT_PERSPECTIVE )
{
if( farPlane == 0 )
{
// Infinite far plane
q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1;
qn = nearPlane * ( Frustum::INFINITE_FAR_PLANE_ADJUST - 1 );
}
else
{
q = -farPlane * inv_d;
qn = -( farPlane * nearPlane ) * inv_d;
}
}
else
{
if( farPlane == 0 )
{
// Can not do infinite far plane here, avoid divided zero only
q = -Frustum::INFINITE_FAR_PLANE_ADJUST / nearPlane;
qn = -Frustum::INFINITE_FAR_PLANE_ADJUST;
}
else
{
q = -inv_d;
qn = -nearPlane * inv_d;
}
}
}
dest[2][2] = q;
dest[2][3] = qn;
}
//-----------------------------------------------------------------------
void RenderSystem::_convertProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest )
{
dest = matrix;
if( !mReverseDepth )
{
// Convert depth range from [-1,+1] to [0,1]
dest[2][0] = ( dest[2][0] + dest[3][0] ) / 2;
dest[2][1] = ( dest[2][1] + dest[3][1] ) / 2;
dest[2][2] = ( dest[2][2] + dest[3][2] ) / 2;
dest[2][3] = ( dest[2][3] + dest[3][3] ) / 2;
}
else
{
// Convert depth range from [-1,+1] to [1,0]
dest[2][0] = ( -dest[2][0] + dest[3][0] ) / 2;
dest[2][1] = ( -dest[2][1] + dest[3][1] ) / 2;
dest[2][2] = ( -dest[2][2] + dest[3][2] ) / 2;
dest[2][3] = ( -dest[2][3] + dest[3][3] ) / 2;
}
}
//-----------------------------------------------------------------------
void RenderSystem::_convertOpenVrProjectionMatrix( const Matrix4 &matrix, Matrix4 &dest )
{
dest = matrix;
if( mReverseDepth )
{
// Convert depth range from [0,1] to [1,0]
dest[2][0] = ( -dest[2][0] + dest[3][0] );
dest[2][1] = ( -dest[2][1] + dest[3][1] );
dest[2][2] = ( -dest[2][2] + dest[3][2] );
dest[2][3] = ( -dest[2][3] + dest[3][3] );
}
}
//-----------------------------------------------------------------------
void RenderSystem::_setWorldMatrices( const Matrix4 *m, unsigned short count )
{
// Do nothing with these matrices here, it never used for now,
// derived class should take care with them if required.
// Set hardware matrix to nothing
_setWorldMatrix( Matrix4::IDENTITY );
}
//-----------------------------------------------------------------------
void RenderSystem::setStencilBufferParams( uint32 refValue, const StencilParams &stencilParams )
{
mStencilParams = stencilParams;
// NB: We should always treat CCW as front face for consistent with default
// culling mode.
const bool mustFlip =
( ( mInvertVertexWinding && !mCurrentRenderPassDescriptor->requiresTextureFlipping() ) ||
( !mInvertVertexWinding && mCurrentRenderPassDescriptor->requiresTextureFlipping() ) );
if( mustFlip )
{
mStencilParams.stencilBack = stencilParams.stencilFront;
mStencilParams.stencilFront = stencilParams.stencilBack;
}
}
//-----------------------------------------------------------------------
void RenderSystem::_render( const v1::RenderOperation &op )
{
// Update stats
size_t primCount = op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount;
size_t trueInstanceNum = std::max<size_t>( op.numberOfInstances, 1 );
primCount *= trueInstanceNum;
// account for a pass having multiple iterations
if( mCurrentPassIterationCount > 1 )
primCount *= mCurrentPassIterationCount;
mCurrentPassIterationNum = 0;
switch( op.operationType )
{
case OT_TRIANGLE_LIST:
mMetrics.mFaceCount += ( primCount / 3u );
break;
case OT_TRIANGLE_STRIP:
case OT_TRIANGLE_FAN:
mMetrics.mFaceCount += ( primCount - 2u );
break;
default:
break;
}
mMetrics.mVertexCount += op.vertexData->vertexCount * trueInstanceNum;
mMetrics.mBatchCount += mCurrentPassIterationCount;
// sort out clip planes
// have to do it here in case of matrix issues
if( mClipPlanesDirty )
{
setClipPlanesImpl( mClipPlanes );
mClipPlanesDirty = false;
}
}
//-----------------------------------------------------------------------
/*void RenderSystem::_render( const VertexArrayObject *vao )
{
// Update stats
mFaceCount += vao->mFaceCount;
mVertexCount += vao->mVertexBuffers[0]->getNumElements();
++mBatchCount;
}*/
//-----------------------------------------------------------------------
void RenderSystem::setInvertVertexWinding( bool invert ) { mInvertVertexWinding = invert; }
//-----------------------------------------------------------------------
bool RenderSystem::getInvertVertexWinding() const { return mInvertVertexWinding; }
//---------------------------------------------------------------------
void RenderSystem::addClipPlane( const Plane &p )
{
mClipPlanes.push_back( p );
mClipPlanesDirty = true;
}
//---------------------------------------------------------------------
void RenderSystem::addClipPlane( Real A, Real B, Real C, Real D )
{
addClipPlane( Plane( A, B, C, D ) );
}
//---------------------------------------------------------------------
void RenderSystem::setClipPlanes( const PlaneList &clipPlanes )
{
if( clipPlanes != mClipPlanes )
{
mClipPlanes = clipPlanes;
mClipPlanesDirty = true;
}
}
//---------------------------------------------------------------------
void RenderSystem::resetClipPlanes()
{
if( !mClipPlanes.empty() )
{
mClipPlanes.clear();
mClipPlanesDirty = true;
}
}
//---------------------------------------------------------------------
bool RenderSystem::updatePassIterationRenderState()
{
if( mCurrentPassIterationCount <= 1 )
return false;
--mCurrentPassIterationCount;
++mCurrentPassIterationNum;
if( mActiveVertexGpuProgramParameters )
{
mActiveVertexGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_VERTEX_PROGRAM );
}
if( mActiveGeometryGpuProgramParameters )
{
mActiveGeometryGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_GEOMETRY_PROGRAM );
}
if( mActiveFragmentGpuProgramParameters )
{
mActiveFragmentGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_FRAGMENT_PROGRAM );
}
if( mActiveTessellationHullGpuProgramParameters )
{
mActiveTessellationHullGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_HULL_PROGRAM );
}
if( mActiveTessellationDomainGpuProgramParameters )
{
mActiveTessellationDomainGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_DOMAIN_PROGRAM );
}
if( mActiveComputeGpuProgramParameters )
{
mActiveComputeGpuProgramParameters->incPassIterationNumber();
bindGpuProgramPassIterationParameters( GPT_COMPUTE_PROGRAM );
}
return true;
}
//-----------------------------------------------------------------------
void RenderSystem::addSharedListener( Listener *l ) { msSharedEventListeners.push_back( l ); }
//-----------------------------------------------------------------------
void RenderSystem::removeSharedListener( Listener *l ) { msSharedEventListeners.remove( l ); }
//-----------------------------------------------------------------------
void RenderSystem::addListener( Listener *l ) { mEventListeners.push_back( l ); }
//-----------------------------------------------------------------------
void RenderSystem::removeListener( Listener *l ) { mEventListeners.remove( l ); }
//-----------------------------------------------------------------------
void RenderSystem::fireEvent( const String &name, const NameValuePairList *params )
{
for( ListenerList::iterator i = mEventListeners.begin(); i != mEventListeners.end(); ++i )
{
( *i )->eventOccurred( name, params );
}
fireSharedEvent( name, params );
}
//-----------------------------------------------------------------------
void RenderSystem::fireSharedEvent( const String &name, const NameValuePairList *params )
{
for( ListenerList::iterator i = msSharedEventListeners.begin();
i != msSharedEventListeners.end(); ++i )
{
( *i )->eventOccurred( name, params );
}
}
//-----------------------------------------------------------------------
const char *RenderSystem::getPriorityConfigOption( size_t ) const
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "idx must be < getNumPriorityConfigOptions()",
"RenderSystem::getPriorityConfigOption" );
}
//-----------------------------------------------------------------------
size_t RenderSystem::getNumPriorityConfigOptions() const { return 0u; }
//-----------------------------------------------------------------------
void RenderSystem::destroyHardwareOcclusionQuery( HardwareOcclusionQuery *hq )
{
HardwareOcclusionQueryList::iterator i =
std::find( mHwOcclusionQueries.begin(), mHwOcclusionQueries.end(), hq );
if( i != mHwOcclusionQueries.end() )
{
mHwOcclusionQueries.erase( i );
OGRE_DELETE hq;
}
}
//-----------------------------------------------------------------------
bool RenderSystem::isGpuProgramBound( GpuProgramType gptype )
{
switch( gptype )
{
case GPT_VERTEX_PROGRAM:
return mVertexProgramBound;
case GPT_GEOMETRY_PROGRAM:
return mGeometryProgramBound;
case GPT_FRAGMENT_PROGRAM:
return mFragmentProgramBound;
case GPT_HULL_PROGRAM:
return mTessellationHullProgramBound;
case GPT_DOMAIN_PROGRAM:
return mTessellationDomainProgramBound;
case GPT_COMPUTE_PROGRAM:
return mComputeProgramBound;
}
// Make compiler happy
return false;
}
//---------------------------------------------------------------------
void RenderSystem::_setTextureProjectionRelativeTo( bool enabled, const Vector3 &pos )
{
mTexProjRelative = enabled;
mTexProjRelativeOrigin = pos;
}
//---------------------------------------------------------------------
RenderSystem::RenderSystemContext *RenderSystem::_pauseFrame()
{
_endFrame();
return new RenderSystem::RenderSystemContext;
}
//---------------------------------------------------------------------
void RenderSystem::_resumeFrame( RenderSystemContext *context )
{
_beginFrame();
delete context;
}
//---------------------------------------------------------------------
void RenderSystem::_update()
{
OgreProfile( "RenderSystem::_update" );
mBarrierSolver.reset();
mTextureGpuManager->_update( false );
mVaoManager->_update();
}
//---------------------------------------------------------------------
void RenderSystem::updateCompositorManager( CompositorManager2 *compositorManager )
{
compositorManager->_updateImplementation();
}
//---------------------------------------------------------------------
void RenderSystem::compositorWorkspaceBegin( CompositorWorkspace *workspace,
const bool forceBeginFrame )
{
workspace->_beginUpdate( forceBeginFrame, true );
}
//---------------------------------------------------------------------
void RenderSystem::compositorWorkspaceUpdate( CompositorWorkspace *workspace )
{
workspace->_update( true );
}
//---------------------------------------------------------------------
void RenderSystem::compositorWorkspaceEnd( CompositorWorkspace *workspace, const bool forceEndFrame )
{
workspace->_endUpdate( forceEndFrame, true );
}
//---------------------------------------------------------------------
const String &RenderSystem::_getDefaultViewportMaterialScheme() const
{
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
if( !( getCapabilities()->hasCapability( Ogre::RSC_FIXED_FUNCTION ) ) )
{
// I am returning the exact value for now - I don't want to add dependency for the RTSS just
// for one string
static const String ShaderGeneratorDefaultScheme = "ShaderGeneratorDefaultScheme";
return ShaderGeneratorDefaultScheme;
}
else
#endif
{
return MaterialManager::DEFAULT_SCHEME_NAME;
}
}
//---------------------------------------------------------------------
Ogre::v1::HardwareVertexBufferSharedPtr RenderSystem::getGlobalInstanceVertexBuffer() const
{
return mGlobalInstanceVertexBuffer;
}
//---------------------------------------------------------------------
void RenderSystem::setGlobalInstanceVertexBuffer( const v1::HardwareVertexBufferSharedPtr &val )
{
if( val && !val->getIsInstanceData() )
{
OGRE_EXCEPT(
Exception::ERR_INVALIDPARAMS,
"A none instance data vertex buffer was set to be the global instance vertex buffer.",
"RenderSystem::setGlobalInstanceVertexBuffer" );
}
mGlobalInstanceVertexBuffer = val;
}
//---------------------------------------------------------------------
size_t RenderSystem::getGlobalNumberOfInstances() const { return mGlobalNumberOfInstances; }
//---------------------------------------------------------------------
void RenderSystem::setGlobalNumberOfInstances( const size_t val ) { mGlobalNumberOfInstances = val; }
v1::VertexDeclaration *RenderSystem::getGlobalInstanceVertexBufferVertexDeclaration() const
{
return mGlobalInstanceVertexBufferVertexDeclaration;
}
//---------------------------------------------------------------------
void RenderSystem::setGlobalInstanceVertexBufferVertexDeclaration( v1::VertexDeclaration *val )
{
mGlobalInstanceVertexBufferVertexDeclaration = val;
}
//---------------------------------------------------------------------
bool RenderSystem::startGpuDebuggerFrameCapture( Window *window )
{
if( !mRenderDocApi )
{
loadRenderDocApi();
if( !mRenderDocApi )
return false;
}
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
RENDERDOC_DevicePointer device = 0;
RENDERDOC_WindowHandle windowHandle = 0;
if( window )
{
window->getCustomAttribute( "RENDERDOC_DEVICE", device );
window->getCustomAttribute( "RENDERDOC_WINDOW", windowHandle );
}
mRenderDocApi->StartFrameCapture( device, windowHandle );
#endif
return true;
}
//---------------------------------------------------------------------
void RenderSystem::endGpuDebuggerFrameCapture( Window *window )
{
if( !mRenderDocApi )
return;
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
RENDERDOC_DevicePointer device = 0;
RENDERDOC_WindowHandle windowHandle = 0;
if( window )
{
window->getCustomAttribute( "RENDERDOC_DEVICE", device );
window->getCustomAttribute( "RENDERDOC_WINDOW", windowHandle );
}
mRenderDocApi->EndFrameCapture( device, windowHandle );
#endif
}
//---------------------------------------------------------------------
bool RenderSystem::loadRenderDocApi()
{
#if OGRE_NO_RENDERDOC_INTEGRATION == 0
if( mRenderDocApi )
return true; // Already loaded
# if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
# if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
void *mod = dlopen( "librenderdoc.so", RTLD_NOW | RTLD_NOLOAD );
# else
void *mod = dlopen( "libVkLayer_GLES_RenderDoc.so", RTLD_NOW | RTLD_NOLOAD );
# endif
if( mod )
{
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym( mod, "RENDERDOC_GetAPI" );
const int ret = RENDERDOC_GetAPI( eRENDERDOC_API_Version_1_4_1, (void **)&mRenderDocApi );
return ret == 1;
}
# elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
HMODULE mod = GetModuleHandleA( "renderdoc.dll" );
if( mod )
{
pRENDERDOC_GetAPI RENDERDOC_GetAPI =
(pRENDERDOC_GetAPI)GetProcAddress( mod, "RENDERDOC_GetAPI" );
const int ret = RENDERDOC_GetAPI( eRENDERDOC_API_Version_1_4_1, (void **)&mRenderDocApi );
return ret == 1;
}
# endif
#endif
return false;
}
//---------------------------------------------------------------------
void RenderSystem::getCustomAttribute( const String &name, void *pData )
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Attribute not found.",
"RenderSystem::getCustomAttribute" );
}
//---------------------------------------------------------------------
void RenderSystem::setDebugShaders( bool bDebugShaders ) { mDebugShaders = bDebugShaders; }
//---------------------------------------------------------------------
bool RenderSystem::isSameLayout( ResourceLayout::Layout a, ResourceLayout::Layout b,
const TextureGpu *texture, bool bIsDebugCheck ) const
{
if( ( a != ResourceLayout::Uav && b != ResourceLayout::Uav ) || bIsDebugCheck )
return true;
return a == b;
}
//---------------------------------------------------------------------
void RenderSystem::_clearStateAndFlushCommandBuffer() {}
//---------------------------------------------------------------------
RenderSystem::Listener::~Listener() {}
} // namespace Ogre
| 59,307 | 15,946 |
#include<iostream>
#include<cstdio>
#include<set>
using namespace std;
int main() {
int temp,n1,n2;
while(scanf("%d %d",&n1,&n2)!=EOF) {
set<int> s;
n1=n1+n2;
while(n1--) {
scanf("%d",&temp);
s.insert(temp);
}
set<int>::const_iterator itor;
itor=s.begin();
while(itor!=s.end()) {
printf("%d",*itor);
itor++;
if(itor!=s.end())
printf(" ");
}
printf("\n");
}
return 0;
} | 409 | 214 |
/*
Copyright (c) 2002-2016 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
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.
*/
/**
* @file AlmaIFIntegrator.hh
*
* Declaration of AlmaIFIntegrator class.
*/
#ifndef TTA_ALMAIF_INTEGRATOR_HH
#define TTA_ALMAIF_INTEGRATOR_HH
#include "PlatformIntegrator.hh"
#include "TCEString.hh"
#include "ProGeTypes.hh"
#include "DefaultProjectFileGenerator.hh"
class AlmaIFIntegrator : public PlatformIntegrator {
public:
AlmaIFIntegrator();
AlmaIFIntegrator(
const TTAMachine::Machine* machine,
const IDF::MachineImplementation* idf,
ProGe::HDL hdl,
TCEString progeOutputDir,
TCEString entityName,
TCEString outputDir,
TCEString programName,
int targetClockFreq,
std::ostream& warningStream,
std::ostream& errorStream,
const MemInfo& imem,
MemType dmemType);
virtual ~AlmaIFIntegrator();
virtual void integrateProcessor(const ProGe::NetlistBlock* progeBlock);
virtual bool integrateCore(const ProGe::NetlistBlock& cores);
virtual void printInfo(std::ostream& stream) const;
virtual TCEString deviceFamily() const;
virtual void setDeviceFamily(TCEString devFamily);
virtual TCEString deviceName() const;
virtual TCEString devicePackage() const;
virtual TCEString deviceSpeedClass() const;
virtual int targetClockFrequency() const;
virtual TCEString pinTag() const;
virtual bool chopTaggedSignals() const;
virtual ProjectFileGenerator* projectFileGenerator() const;
protected:
virtual MemoryGenerator& imemInstance(MemInfo imem);
virtual MemoryGenerator& dmemInstance(
MemInfo dmem,
TTAMachine::FunctionUnit& lsuArch,
HDB::FUImplementation& lsuImplementation);
private:
void addMemoryPorts(const TCEString as_name, const TCEString data_width,
const TCEString addr_width);
void addAlmaifBlock();
void addAlmaifFiles();
void copyPlatformFile(const TCEString inputPath,
std::vector<TCEString>& fileList) const;
void instantiatePlatformFile(const TCEString inputPath,
std::vector<TCEString>& fileList) const;
int axiAddressWidth() const;
bool verifyMemories() const;
static const TCEString DMEM_NAME;
static const TCEString PMEM_NAME;
static const TCEString ALMAIF_MODULE;
MemoryGenerator* imemGen_;
std::map<TCEString, MemoryGenerator*> dmemGen_;
std::map<TCEString, ProGe::NetlistPort*> almaif_ttacore_ports;
ProGe::NetlistBlock* almaifBlock_;
TCEString deviceFamily_;
DefaultProjectFileGenerator* fileGen_;
};
#endif
| 3,747 | 1,161 |
/* ocaml-clanlib: OCaml bindings to the ClanLib SDK
Copyright (C) 2013 Florent Monnier
This software is provided "AS-IS", without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely. */
#include <ClanLib/Core/System/databuffer.h>
#include "cl_caml_incs.hpp"
#include "cl_caml_conv.hpp"
#include "CL_DataBuffer_stub.hpp"
CAMLextern_C value
caml_CL_DataBuffer_init(value unit)
{
CL_DataBuffer *buf = new CL_DataBuffer();
return Val_CL_DataBuffer(buf);
}
CAMLextern_C value
caml_CL_DataBuffer_copy(value orig)
{
CL_DataBuffer *buf = new CL_DataBuffer(*CL_DataBuffer_val(orig));
return Val_CL_DataBuffer(buf);
}
CAMLextern_C value
caml_CL_DataBuffer_of_string(value str)
{
CL_DataBuffer *buf = new CL_DataBuffer(
String_val(str),
caml_string_length(str));
return Val_CL_DataBuffer(buf);
}
/* TODO:
CL_DataBuffer(int size, CL_MemoryPool *pool = 0);
CL_DataBuffer(const void *data, int size, CL_MemoryPool *pool = 0);
CL_DataBuffer(const CL_DataBuffer &data, int pos, int size = -1, CL_MemoryPool *pool = 0);
*/
CAMLextern_C value
caml_CL_DataBuffer_delete(value buf)
{
delete CL_DataBuffer_val(buf);
nullify_ptr(buf);
return Val_unit;
}
CAMLextern_C value
caml_CL_DataBuffer_get_size(value buf)
{
int size = CL_DataBuffer_val(buf)->get_size();
return Val_long(size);
}
CAMLextern_C value
caml_CL_DataBuffer_get_capacity(value buf)
{
int cap = CL_DataBuffer_val(buf)->get_capacity();
return Val_long(cap);
}
CAMLextern_C value
caml_CL_DataBuffer_set_size(value buf, value size)
{
CL_DataBuffer_val(buf)->set_size(Int_val(size));
return Val_unit;
}
CAMLextern_C value
caml_CL_DataBuffer_set_capacity(value buf, value cap)
{
CL_DataBuffer_val(buf)->set_capacity(Int_val(cap));
return Val_unit;
}
CAMLextern_C value
caml_CL_DataBuffer_get_i(value buf, value i)
{
const char c =
(*CL_DataBuffer_val(buf))[ Int_val(i) ];
return Val_char(c);
}
CAMLextern_C value
caml_CL_DataBuffer_set_i(value buf, value i, value c)
{
(*CL_DataBuffer_val(buf))[ Int_val(i) ] = Char_val(c);
return Val_unit;
}
/* TODO:
char *get_data();
const char *get_data();
char &operator[](int i);
const char &operator[](int i);
char &operator[](unsigned int i);
const char &operator[](unsigned int i);
bool is_null();
CL_DataBuffer &operator =(const CL_DataBuffer ©);
*/
// vim: sw=4 sts=4 ts=4 et
| 2,685 | 996 |
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include <utility>
#include <algorithm>
#include "caf/response_promise.hpp"
#include "caf/logger.hpp"
#include "caf/local_actor.hpp"
namespace caf {
response_promise::response_promise() : self_(nullptr) {
// nop
}
response_promise::response_promise(none_t) : response_promise() {
// nop
}
response_promise::response_promise(strong_actor_ptr self,
strong_actor_ptr source,
forwarding_stack stages, message_id mid)
: self_(std::move(self)),
source_(std::move(source)),
stages_(std::move(stages)),
id_(mid) {
// Form an invalid request promise when initialized from a response ID, since
// we always drop messages in this case.
if (mid.is_response()) {
source_ = nullptr;
stages_.clear();
}
}
response_promise::response_promise(strong_actor_ptr self, mailbox_element& src)
: response_promise(std::move(self), std::move(src.sender),
std::move(src.stages), src.mid) {
// nop
}
void response_promise::deliver(error x) {
deliver_impl(make_message(std::move(x)));
}
void response_promise::deliver(unit_t) {
deliver_impl(make_message());
}
bool response_promise::async() const {
return id_.is_async();
}
execution_unit* response_promise::context() {
return self_ == nullptr
? nullptr
: static_cast<local_actor*>(actor_cast<abstract_actor*>(self_))
->context();
}
void response_promise::deliver_impl(message msg) {
CAF_LOG_TRACE(CAF_ARG(msg));
if (!stages_.empty()) {
auto next = std::move(stages_.back());
stages_.pop_back();
next->enqueue(make_mailbox_element(std::move(source_), id_,
std::move(stages_), std::move(msg)),
context());
return;
}
if (source_) {
source_->enqueue(std::move(self_), id_.response_id(),
std::move(msg), context());
source_.reset();
return;
}
CAF_LOG_INFO_IF(self_ != nullptr, "response promise already satisfied");
CAF_LOG_INFO_IF(self_ == nullptr, "invalid response promise");
}
} // namespace caf
| 3,491 | 995 |
// Copyright 2020 Tier IV, 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.
#ifndef DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
#define DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
#include <diagnostic_updater/diagnostic_updater.hpp>
#include <rclcpp/rclcpp.hpp>
#include <string>
#include <vector>
struct DiagConfig
{
std::string name;
std::string hardware_id;
std::string msg_ok;
std::string msg_warn;
std::string msg_error;
std::string msg_stale;
};
class DummyDiagPublisherNode : public rclcpp::Node
{
public:
explicit DummyDiagPublisherNode(const rclcpp::NodeOptions & node_options);
private:
enum Status {
OK,
WARN,
ERROR,
STALE,
};
struct DummyDiagPublisherConfig
{
Status status;
bool is_active;
};
// Parameter
double update_rate_;
DiagConfig diag_config_;
DummyDiagPublisherConfig config_;
// Dynamic Reconfigure
OnSetParametersCallbackHandle::SharedPtr set_param_res_;
rcl_interfaces::msg::SetParametersResult paramCallback(
const std::vector<rclcpp::Parameter> & parameters);
// Diagnostic Updater
// Set long period to reduce automatic update
diagnostic_updater::Updater updater_{this, 1000.0 /* sec */};
void produceDiagnostics(diagnostic_updater::DiagnosticStatusWrapper & stat);
// Timer
void onTimer();
rclcpp::TimerBase::SharedPtr timer_;
};
#endif // DUMMY_DIAG_PUBLISHER__DUMMY_DIAG_PUBLISHER_NODE_HPP_
| 1,948 | 677 |
/*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::fvSurfaceMapper
Description
FV surface mapper.
SourceFiles
fvSurfaceMapper.cpp
\*---------------------------------------------------------------------------*/
#ifndef fvSurfaceMapper_H
#define fvSurfaceMapper_H
#include "morphFieldMapper.hpp"
#include "fvMesh.hpp"
#include "faceMapper.hpp"
#include "HashSet.hpp"
#include "mapPolyMesh.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
// Forward declaration of classes
/*---------------------------------------------------------------------------*\
Class fvSurfaceMapper Declaration
\*---------------------------------------------------------------------------*/
class fvSurfaceMapper
:
public morphFieldMapper
{
// Private data
//- Reference to mesh
const fvMesh& mesh_;
//- Reference to face mapper
const faceMapper& faceMap_;
// Demand-driven private data
//- Direct addressing (only one for of addressing is used)
mutable labelList* directAddrPtr_;
//- Interpolated addressing (only one for of addressing is used)
mutable labelListList* interpolationAddrPtr_;
//- Interpolation weights
mutable scalarListList* weightsPtr_;
//- Inserted faces
mutable labelList* insertedObjectLabelsPtr_;
// Private Member Functions
//- Disallow default bitwise copy construct
fvSurfaceMapper(const fvSurfaceMapper&);
//- Disallow default bitwise assignment
void operator=(const fvSurfaceMapper&);
//- Calculate addressing
void calcAddressing() const;
//- Clear out local storage
void clearOut();
public:
// Constructors
//- Construct from components
fvSurfaceMapper
(
const fvMesh& mesh,
const faceMapper& fMapper
);
//- Destructor
virtual ~fvSurfaceMapper();
// Member Functions
//- Return size
virtual label size() const
{
return mesh_.nInternalFaces();
}
//- Return size of field before mapping
virtual label sizeBeforeMapping() const
{
return faceMap_.internalSizeBeforeMapping();
}
//- Is the mapping direct
virtual bool direct() const
{
return faceMap_.direct();
}
//- Has unmapped elements
virtual bool hasUnmapped() const
{
return insertedObjects();
}
//- Return direct addressing
virtual const labelUList& directAddressing() const;
//- Return interpolated addressing
virtual const labelListList& addressing() const;
//- Return interpolaion weights
virtual const scalarListList& weights() const;
//- Are there any inserted faces
virtual bool insertedObjects() const
{
return faceMap_.insertedObjects();
}
//- Return list of inserted faces
virtual const labelList& insertedObjectLabels() const;
//- Return flux flip map
const labelHashSet& flipFaceFlux() const
{
return faceMap_.flipFaceFlux();
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 4,416 | 1,193 |
// (C) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, Howard
// Hinnant & John Maddock 2000. Permission to copy, use, modify,
// sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
//
// See http://www.boost.org for most recent version including documentation.
#ifndef BOOST_TT_DETAIL_CV_TRAITS_IMPL_HPP_INCLUDED
#define BOOST_TT_DETAIL_CV_TRAITS_IMPL_HPP_INCLUDED
#include "boost/config.hpp"
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
namespace boost {
namespace detail {
// implementation helper:
template <typename T> struct cv_traits_imp {};
template <typename T>
struct cv_traits_imp<T*>
{
BOOST_STATIC_CONSTANT(bool, is_const = false);
BOOST_STATIC_CONSTANT(bool, is_volatile = false);
typedef T unqualified_type;
};
template <typename T>
struct cv_traits_imp<const T*>
{
BOOST_STATIC_CONSTANT(bool, is_const = true);
BOOST_STATIC_CONSTANT(bool, is_volatile = false);
typedef T unqualified_type;
};
template <typename T>
struct cv_traits_imp<volatile T*>
{
BOOST_STATIC_CONSTANT(bool, is_const = false);
BOOST_STATIC_CONSTANT(bool, is_volatile = true);
typedef T unqualified_type;
};
template <typename T>
struct cv_traits_imp<const volatile T*>
{
BOOST_STATIC_CONSTANT(bool, is_const = true);
BOOST_STATIC_CONSTANT(bool, is_volatile = true);
typedef T unqualified_type;
};
} // namespace detail
} // namespace boost
#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
#endif // BOOST_TT_DETAIL_CV_TRAITS_IMPL_HPP_INCLUDED
| 1,749 | 658 |
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <future>
#include <vector>
#include <getopt.h>
#include <unistd.h>
#include <string.h>
#include "rilc_api.h"
#include "rilc_interface.h"
#include "logger.h"
std::mutex mutexSocilited;
std::condition_variable condSocilited;
void socilited_notify(RILResponse *arg)
{
condSocilited.notify_one();
LOGI << "RILC call user defined socilited_notify function" << ENDL;
}
void unsocilited_notify(RILResponse *arg)
{
LOGI << "RILC call user defined unsocilited_notify function" << ENDL;
}
static int sg_index = 0;
/**
* will call std::abort() if get an timeout
*/
#define RILC_TEST_ABORT_TIMEOUT(func, args...) \
do \
{ \
LOGI << ">>>>>>>> RILC_TEST index: " << ++sg_index << ENDL; \
RILResponse resp; \
memset(&resp, 0, sizeof(RILResponse)); \
resp.responseNotify = socilited_notify; \
std::unique_lock<std::mutex> _lk(mutexSocilited); \
func(&resp, ##args); \
if (condSocilited.wait_for(_lk, std::chrono::seconds(60)) == std::cv_status::timeout) \
{ \
LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " failed for timeout" << ENDL; \
LOGE << "OOPS!!! request timeout" << ENDL; \
LOGE << "check wether host can get response from device" << ENDL; \
std::abort(); \
} \
else \
{ \
if (resp.responseShow) \
resp.responseShow(&resp); \
if (resp.responseFree) \
resp.responseFree(&resp); \
LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " pass" << ENDL; \
} \
_lk.unlock(); \
LOGI << ">>>>>>>> RILC_TEST index: " << sg_index << " finished" << ENDL << ENDL << ENDL; \
} while (0);
int main(int argc, char **argv)
{
static const struct option long_options[] = {
{"device", required_argument, NULL, 'd'},
{"mode", required_argument, NULL, 'm'},
{"platform", required_argument, NULL, 'p'},
{"level", required_argument, NULL, 'l'},
{NULL, 0, NULL, 0}};
const char *device = "/dev/ttyUSB4";
Severity s = Severity::DEBUG;
/**
* 0 Linux
* 1 Android
*/
int platform = 0;
/**
* 0 abort if timeout
* 1 abort if response report an error
*/
int test_mode = 0;
int long_index = 0;
int opt;
while ((opt = getopt_long(argc, argv, "d:m:p:l:?h", long_options, &long_index)) != -1)
{
switch (opt)
{
case 'd':
device = optarg;
LOGI << "using device: " << device << ENDL;
break;
case 'm':
test_mode = !!atoi(optarg);
LOGI << "using test mode: " << test_mode << ENDL;
break;
case 'p':
if (optarg && !strncasecmp(optarg, "linux", 4))
platform = 0;
else if (optarg && !strncasecmp(optarg, "android", 4))
platform = 1;
LOGI << "using platform: " << (platform ? "Android" : "Linux") << ENDL;
break;
case 'l':
if (optarg && !strncasecmp(optarg, "debug", 4))
s = Severity::DEBUG;
else if (optarg && !strncasecmp(optarg, "info", 4))
s = Severity::INFO;
else if (optarg && !strncasecmp(optarg, "warn", 4))
s = Severity::WARNING;
else if (optarg && !strncasecmp(optarg, "error", 4))
s = Severity::ERROR;
else
s = Severity::INFO;
break;
default:
LOGI << "help message:" << ENDL;
LOGI << " -d, --device ttydevice or socket" << ENDL;
LOGI << " -m, --mode test mode(0 stop test if meet a timeout, 1 stop test if meet an error)" << ENDL;
LOGI << " -p, --platform os platform(0 for Linux, 1 for Android)" << ENDL;
LOGI << " -l, --level log level(debug, info, warning, error)" << ENDL;
return 0;
}
}
if (access(device, R_OK | W_OK))
{
LOGE << "invalid device: " << device << ENDL;
return 0;
}
/**
* set log level Severity::INFO
* for more detail set Severity::DEBUG
*/
Logger::Init("RILC", s, false);
/** test on Android
* Android only allow user radio connect socket '/dev/socket/rild'
*/
if (platform == 1)
{
setgid(1001);
setuid(1001);
LOGI << "try to switch user to radio: id 1001" << ENDL;
LOGD << "after switch user UID\t= " << getuid() << ENDL;
LOGD << "after switch user EUID\t= " << geteuid() << ENDL;
LOGD << "after switch user GID\t= " << getgid() << ENDL;
LOGD << "after switch user EGID\t= " << getegid() << ENDL;
}
/** test on Linux with RG500U
* Android only allow user radio connect socket '/dev/socket/rild'
*/
if (device)
RILC_init(device);
else
{
if (platform == 1)
RILC_init("/dev/socket/rild");
else
RILC_init("/dev/ttyUSB4");
}
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ON_USSD, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ON_USSD_REQUEST, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_NITZ_TIME_RECEIVED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SIGNAL_STRENGTH, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_DATA_CALL_LIST_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SUPP_SVC_NOTIFICATION, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_SESSION_END, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_PROACTIVE_COMMAND, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_EVENT_NOTIFY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_STK_CALL_SETUP, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SIM_SMS_STORAGE_FULL, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SIM_REFRESH, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CALL_RING, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_CDMA_NEW_SMS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESTRICTED_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_CALL_WAITING, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_OTA_PROVISION_STATUS, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_INFO_REC, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_OEM_HOOK_RAW, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RINGBACK_TONE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RESEND_INCALL_MUTE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CDMA_PRL_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RIL_CONNECTED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_VOICE_RADIO_TECH_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_CELL_INFO_LIST, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_UICC_SUBSCRIPTION_STATUS_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_SRVCC_STATE_NOTIFY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_HARDWARE_CONFIG_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_DC_RT_INFO_CHANGED, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_RADIO_CAPABILITY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_ON_SS, unsocilited_notify); // TOD;
RILC_unsocilitedRegister(RIL_UNSOL_STK_CC_ALPHA_NOTIFY, unsocilited_notify);
RILC_unsocilitedRegister(RIL_UNSOL_LCEDATA_RECV, unsocilited_notify);
RILC_TEST_ABORT_TIMEOUT(RILC_getIMEI);
RILC_TEST_ABORT_TIMEOUT(RILC_getIMEISV);
RILC_TEST_ABORT_TIMEOUT(RILC_getIMSI);
RILC_TEST_ABORT_TIMEOUT(RILC_getVoiceRegistrationState);
RILC_TEST_ABORT_TIMEOUT(RILC_getDataRegistrationState);
RILC_TEST_ABORT_TIMEOUT(RILC_getOperator);
RILC_TEST_ABORT_TIMEOUT(RILC_getNeighboringCids);
RILC_TEST_ABORT_TIMEOUT(RILC_getSignalStrength);
RILC_TEST_ABORT_TIMEOUT(RILC_getPreferredNetworkType);
RILC_TEST_ABORT_TIMEOUT(RILC_setPreferredNetworkType, RADIO_TECHNOLOGY_LTE);
RILC_TEST_ABORT_TIMEOUT(RILC_setupDataCall, RADIO_TECHNOLOGY_LTE, "0", "3gnet",
"", "", SETUP_DATA_AUTH_NONE, PROTOCOL_IPV4);
RILC_TEST_ABORT_TIMEOUT(RILC_getIccCardStatus);
RILC_TEST_ABORT_TIMEOUT(RILC_getCurrentCalls);
RILC_TEST_ABORT_TIMEOUT(RILC_getNetworkSelectionMode);
RILC_TEST_ABORT_TIMEOUT(RILC_getDataCallList);
RILC_TEST_ABORT_TIMEOUT(RILC_getBasebandVersion);
RILC_TEST_ABORT_TIMEOUT(RILC_queryAvailableBandMode);
RILC_uninit();
return 0;
}
| 11,493 | 4,048 |
#include <d3dx9.h>
#include "utils.h"
#include "trace.h"
LPDIRECT3DSURFACE9 CreateSurfaceFromFile(LPDIRECT3DDEVICE9 d3ddv, LPWSTR FilePath)
{
D3DXIMAGE_INFO info;
HRESULT result = D3DXGetImageInfoFromFile(FilePath,&info);
if (result!=D3D_OK)
{
trace(L"[ERROR] Failed to get image info '%s'",FilePath);
return NULL;
}
LPDIRECT3DSURFACE9 surface;
d3ddv->CreateOffscreenPlainSurface(
info.Width, // width
info.Height, // height
D3DFMT_X8R8G8B8, // format
D3DPOOL_DEFAULT,
&surface,
NULL);
result = D3DXLoadSurfaceFromFile(
surface, // surface
NULL, // destination palette
NULL, // destination rectangle
FilePath,
NULL, // source rectangle
D3DX_DEFAULT, // filter image
D3DCOLOR_XRGB(0,0,0), // transparency (0 = none)
NULL); // reserved
if (result!=D3D_OK)
{
trace(L"[ERROR] D3DXLoadSurfaceFromFile() failed");
return NULL;
}
return surface;
} | 939 | 446 |
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <Windows.h>
#include <cmath>
#include "CanInterface.h"
using namespace pybind11::literals;
namespace py = pybind11;
class Can4Python : public CanInterface
{
public:
Can4Python()
: CanInterface()
{}
bool SendCanMessage(int devIndex, unsigned int messageId, std::vector<unsigned char> payload, int messageFlags)
{
unsigned char payloadArr[64];
for (int i = 0; i < payload.size(); i++) payloadArr[i] = payload.at(i);
return CanInterface::SendCanMessage(devIndex, messageId, payloadArr, payload.size(), messageFlags);
}
bool SendCanMessageAsync(int devIndex, unsigned int messageId, std::vector<unsigned char> payload, int messageFlags)
{
unsigned char payloadArr[64];
for (int i = 0; i < payload.size(); i++) payloadArr[i] = payload.at(i);
return CanInterface::SendCanMessageAsync(devIndex, messageId, payloadArr, payload.size(), messageFlags);
}
py::dict GetCanMessage(int devIndex)
{
unsigned int identifier;
unsigned char payload[64];
int payloadLength;
int messageFlags;
unsigned long timestamp;
if (CanInterface::GetCanMessage(devIndex, &identifier, payload, &payloadLength, &messageFlags, ×tamp))
{
auto payloadArr = std::vector<unsigned char>();
for (int i = 0; i < payloadLength; i++) payloadArr.push_back(payload[i]);
return py::dict("identifier"_a = identifier, "payload"_a = payloadArr, "messageFlags"_a = messageFlags, "timestamp"_a = timestamp);
}
return py::dict();
}
};
PYBIND11_MODULE(Can4Python, mod) {
py::class_<Can4Python, std::shared_ptr<Can4Python>> clsCan4Python(mod, "CanInterface");
py::enum_<Can4Python::IdentifierFlags>(clsCan4Python, "IdentifierFlags")
.value("EXTENDED_29BIT", Can4Python::IdentifierFlags::EXTENDED_29BIT)
.value("STANDARD_11BIT", Can4Python::IdentifierFlags::STANDARD_11BIT);
py::enum_<Can4Python::MessageFlags>(clsCan4Python, "MessageFlags")
.value("USE_BRS", Can4Python::MessageFlags::USE_BRS)
.value("USE_EDL", Can4Python::MessageFlags::USE_EDL)
.value("USE_EXT", Can4Python::MessageFlags::USE_EXT);
clsCan4Python.def(py::init<>());
clsCan4Python.def("GetDeviceCount", &Can4Python::GetDeviceCount);
clsCan4Python.def("EnableTransreceiver", &Can4Python::EnableTransreceiver);
clsCan4Python.def("DisableTransreceiver", &Can4Python::DisableTransreceiver);
clsCan4Python.def("OpenCan20", &Can4Python::OpenCan20);
clsCan4Python.def("OpenCanFD", &Can4Python::OpenCanFD);
clsCan4Python.def("CloseCan", &Can4Python::CloseCan);
clsCan4Python.def("StartReceiving", &Can4Python::StartReceiving);
clsCan4Python.def("StopReceiving", &Can4Python::StopReceiving);
clsCan4Python.def("SendCanMessage", &Can4Python::SendCanMessage);
clsCan4Python.def("SendCanMessageAsync", &Can4Python::SendCanMessageAsync);
clsCan4Python.def("GetCanMessage", &Can4Python::GetCanMessage);
clsCan4Python.def("AddReceiveHandler",
(int (Can4Python::*)(int, unsigned int, int) ) & Can4Python::AddReceiveHandler,
"devIndex"_a, "messageId"_a, "identifierFlags"_a);
clsCan4Python.def("AddReceiveHandler",
(int (Can4Python::*)(int, unsigned int, unsigned int, int)) & Can4Python::AddReceiveHandler,
"devIndex"_a, "lowerMessageId"_a, "higherMessageId"_a, "identifierFlags"_a);
clsCan4Python.def("AddReceiveHandler",
(int (Can4Python::*)(int, int)) & Can4Python::AddReceiveHandler,
"devIndex"_a, "identifierFlags"_a);
clsCan4Python.def("RemoveReceiveHandler", &Can4Python::RemoveReceiveHandler, "devIndex"_a, "handlerId"_a = -1);
#ifdef VERSION_INFO
mod.attr("__version__") = VERSION_INFO;
#else
mod.attr("__version__") = "dev";
#endif
} | 3,619 | 1,296 |
#include <cstdio>
int main() {
int pwg;scanf("%d", &pwg);
while (pwg--) {
int awr;scanf("%d", &awr);
switch (awr) {
case 1: printf("9");break;
case 2: printf("98");break;
default: printf("989");int zqi_ifn = 0;for (int ebe = 4;ebe <= awr;ebe++) {printf("%d", zqi_ifn);zqi_ifn = (zqi_ifn + 1) % 10;}break;
}
printf("\n");
}
return 0;
}
| 356 | 190 |
/*
* Microsoft Public License (Ms-PL) - Copyright (c) 2020-2021 Sean Moss
* This file is subject to the terms and conditions of the Microsoft Public License, the text of which can be found in
* the 'LICENSE' file at the root of this repository, or online at <https://opensource.org/licenses/MS-PL>.
*/
#pragma once
#include "./Config.hpp"
#include <unordered_map>
#include <vector>
namespace vsl
{
// Enum of the base shader types
enum class BaseType : uint32
{
Void = 0, // Special type for errors and function returns
Boolean = 1, // Boolean scalar/vector
Signed = 2, // Signed integer scalar/vector
Unsigned = 3, // Unsigned integer scalar/vector
Float = 4, // Floating point scalar/vector/matrix
Sampler = 5, // Vk combined image/sampler, glsl 'sampler*D' (no separate image and sampler objects)
Image = 6, // Vk storage image, glsl `image*D` w/ layout
ROBuffer = 7, // Vk readonly storage buffer, glsl `readonly buffer <name> { ... }`
RWBuffer = 8, // Vk read/write storage buffer, glsl `buffer <name> { ... }`
ROTexels = 9, // Vk uniform texel buffer, glsl `textureBuffer`
RWTexels = 10, // Vk storage texel buffer, glsl `imageBuffer` w/ layout
SPInput = 11, // Vk input attachment, glsl `[ ui]subpassInput`
Uniform = 12, // Vk uniform buffer, glsl `uniform <name> { ... }`
Struct = 13, // User-defined POD struct
// Max value
MAX = Struct
}; // enum class BaseType
struct ShaderType;
// Describes a user-defined struct type
struct StructType final
{
public:
struct Member final
{
string name;
uint32 arraySize;
const ShaderType* type;
}; // struct Member
StructType(const string& name, const std::vector<Member>& members);
StructType() : StructType("INVALID", {}) { }
~StructType() { }
/* Fields */
inline const string& name() const { return name_; }
inline const std::vector<Member>& members() const { return members_; }
inline const std::vector<uint32>& offsets() const { return offsets_; }
inline uint32 size() const { return size_; }
inline uint32 alignment() const { return alignment_; }
/* Member Access */
const Member* getMember(const string& name, uint32* offset = nullptr) const;
inline bool hasMember(const string& name) const { return !!getMember(name, nullptr); }
private:
string name_;
std::vector<Member> members_;
std::vector<uint32> offsets_;
uint32 size_;
uint32 alignment_;
}; // struct StructType
// The different ranks (dimension counts) that texel-like objects can have
enum class TexelRank : uint32
{
E1D = 0, // Single 1D texture
E2D = 1, // Single 2D texture
E3D = 2, // Single 3D texture
E1DArray = 3, // Array of 1D textures
E2DArray = 4, // Array of 2D textures
Cube = 5, // Single cubemap texture
Buffer = 6, // The dims specific to a ROTexels object
// Max value
MAX = Buffer
}; // enum class TexelRank
string TexelRankGetSuffix(TexelRank rank);
uint32 TexelRankGetComponentCount(TexelRank rank);
// The base types for texel formats
enum class TexelType : uint32
{
Signed = 0,
Unsigned = 1,
Float = 2,
UNorm = 3,
SNorm = 4,
MAX = SNorm
};
// Describes a texel format
struct TexelFormat final
{
public:
TexelFormat() : type{}, size{ 0 }, count{ 0 } { }
TexelFormat(TexelType type, uint32 size, uint32 count)
: type{ type }, size{ size }, count{ count }
{ }
/* Base Type Checks */
inline bool isSigned() const { return type == TexelType::Signed; }
inline bool isUnsigned() const { return type == TexelType::Unsigned; }
inline bool isFloat() const { return type == TexelType::Float; }
inline bool isUNorm() const { return type == TexelType::UNorm; }
inline bool isSNorm() const { return type == TexelType::SNorm; }
inline bool isIntegerType() const { return isSigned() || isUnsigned(); }
inline bool isFloatingType() const { return isFloat() || isUNorm() || isSNorm(); }
inline bool isNormlizedType() const { return isUNorm() || isSNorm(); }
/* Type Check */
bool isSame(const TexelFormat* format) const;
/* Names */
string getVSLName() const;
string getGLSLName() const;
string getVSLPrefix() const;
string getGLSLPrefix() const;
/* Conversion */
const ShaderType* asDataType() const;
public:
TexelType type;
uint32 size;
uint32 count;
}; // struct TexelFormat
// Contains complete type information (minus array size) about an object, variable, or result
struct ShaderType final
{
public:
ShaderType() : baseType{ BaseType::Void }, texel{} { }
ShaderType(BaseType numericType, uint32 size, uint32 components, uint32 columns)
: baseType{ numericType }, texel{}
{
numeric = { size, { components, columns } };
}
ShaderType(BaseType texelObjectType, TexelRank rank, const TexelFormat* format)
: baseType{ texelObjectType }, texel{ rank, format }
{ }
ShaderType(const BaseType bufferType, const ShaderType* structType)
: baseType{ bufferType }, texel{}
{
buffer.structType = structType;
}
ShaderType(const StructType* structType)
: baseType{ BaseType::Struct }, texel{}
{
userStruct.type = structType;
}
/* Base Type Checks */
inline bool isVoid() const { return baseType == BaseType::Void; }
inline bool isBoolean() const { return baseType == BaseType::Boolean; }
inline bool isSigned() const { return baseType == BaseType::Signed; }
inline bool isUnsigned() const { return baseType == BaseType::Unsigned; }
inline bool isFloat() const { return baseType == BaseType::Float; }
inline bool isSampler() const { return baseType == BaseType::Sampler; }
inline bool isImage() const { return baseType == BaseType::Image; }
inline bool isROBuffer() const { return baseType == BaseType::ROBuffer; }
inline bool isRWBuffer() const { return baseType == BaseType::RWBuffer; }
inline bool isROTexels() const { return baseType == BaseType::ROTexels; }
inline bool isRWTexels() const { return baseType == BaseType::RWTexels; }
inline bool isSPInput() const { return baseType == BaseType::SPInput; }
inline bool isUniform() const { return baseType == BaseType::Uniform; }
inline bool isStruct() const { return baseType == BaseType::Struct; }
/* Composite Type Checks */
inline bool isInteger() const { return isSigned() || isUnsigned(); }
inline bool isNumericType() const { return isInteger() || isFloat(); }
inline bool isScalar() const {
return (isNumericType() || isBoolean()) && (numeric.dims[0] == 1) && (numeric.dims[1] == 1);
}
inline bool isVector() const {
return (isNumericType() || isBoolean()) && (numeric.dims[0] != 1) && (numeric.dims[1] == 1);
}
inline bool isMatrix() const {
return isNumericType() && (numeric.dims[0] != 1) && (numeric.dims[1] != 1);
}
inline bool isTexelType() const { return isSampler() || isImage() || isROTexels() || isRWTexels() || isSPInput(); }
inline bool isBufferType() const { return isROBuffer() || isRWBuffer(); }
inline bool hasStructType() const { return isUniform() || isBufferType() || isStruct(); }
/* Casting */
bool isSame(const ShaderType* otherType) const;
bool hasImplicitCast(const ShaderType* targetType) const;
/* Names */
string getVSLName() const;
string getGLSLName() const;
/* Type-Specific Functions */
uint32 getBindingCount() const;
/* Operators */
inline bool operator == (const ShaderType& r) const { return (this == &r) || isSame(&r); }
inline bool operator != (const ShaderType& r) const { return (this != &r) && !isSame(&r); }
public:
BaseType baseType;
union
{
struct NumericInfo
{
uint32 size;
uint32 dims[2];
} numeric;
struct TexelInfo
{
TexelRank rank;
const TexelFormat* format;
} texel;
struct BufferInfo
{
const ShaderType* structType;
} buffer;
struct StructInfo
{
const StructType* type;
} userStruct;
};
}; // struct ShaderType
// Contains a collection of types for a specific shader
class TypeList final
{
public:
using TypeMap = std::unordered_map<string, ShaderType>;
using StructMap = std::unordered_map<string, StructType>;
using FormatMap = std::unordered_map<string, TexelFormat>;
TypeList() : types_{ }, structs_{ }, error_{ } { Initialize(); }
~TypeList() { }
inline const string& lastError() const { return error_; }
/* Types */
const ShaderType* addType(const string& name, const ShaderType& type);
const ShaderType* getType(const string& name) const;
const StructType* addStructType(const string& name, const StructType& type);
const StructType* getStructType(const string& name) const;
const ShaderType* parseOrGetType(const string& name);
/* Access */
inline static const TypeMap& BuiltinTypes() {
if (BuiltinTypes_.empty()) {
Initialize();
}
return BuiltinTypes_;
}
static const ShaderType* GetBuiltinType(const string& name);
static const TexelFormat* GetTexelFormat(const string& format);
static const ShaderType* GetNumericType(BaseType baseType, uint32 size, uint32 dim0, uint32 dim1);
static const ShaderType* ParseGenericType(const string& baseType);
private:
static void Initialize();
private:
TypeMap types_; // Types added by the shader, does not duplicate BuiltinTypes_
StructMap structs_;
mutable string error_;
static bool Initialized_;
static TypeMap BuiltinTypes_;
static TypeMap GenericTypes_;
static FormatMap Formats_;
VSL_NO_COPY(TypeList)
VSL_NO_MOVE(TypeList)
}; // class TypeList
} // namespace vsl
| 9,350 | 3,167 |
#include "utils.hpp"
#include "cli.hpp"
#include <mach-o/dyld_images.h>
bool readTaskMemory(task_t t, vm_address_t addr, void *buf, unsigned long len)
{
if(addr <= 0)
Serror("memory read address < 0");
if(len <= 0)
Serror("memory read length <0");
vm_size_t dataCnt = len;
kern_return_t kr = vm_read_overwrite(t, addr, len, (vm_address_t)buf, (vm_size_t *)&dataCnt);
if (kr)
return false;
if (len != dataCnt)
{
warnx("rt_read size return not match!");
return false;
}
return true;
}
char *readTaskString(task_t t, vm_address_t addr)
{
char x = '\0';
vm_address_t end;
char *str = NULL;
//string upper limit 0x1000
end = memorySearch(t, addr, addr + 0x1000, &x, 1);
if (!end)
{
return NULL;
}
str = (char *)malloc(end - addr + 1);
if (readTaskMemory(t, addr, str, end - addr + 1)) {
return str;
}
return NULL;
}
task_t pid2task(unsigned int pid)
{
task_t t;
kern_return_t ret = task_for_pid(mach_task_self(), pid, &t);
if (ret != KERN_SUCCESS) {
printf("Attach to: %d Failed: %d %s\n", pid, ret, mach_error_string(ret));
return 0;
}
return t;
}
//get dyld load address by task_info, TASK_DYLD_INFO
vm_address_t getDyldLoadAddress(task_t task) {
//http://stackoverflow.com/questions/4309117/determining-programmatically-what-modules-are-loaded-in-another-process-os-x
kern_return_t kr;
task_flavor_t flavor = TASK_DYLD_INFO;
task_dyld_info_data_t infoData;
mach_msg_type_number_t task_info_outCnt = TASK_DYLD_INFO_COUNT;
kr = task_info(task,
flavor,
(task_info_t)&infoData,
&task_info_outCnt
);
if(kr){
Serror("getDyldLoadAddress:task_info error");
return 0;
}
struct dyld_all_image_infos *allImageInfos = (struct dyld_all_image_infos *)infoData.all_image_info_addr;
allImageInfos = (struct dyld_all_image_infos *)malloc(sizeof(struct dyld_all_image_infos));
if(readTaskMemory(task, infoData.all_image_info_addr, allImageInfos, sizeof(struct dyld_all_image_infos))) {
return (vm_address_t)(allImageInfos->dyldImageLoadAddress);
} else {
Serror("getDyldLoadAddress:readTaskMemory error");
return 0;
}
}
vm_address_t memorySearch(task_t task, vm_address_t start, vm_address_t end, char *data, unsigned long len)
{
if(start <= 0)
Serror("memory search address < 0");
if(start > end)
Serror("memeory search end < start");
vm_address_t addr = start;
char *buf = (char *)malloc(len);
while (end > addr)
{
if (readTaskMemory(task, addr, buf, len))
if (!memcmp(buf, data, len))
{
return addr;
}
addr += len;
}
return 0;
// unsigned long search_block_size = 0x1000;
// vm_address_t addr = start;
//
// char *buf = (char *)malloc(search_block_size + len);
// unsigned long search_len;
// search_len = search_block_size;
//
// while(end >= addr + len || (!end)) {
//
// if(readTaskMemory(task, addr, buf, search_len + len - 1)) {
// if(len == 1) {
// std::cout << "memorySearch: " << buf << std::endl;
// }
// for(char *p = buf; p < buf + search_len; p++){
//
// if(!memcmp(p, data, len)) {
// return addr + p - buf;
// }
// }
// } else {
// if(len == 1) {
// sleep(-1);
// std::cout << "memorySearch: error" << std::endl;
// }
// }
//
// addr += search_block_size;
// }
//
// search_len = end - addr - (len - 1);
// if(search_len >0 && readTaskMemory(task, addr, buf, search_len + len - 1)) {
// for(char *p = buf; p < buf + search_len; p++){
// if(!memcmp(p, data, len)) {
// return addr + p - buf;
// }
// }
// }
// return 0;
}
| 4,223 | 1,498 |
#include "precheader.h"
#include "Scene.h"
#include "renderer/ModelLoader.h"
#include "renderer/Renderer.h"
#include "renderer/MaterialLibrary.h"
#include <glm/gtx/string_cast.hpp>
namespace vengine
{
void Scene::init(Ref<Renderer> renderer)
{
m_renderer = renderer;
create_camera();
}
void Scene::on_update()
{
//Try to move setting params out from loop
m_renderer->set_camera_params(m_active_camera);
for (auto&& [view_entity, dir_light_component, transform_component] : m_registry.view<DirLightComponent, TransformComponent>().each())
{
m_renderer->add_dir_light(dir_light_component, transform_component.translation);
}
for (auto&& [view_entity, point_light_component, transform_component] : m_registry.view<PointLightComponent, TransformComponent>().each())
{
m_renderer->add_point_light(point_light_component, transform_component.translation);
}
for (auto&& [view_entity, sphere_area_light_component, transform_component] : m_registry.view<SphereAreaLightComponent, TransformComponent>().each())
{
m_renderer->add_sphere_area_light(sphere_area_light_component, transform_component.translation);
}
for (auto&& [view_entity, tube_area_light_component, transform_component] : m_registry.view<TubeAreaLightComponent, TransformComponent>().each())
{
m_renderer->add_tube_area_light(tube_area_light_component, transform_component.translation);
}
for (auto&& [view_entity, model_component, transform_component, materials_component]
: m_registry.view<ModelComponent, TransformComponent, MaterialsComponent>().each())
{
auto& mesh = ModelLoader::get_mesh(model_component.filepath);
mesh.is_casting_shadow = true;
mesh.transform = transform_component.get_transform();
mesh.materials = materials_component;
m_renderer->add_drawable(mesh);
}
}
void Scene::on_event(const Event& event)
{
m_active_camera.on_event(event);
}
[[nodiscard]] entt::entity Scene::create_empty_entity(const std::string& tag)
{
const auto entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, tag);
return entity;
}
void Scene::create_camera()
{
m_game_camera_entity = m_registry.create();
m_registry.emplace<TagComponent>(m_game_camera_entity, "Camera");
const Camera camera{ 45.0f, 0.1f, 500.f };
m_registry.emplace<CameraComponent>(m_game_camera_entity, camera);
m_registry.emplace<TransformComponent>(m_game_camera_entity);
}
void Scene::create_model(const std::string& model_path)
{
const auto entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Model entity");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<ModelComponent>(entity, model_path);
m_registry.emplace<MaterialsComponent>(entity);
}
void Scene::destroy_entity(entt::entity entity)
{
m_registry.destroy(entity);
}
void Scene::set_game_camera_entity(entt::entity entity)
{
m_game_camera_entity = entity;
}
void Scene::clear()
{
m_registry.clear();
}
void Scene::create_dir_light()
{
if (m_registry.view<DirLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Directional light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<DirLightComponent>(entity);
}
void Scene::create_point_light()
{
if (m_registry.view<PointLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Point light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<PointLightComponent>(entity);
}
void Scene::create_sphere_area_light()
{
if (m_registry.view<SphereAreaLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Sphere area light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<SphereAreaLightComponent>(entity);
}
void Scene::create_tube_area_light()
{
if(m_registry.view<TubeAreaLightComponent>().size() == Renderer::get_max_lights())
{
LOG_WARNING("Too many lights")
return;
}
const entt::entity entity = m_registry.create();
m_registry.emplace<TagComponent>(entity, "Tube area light");
m_registry.emplace<TransformComponent>(entity);
m_registry.emplace<TubeAreaLightComponent>(entity);
}
void Scene::start_game()
{
if(m_registry.valid(m_game_camera_entity) && m_registry.has<CameraComponent>(m_game_camera_entity))
{
m_is_gamemode_on = true;
m_active_camera = m_registry.get<CameraComponent>(m_game_camera_entity).camera;
m_active_camera.set_position(m_registry.get<TransformComponent>(m_game_camera_entity).translation);
}
else
{
LOG_ERROR("There is no camera in the scene")
}
}
void Scene::stop_game()
{
m_is_gamemode_on = false;
m_active_camera = m_editor_camera;
}
void Scene::set_environment_texture(const TextureGL& texture) const
{
m_renderer->set_scene_environment_map(texture);
}
void Scene::set_exposure(float exposure) const
{
m_renderer->set_exposure(exposure);
}
}
| 5,322 | 2,029 |
#include <vector>
#include "third_party/gflags/include/gflags.h"
#include "third_party/glog/include/logging.h"
using namespace std;
// Problem: https://leetcode-cn.com/problems/2-keys-keyboard
class Solution {
public:
int minSteps(int n) {
int ret = 0;
for (int i = 2; i * i < n; ++i) {
while (n % i == 0) {
n /= i;
ret += i;
}
}
if (n > 1) ret += n;
return ret;
}
};
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
gflags::ParseCommandLineFlags(&argc, &argv, false);
Solution solu;
for (int i = 3; i < 1000; ++i) {
int ret = solu.minSteps(i);
LOG(INFO) << "ret: " << ret;
}
return 0;
}
| 688 | 287 |
#include <iostream>
using namespace std;
void print_fun1()
{
cout << "In Section1_1AuxC, function print one" << endl;
} | 126 | 46 |
/*****************************************************************************
*
* main.cpp file for the saliency program VOCUS2.
* A detailed description of the algorithm can be found in the paper: "Traditional Saliency Reloaded: A Good Old Model in New Shape", S. Frintrop, T. Werner, G. Martin Garcia, in Proceedings of the IEEE International Conference on Computer Vision and Pattern Recognition (CVPR), 2015.
* Please cite this paper if you use our method.
*
* Implementation: Thomas Werner (wernert@cs.uni-bonn.de)
* Design and supervision: Simone Frintrop (frintrop@iai.uni-bonn.de)
*
* Version 1.1
*
* This code is published under the MIT License
* (see file LICENSE.txt for details)
*
******************************************************************************/
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <sys/stat.h>
#include "VOCUS2.h"
using namespace std;
using namespace cv;
struct stat sb;
int WEBCAM_MODE = -1;
bool VIDEO_MODE = false;
float MSR_THRESH = 0.75; // most salient region
bool SHOW_OUTPUT = true;
string WRITE_OUT = "";
string WRITE_PATH = "";
string OUTOUT = "";
bool WRITEPATHSET = false;
bool CENTER_BIAS = false;
float SIGMA, K;
int MIN_SIZE, METHOD;
vector<string> split_string(const string &s, char delim) {
vector<string> elems;
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
void print_usage(char* argv[]){
cout << "\nUsage: " << argv[0] << " [OPTIONS] <input-file(s)>" << endl << endl;
cout << "===== SALIENCY =====" << endl << endl;
cout << " -x <name>" << "\t\t" << "Config file (is loaded first, additional options have higher priority)" << endl << endl;
cout << " -C <value>" << "\t\t" << "Used colorspace [default: 1]:" << endl;
cout << "\t\t " << "0: LAB" << endl;
cout << "\t\t " << "1: Opponent (CoDi)" << endl;
cout << "\t\t " << "2: Opponent (Equal domains)\n" << endl;
cout << " -f <value>" << "\t\t" << "Fusing operation (Feature maps) [default: 0]:" << endl;
cout << " -F <value>" << "\t\t" << "Fusing operation (Conspicuity/Saliency maps) [default: 0]:" << endl;
cout << "\t\t " << "0: Arithmetic mean" << endl;
cout << "\t\t " << "1: Max" << endl;
cout << "\t\t " << "2: Uniqueness weight\n" << endl;
cout << " -p <value>" << "\t\t" << "Pyramidal structure [default: 2]:" << endl;
cout << "\t\t " << "0: Two independant pyramids (Classic)" << endl;
cout << "\t\t " << "1: Two pyramids derived from a base pyramid (CoDi-like)" << endl;
cout << "\t\t " << "2: Surround pyramid derived from center pyramid (New)\n" << endl;
cout << " -l <value>" << "\t\t" << "Start layer (included) [default: 0]" << endl << endl;
cout << " -L <value>" << "\t\t" << "Stop layer (included) [default: 4]" << endl << endl;
cout << " -S <value>" << "\t\t" << "No. of scales [default: 2]" << endl << endl;
cout << " -c <value>" << "\t\t" << "Center sigma [default: 2]" << endl << endl;
cout << " -s <value>" << "\t\t" << "Surround sigma [default: 10]" << endl << endl;
//cout << " -r" << "\t\t" << "Use orientation [default: off] " << endl << endl;
cout << " -e" << "\t\t" << "Use Combined Feature [default: off]" << endl << endl;
cout << "===== MISC (NOT INCLUDED IN A CONFIG FILE) =====" << endl << endl;
cout << " -v <id>" << "\t\t" << "Webcam source" << endl << endl;
cout << " -V" << "\t\t" << "Video files" << endl << endl;
cout << " -t <value>" << "\t\t" << "MSR threshold (percentage of fixation) [default: 0.75]" << endl << endl;
cout << " -N" << "\t\t" << "No visualization" << endl << endl;
cout << " -o <path>" << "\t\t" << "WRITE results to specified path [default: <input_path>/saliency/*]" << endl << endl;
cout << " -w <path>" << "\t\t" << "WRITE all intermediate maps to an existing folder" << endl << endl;
cout << " -b" << "\t\t" << "Add center bias to the saliency map\n" << endl << endl;
}
bool process_arguments(int argc, char* argv[], VOCUS2_Cfg& cfg, vector<char*>& files){
if(argc == 1) return false;
int c;
while((c = getopt(argc, argv, "bnreNhVC:x:f:F:v:l:o:L:S:c:s:t:p:w:G:")) != -1){
switch(c){
case 'h': return false;
case 'C': cfg.c_space = ColorSpace(atoi(optarg)); break;
case 'f': cfg.fuse_feature = FusionOperation(atoi(optarg)); break;
case 'F': cfg.fuse_conspicuity = FusionOperation(atoi(optarg)); break;
case 'v': WEBCAM_MODE = atoi(optarg) ; break;
case 'l': cfg.start_layer = atoi(optarg); break;
case 'L': cfg.stop_layer = atoi(optarg); break;
case 'S': cfg.n_scales = atoi(optarg); break;
case 'c': cfg.center_sigma = atof(optarg); break;
case 's': cfg.surround_sigma = atof(optarg); break;
case 'V': VIDEO_MODE = true; break;
case 't': MSR_THRESH = atof(optarg); break;
case 'N': SHOW_OUTPUT = false; break;
case 'o': WRITEPATHSET = true; WRITE_PATH = string(optarg); break;
case 'n': cfg.normalize = true; break;
case 'r': cfg.orientation = true; break;
case 'e': cfg.combined_features = true; break;
case 'p': cfg.pyr_struct = PyrStructure(atoi(optarg));
case 'w': WRITE_OUT = string(optarg); break;
case 'b': CENTER_BIAS = true; break;
case 'x': break;
default:
return false;
}
}
if(MSR_THRESH < 0 || MSR_THRESH > 1){
cerr << "MSR threshold must be in the range [0,1]" << endl;
return false;
}
if(cfg.start_layer < 0){
cerr << "Start layer must be positive" << endl;
return false;
}
if(cfg.start_layer > cfg.stop_layer){
cerr << "Start layer cannot be larger than stop layer" << endl;
return false;
}
if(cfg.n_scales <= 0){
cerr << "Numbor of scales must be > 0" << endl;
return false;
}
if(cfg.center_sigma <= 0){
cerr << "Center sigma must be positive" << endl;
return false;
}
if(cfg.surround_sigma <= cfg.center_sigma){
cerr << "Surround sigma must be positive and largen than center sigma" << endl;
return false;
}
for (int i = optind; i < argc; i++)
files.push_back(argv[i]);
if (files.size() == 0 && WEBCAM_MODE < 0) {
return false;
}
if(files.size() == 0 && VIDEO_MODE){
return false;
}
if(WEBCAM_MODE >= 0 && VIDEO_MODE){
return false;
}
return true;
}
// if parameter x specified, load config file
VOCUS2_Cfg create_base_config(int argc, char* argv[]){
VOCUS2_Cfg cfg;
int c;
while((c = getopt(argc, argv, "NbnrehVC:x:f:F:v:l:L:S:o:c:s:t:p:w:G:")) != -1){
if(c == 'x') cfg.load(optarg);
}
optind = 1;
return cfg;
}
//get most salient region
vector<Point> get_msr(Mat& salmap){
double ma;
Point p_ma;
minMaxLoc(salmap, nullptr, &ma, nullptr, &p_ma);
vector<Point> msr;
msr.push_back(p_ma);
int pos = 0;
float thresh = MSR_THRESH*ma;
Mat considered = Mat::zeros(salmap.size(), CV_8U);
considered.at<uchar>(p_ma) = 1;
while(pos < (int)msr.size()){
int r = msr[pos].y;
int c = msr[pos].x;
for(int dr = -1; dr <= 1; dr++){
for(int dc = -1; dc <= 1; dc++){
if(dc == 0 && dr == 0) continue;
if(considered.ptr<uchar>(r+dr)[c+dc] != 0) continue;
if(r+dr < 0 || r+dr >= salmap.rows) continue;
if(c+dc < 0 || c+dc >= salmap.cols) continue;
if(salmap.ptr<float>(r+dr)[c+dc] >= thresh){
msr.push_back(Point(c+dc, r+dr));
considered.ptr<uchar>(r+dr)[c+dc] = 1;
}
}
}
pos++;
}
return msr;
}
int main(int argc, char* argv[]) {
VOCUS2_Cfg cfg = create_base_config(argc, argv);
vector<char*> files; // names of input images or video files
bool correct = process_arguments(argc, argv, cfg, files);
if(!correct){
print_usage(argv);
return EXIT_FAILURE;
}
VOCUS2 vocus2(cfg);
if(WEBCAM_MODE <= -1 && !VIDEO_MODE){ // if normal image
double overall_time = 0;
if(stat(WRITE_PATH.c_str(), &sb)!=0){
if(WRITEPATHSET){
std::cout << "Creating directory..." << std::endl;
mkdir(WRITE_PATH.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
}
//test if data is image data
if(files.size()>=1){
Mat img = imread(files[0]);
if( !(img.channels()==3) ){
std::cout << "ABBORT: Inconsistent Image Data"<< img.channels() << std::endl;
exit(-1);
}
}
//compute saliency
for(size_t i = 0; i < files.size(); i++){
cout << "Opening " << files[i] << " (" << i+1 << "/" << files.size() << "), ";
Mat img = imread(files[i], 1);
long long start = getTickCount();
Mat salmap;
vocus2.process(img);
if(CENTER_BIAS)
salmap = vocus2.add_center_bias(0.00005);
else
salmap = vocus2.get_salmap();
long long stop = getTickCount();
double elapsed_time = (stop-start)/getTickFrequency();
cout << elapsed_time << "sec" << endl;
overall_time += elapsed_time;
//WRITE resulting saliency maps to path/directory
string pathStr(files[i]);
int found = 0;
found = pathStr.find_last_of("/\\");
string path = pathStr.substr(0,found);
string filename_plus = pathStr.substr(found+1);
string filename = filename_plus.substr(0,filename_plus.find_last_of("."));
string WRITE_NAME = filename + "_saliency";
string WRITE_result_PATH;
//if no path set, write to /saliency directory
if(!WRITEPATHSET){
//get the folder, if possible
if(found>=0){
string WRITE_DIR = "/saliency/";
if ( !(stat(WRITE_PATH.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))){
mkdir((path+WRITE_DIR).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
WRITE_result_PATH = path + WRITE_DIR + WRITE_NAME + ".png";
}
else{ //if images are in the source folder
string WRITE_DIR = "saliency/";
if ( !(stat(WRITE_PATH.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))){
mkdir((WRITE_DIR).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
WRITE_result_PATH = WRITE_DIR + WRITE_NAME + ".png";
}
}
else{
WRITE_result_PATH = WRITE_PATH+"/"+WRITE_NAME+".png";
}
std::cout << "WRITE result to " << WRITE_result_PATH << std::endl << std::endl;
imwrite(WRITE_result_PATH.c_str(), salmap*255.f);
if(WRITE_OUT.compare("") != 0) vocus2.write_out(WRITE_OUT);
vector<Point> msr = get_msr(salmap);
Point2f center;
float rad;
minEnclosingCircle(msr, center, rad);
if(rad >= 5 && rad <= max(img.cols, img.rows)){
circle(img, center, (int)rad, Scalar(0,0,255), 3);
}
if(SHOW_OUTPUT){
imshow("input", img);
imshow("saliency normalized", salmap);
waitKey(0);
}
img.release();
}
cout << "Avg. runtime per image: " << overall_time/(double)files.size() << endl;
}
else if(WEBCAM_MODE >= 0 || !VIDEO_MODE){ // data from webcam
double overall_time = 0;
int n_frames = 0;
VideoCapture vc(WEBCAM_MODE);
if(!vc.isOpened()) return EXIT_FAILURE;
Mat img;
while(vc.read(img)){
n_frames++;
long start = getTickCount();
Mat salmap;
vocus2.process(img);
if(CENTER_BIAS)
salmap = vocus2.add_center_bias(0.00005);
else
salmap = vocus2.get_salmap();
long stop = getTickCount();
double elapsed_time = (stop-start)/getTickFrequency();
cout << "frame " << n_frames << ": " << elapsed_time << "sec" << endl;
overall_time += elapsed_time;
vector<Point> msr = get_msr(salmap);
Point2f center;
float rad;
minEnclosingCircle(msr, center, rad);
if(SHOW_OUTPUT){
imshow("input (ESC to exit)", img);
imshow("saliency streched (ESC to exit)", salmap);
int key_code = waitKey(30);
if(key_code == 113 || key_code == 27) break;
}
img.release();
}
vc.release();
cout << "Avg. runtime per frame: " << overall_time/(double)n_frames << endl;
}
else{ // Video data
for(size_t i = 0; i < files.size(); i++){ // loop over video files
double overall_time = 0;
int n_frames = 0;
VideoCapture vc(files[i]);
if(!vc.isOpened()) return EXIT_FAILURE;
Mat img;
while(vc.read(img)){
n_frames++;
long start = getTickCount();
Mat salmap;
vocus2.process(img);
if(!CENTER_BIAS) salmap = vocus2.get_salmap();
else salmap = vocus2.add_center_bias(0.5);
long stop = getTickCount();
double elapsed_time = (stop-start)/getTickFrequency();
cout << "frame " << n_frames << ": " << elapsed_time << "sec" << endl;
overall_time += elapsed_time;
vector<Point> msr = get_msr(salmap);
Point2f center;
float rad;
minEnclosingCircle(msr, center, rad);
if(SHOW_OUTPUT){
imshow("input (ESC to exit)", img);
imshow("saliency streched (ESC to exit)", salmap);
int key_code = waitKey(30);
if(key_code == 113 || key_code == 27) break;
}
img.release();
}
vc.release();
cout << "Avg. runtime per frame: " << overall_time/(double)n_frames << endl;
}
}
return EXIT_SUCCESS;
}
| 12,853 | 5,644 |
#include <fstream>
#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/scoped_array.hpp>
#include <boost/program_options.hpp>
namespace
{
const char s_version[] = "x3 parser version 1.0.0";
// at least need room for the header
const boost::uint32_t s_minFileSize = 12;
// this isn't actually a hard limit, but larger sizes are unexpected
const boost::uint32_t s_maxFileSize = 100000;
struct x3_header
{
// total length is the file size - 4 bytes (ie. itself)
boost::uint32_t m_totalLength;
// unused?
boost::uint32_t m_reserved0;
// unused?
boost::uint32_t m_reserved1;
};
struct x3_entry
{
boost::uint32_t m_length;
boost::uint32_t m_type;
};
bool parseCommandLine(int p_argCount, const char* p_argArray[], std::string& p_file)
{
boost::program_options::options_description description("options");
description.add_options()
("help,h", "A list of command line options")
("version,v", "Display version information")
("file,f", boost::program_options::value<std::string>(), "The file to parse");
boost::program_options::variables_map argv_map;
try
{
boost::program_options::store(
boost::program_options::parse_command_line(
p_argCount, p_argArray, description), argv_map);
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cout << description << std::endl;
return false;
}
boost::program_options::notify(argv_map);
if (argv_map.empty() || argv_map.count("help"))
{
std::cout << description << std::endl;
return false;
}
if (argv_map.count("version"))
{
std::cout << "Version: " << ::s_version << std::endl;
return false;
}
if (argv_map.count("file"))
{
p_file.assign(argv_map["file"].as<std::string>());
return true;
}
return false;
}
}
int main(int p_argc, const char** p_argv)
{
std::string file;
if (!parseCommandLine(p_argc, p_argv, file))
{
return EXIT_FAILURE;
}
std::ifstream fileStream(file, std::ios::in | std::ios::binary | std::ios::ate);
if (!fileStream.is_open())
{
std::cerr << "Failed to open " << file << std::endl;
return EXIT_FAILURE;
}
std::streampos fileSize = fileStream.tellg();
if (fileSize < s_minFileSize || fileSize > s_maxFileSize)
{
std::cerr << "Bad file size: " << fileSize << std::endl;
fileStream.close();
return EXIT_FAILURE;
}
// read the file into an array
boost::scoped_array<char> memblock(new char[fileSize]);
fileStream.seekg(0, std::ios::beg);
fileStream.read(memblock.get(), fileSize);
fileStream.close();
const x3_header* head = reinterpret_cast<const x3_header*>(memblock.get());
if (head->m_totalLength != (static_cast<boost::uint32_t>(fileSize) - 4))
{
std::cerr << "Invalid total size." << std::endl;
return EXIT_FAILURE;
}
const char* memoryEnd = memblock.get() + fileSize;
const char* memoryCurrent = memblock.get() + 12;
for (const x3_entry* entry = reinterpret_cast<const x3_entry*>(memoryCurrent);
(reinterpret_cast<const char*>(entry) + 12) < memoryEnd;
memoryCurrent += entry->m_length + 4, entry = reinterpret_cast<const x3_entry*>(memoryCurrent))
{
// the outter entry should always be of type 0x1e
if (entry->m_type != 0x1e)
{
std::cerr << "Parsing error." << std::endl;
return EXIT_FAILURE;
}
for (const x3_entry* inner_entry = reinterpret_cast<const x3_entry*>(memoryCurrent + 12);
reinterpret_cast<const char*>(inner_entry) < (memoryCurrent + entry->m_length + 4);
inner_entry = reinterpret_cast<const x3_entry*>(reinterpret_cast<const char*>(inner_entry) + inner_entry->m_length + 4))
{
switch (inner_entry->m_type)
{
case 0x04: // the router number
{
const char* route = reinterpret_cast<const char*>(inner_entry) + inner_entry->m_length;
std::cout << ",";
for (boost::uint8_t i = 0; i < 4; i++)
{
if (route[i] != 0)
{
std::cout << route[i];
}
}
std::cout << std::endl;
}
break;
case 0x07: // the binary name
{
std::string path(reinterpret_cast<const char*>(inner_entry) + 20, inner_entry->m_length - 16);
std::cout << path;
}
break;
default:
break;
}
}
}
return EXIT_SUCCESS;
}
| 5,112 | 1,607 |
/*
Oscar Efrain RAMOS PONCE, LAAS-CNRS
Date: 28/10/2014
Object to estimate a polynomial of first order that fits some data.
*/
#ifndef _LIN_ESTIMATOR_HH_
#define _LIN_ESTIMATOR_HH_
#include <sot/torque_control/utils/poly-estimator.hh>
/**
* Object to fit a first order polynomial to a given data. This can be used to
* compute the velocities given the positions.
*/
class LinEstimator : public PolyEstimator {
public:
/**
* Create a linear estimator on a window of length N
* @param N is the window length.
* @param dim is the dimension of the input elements (number of dofs).
* @param dt is the control (sampling) time.
*/
LinEstimator(const unsigned int& N, const unsigned int& dim, const double& dt = 0.0);
virtual void estimate(std::vector<double>& estimee, const std::vector<double>& el);
virtual void estimateRecursive(std::vector<double>& estimee, const std::vector<double>& el, const double& time);
void getEstimateDerivative(std::vector<double>& estimeeDerivative, const unsigned int order);
private:
virtual void fit();
virtual double getEsteeme();
int dim_; // size of the data
// Sums for the recursive computation
double sum_ti_;
double sum_ti2_;
std::vector<double> sum_xi_;
std::vector<double> sum_tixi_;
// coefficients of the polynomial c2*x^2 + c1*x + c0
std::vector<double> c0_;
std::vector<double> c1_;
// Rows of the pseudo-inverse (when assuming constant sample time)
double* pinv0_;
double* pinv1_;
// Half of the maximum time (according to the size of the window and dt)
double tmed_;
};
#endif
| 1,603 | 531 |
#include <iostream>
#include <stdio.h>
#include <string>
#include <numeric>
#include <algorithm>
// supplied values
int blockSize[] = {5,10,50,100};
int numBlocks = sizeof blockSize / sizeof blockSize[0];
int processSize[] = {11,6,34,5,25,60};
int numberOfProcesses = sizeof processSize / sizeof processSize[0];
// process struct
struct Process
{
int pid;
int blockNumberFF;
int blockNumberNF;
int size;
};
int main()
{
// create an array to hold our processes
Process* list[numberOfProcesses];
// populate array
for(int i = 0; i < numberOfProcesses; i++)
{
list[i] = new Process{ i+1 , 0 , 0 , processSize[i] };
}
// First First
for(int pid = 0; pid < numberOfProcesses; pid++)
{
Process* proc = list[pid];
for(int block = 0; block < numBlocks; block++)
{
// if the process size is less than or equal to block size, assign it to this block
if (proc->size <= blockSize[block] ) {
proc->blockNumberFF = block + 1;
// subtract size from remaining
blockSize[block] -= proc->size;
//exit loop
break;
}
}
}
int blockSize[] = {5,10,50,100};
// Best Fit
int lastblock = 0;
for(int pid = 0; pid < numberOfProcesses; pid++)
{
for(int block = lastblock; block < numBlocks; block++)
{
Process* proc = list[pid];
// if the process size is less than or equal to block size, assign it to this block
if (proc->size <= blockSize[block] && proc->blockNumberNF < 1 ) {
proc->blockNumberNF = block + 1;
// subtract size from remaining
blockSize[block] -= proc->size;
lastblock=block;
}
}
}
// print processes
printf("First Fit:\nPID Process Size Block no.\n");
for(int pid = 0; pid < numberOfProcesses; pid++)
{
Process* proc = list[pid];
printf(" %d %2d %d\n",proc->pid,proc->size,proc->blockNumberFF);
}
// print processes
printf("Next Fit:\nPID Process Size Block no.\n");
for(int pid = 0; pid < numberOfProcesses; pid++)
{
Process* proc = list[pid];
if (proc->blockNumberNF==0) {
printf(" %d %2d %s\n",proc->pid,proc->size,"Not Allocated");
}
else
{
printf(" %d %2d %d\n",proc->pid,proc->size,proc->blockNumberNF);
}
}
} | 2,213 | 870 |
// Filename: txaLine.cxx
// Created by: drose (30Nov00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "txaLine.h"
#include "pal_string_utils.h"
#include "eggFile.h"
#include "palettizer.h"
#include "textureImage.h"
#include "sourceTextureImage.h"
#include "paletteGroup.h"
#include "pnotify.h"
#include "pnmFileType.h"
////////////////////////////////////////////////////////////////////
// Function: TxaLine::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
TxaLine::
TxaLine() {
_size_type = ST_none;
_scale = 0.0;
_x_size = 0;
_y_size = 0;
_aniso_degree = 0;
_num_channels = 0;
_format = EggTexture::F_unspecified;
_force_format = false;
_generic_format = false;
_keep_format = false;
_alpha_mode = EggRenderMode::AM_unspecified;
_wrap_u = EggTexture::WM_unspecified;
_wrap_v = EggTexture::WM_unspecified;
_quality_level = EggTexture::QL_unspecified;
_got_margin = false;
_margin = 0;
_got_coverage_threshold = false;
_coverage_threshold = 0.0;
_color_type = (PNMFileType *)NULL;
_alpha_type = (PNMFileType *)NULL;
}
////////////////////////////////////////////////////////////////////
// Function: TxaLine::parse
// Access: Public
// Description: Accepts a string that defines a line of the .txa file
// and parses it into its constinuent parts. Returns
// true if successful, false on error.
////////////////////////////////////////////////////////////////////
bool TxaLine::
parse(const string &line) {
size_t colon = line.find(':');
if (colon == string::npos) {
nout << "Colon required.\n";
return false;
}
// Chop up the first part of the string (preceding the colon) into
// its individual words. These are patterns to match.
vector_string words;
extract_words(line.substr(0, colon), words);
vector_string::iterator wi;
for (wi = words.begin(); wi != words.end(); ++wi) {
string word = (*wi);
// If the pattern ends in the string ".egg", and only if it ends
// in this string, it is deemed an egg pattern and will only be
// tested against egg files. If it ends in anything else, it is
// deemed a texture pattern and will only be tested against
// textures.
if (word.length() > 4 && word.substr(word.length() - 4) == ".egg") {
GlobPattern pattern(word);
pattern.set_case_sensitive(false);
_egg_patterns.push_back(pattern);
} else {
// However, the filename extension, if any, is stripped off
// because the texture key names nowadays don't include them.
size_t dot = word.rfind('.');
if (dot != string::npos) {
word = word.substr(0, dot);
}
GlobPattern pattern(word);
pattern.set_case_sensitive(false);
_texture_patterns.push_back(pattern);
}
}
if (_egg_patterns.empty() && _texture_patterns.empty()) {
nout << "No texture or egg filenames given.\n";
return false;
}
// Now chop up the rest of the string (following the colon) into its
// individual words. These are keywords and size indications.
words.clear();
extract_words(line.substr(colon + 1), words);
wi = words.begin();
while (wi != words.end()) {
const string &word = *wi;
nassertr(!word.empty(), false);
if (isdigit(word[0])) {
// This is either a new size or a scale percentage.
if (_size_type != ST_none) {
nout << "Invalid repeated size request: " << word << "\n";
return false;
}
if (word[word.length() - 1] == '%') {
// It's a scale percentage!
_size_type = ST_scale;
string tail;
_scale = string_to_double(word, tail);
if (!(tail == "%")) {
// This is an invalid number.
return false;
}
++wi;
} else {
// Collect a number of consecutive numeric fields.
pvector<int> numbers;
while (wi != words.end() && isdigit((*wi)[0])) {
const string &word = *wi;
int num;
if (!string_to_int(word, num)) {
nout << "Invalid size: " << word << "\n";
return false;
}
numbers.push_back(num);
++wi;
}
if (numbers.size() < 2) {
nout << "At least two size numbers must be given, or a percent sign used to indicate scaling.\n";
return false;
} else if (numbers.size() == 2) {
_size_type = ST_explicit_2;
_x_size = numbers[0];
_y_size = numbers[1];
} else if (numbers.size() == 3) {
_size_type = ST_explicit_3;
_x_size = numbers[0];
_y_size = numbers[1];
_num_channels = numbers[2];
} else {
nout << "Too many size numbers given.\n";
return false;
}
}
} else {
// The word does not begin with a digit; therefore it's either a
// keyword or an image file type request.
if (word == "omit") {
_keywords.push_back(KW_omit);
} else if (word == "nearest") {
_keywords.push_back(KW_nearest);
} else if (word == "linear") {
_keywords.push_back(KW_linear);
} else if (word == "mipmap") {
_keywords.push_back(KW_mipmap);
} else if (word == "cont") {
_keywords.push_back(KW_cont);
} else if (word == "margin") {
++wi;
if (wi == words.end()) {
nout << "Argument required for 'margin'.\n";
return false;
}
const string &arg = (*wi);
if (!string_to_int(arg, _margin)) {
nout << "Not an integer: " << arg << "\n";
return false;
}
if (_margin < 0) {
nout << "Invalid margin: " << _margin << "\n";
return false;
}
_got_margin = true;
} else if (word == "aniso") {
++wi;
if (wi == words.end()) {
nout << "Integer argument required for 'aniso'.\n";
return false;
}
const string &arg = (*wi);
if (!string_to_int(arg, _aniso_degree)) {
nout << "Not an integer: " << arg << "\n";
return false;
}
if ((_aniso_degree < 2) || (_aniso_degree > 16)) {
// make it an error to specific degree 0 or 1, which means no anisotropy so it's probably an input mistake
nout << "Invalid anistropic degree (range is 2-16): " << _aniso_degree << "\n";
return false;
}
_keywords.push_back(KW_anisotropic);
} else if (word == "coverage") {
++wi;
if (wi == words.end()) {
nout << "Argument required for 'coverage'.\n";
return false;
}
const string &arg = (*wi);
if (!string_to_double(arg, _coverage_threshold)) {
nout << "Not a number: " << arg << "\n";
return false;
}
if (_coverage_threshold <= 0.0) {
nout << "Invalid coverage threshold: " << _coverage_threshold << "\n";
return false;
}
_got_coverage_threshold = true;
} else if (word.substr(0, 6) == "force-") {
// Force a particular format, despite the number of channels
// in the image.
string format_name = word.substr(6);
EggTexture::Format format = EggTexture::string_format(format_name);
if (format != EggTexture::F_unspecified) {
_format = format;
_force_format = true;
} else {
nout << "Unknown image format: " << format_name << "\n";
return false;
}
} else if (word == "generic") {
// Genericize the image format by replacing bitcount-specific
// formats with their generic equivalents, e.g. rgba8 becomes
// rgba.
_generic_format = true;
} else if (word == "keep-format") {
// Keep whatever image format was specified.
_keep_format = true;
} else {
// Maybe it's a group name.
PaletteGroup *group = pal->test_palette_group(word);
if (group != (PaletteGroup *)NULL) {
_palette_groups.insert(group);
} else {
// Maybe it's a format name. This suggests an image format,
// but may be overridden to reflect the number of channels in
// the image.
EggTexture::Format format = EggTexture::string_format(word);
if (format != EggTexture::F_unspecified) {
if (!_force_format) {
_format = format;
}
} else {
// Maybe it's an alpha mode.
EggRenderMode::AlphaMode am = EggRenderMode::string_alpha_mode(word);
if (am != EggRenderMode::AM_unspecified) {
_alpha_mode = am;
} else {
// Maybe it's a quality level.
EggTexture::QualityLevel ql = EggTexture::string_quality_level(word);
if (ql != EggTexture::QL_unspecified) {
_quality_level = ql;
} else if (word.length() > 2 && word[word.length() - 2] == '_' &&
strchr("uv", word[word.length() - 1]) != NULL) {
// It must be a wrap mode for u or v.
string prefix = word.substr(0, word.length() - 2);
EggTexture::WrapMode wm = EggTexture::string_wrap_mode(prefix);
if (wm == EggTexture::WM_unspecified) {
return false;
}
switch (word[word.length() - 1]) {
case 'u':
_wrap_u = wm;
break;
case 'v':
_wrap_v = wm;
break;
}
} else {
// Maybe it's an image file request.
if (!parse_image_type_request(word, _color_type, _alpha_type)) {
return false;
}
}
}
}
}
}
++wi;
}
}
return true;
}
////////////////////////////////////////////////////////////////////
// Function: TxaLine::match_egg
// Access: Public
// Description: Compares the patterns on the line to the indicated
// EggFile. If they match, updates the egg with the
// appropriate information. Returns true if a match is
// detected and the search for another line should stop,
// or false if a match is not detected (or if the
// keyword "cont" is present, which means the search
// should continue regardless).
////////////////////////////////////////////////////////////////////
bool TxaLine::
match_egg(EggFile *egg_file) const {
string name = egg_file->get_name();
bool matched_any = false;
Patterns::const_iterator pi;
for (pi = _egg_patterns.begin();
pi != _egg_patterns.end() && !matched_any;
++pi) {
matched_any = (*pi).matches(name);
}
if (!matched_any) {
// No match this line; continue.
return false;
}
bool got_cont = false;
Keywords::const_iterator ki;
for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) {
switch (*ki) {
case KW_omit:
break;
case KW_nearest:
case KW_linear:
case KW_mipmap:
case KW_anisotropic:
// These mean nothing to an egg file.
break;
case KW_cont:
got_cont = true;
break;
}
}
egg_file->match_txa_groups(_palette_groups);
if (got_cont) {
// If we have the "cont" keyword, we should keep scanning for
// another line, even though we matched this one.
return false;
}
// Otherwise, in the normal case, a match ends the search for
// matches.
egg_file->clear_surprise();
return true;
}
////////////////////////////////////////////////////////////////////
// Function: TxaLine::match_texture
// Access: Public
// Description: Compares the patterns on the line to the indicated
// TextureImage. If they match, updates the texture
// with the appropriate information. Returns true if a
// match is detected and the search for another line
// should stop, or false if a match is not detected (or
// if the keyword "cont" is present, which means the
// search should continue regardless).
////////////////////////////////////////////////////////////////////
bool TxaLine::
match_texture(TextureImage *texture) const {
string name = texture->get_name();
bool matched_any = false;
Patterns::const_iterator pi;
for (pi = _texture_patterns.begin();
pi != _texture_patterns.end() && !matched_any;
++pi) {
matched_any = (*pi).matches(name);
}
if (!matched_any) {
// No match this line; continue.
return false;
}
SourceTextureImage *source = texture->get_preferred_source();
TextureRequest &request = texture->_request;
if (!request._got_size) {
switch (_size_type) {
case ST_none:
break;
case ST_scale:
if (source != (SourceTextureImage *)NULL && source->get_size()) {
request._got_size = true;
request._x_size = max(1, (int)(source->get_x_size() * _scale / 100.0));
request._y_size = max(1, (int)(source->get_y_size() * _scale / 100.0));
}
break;
case ST_explicit_3:
request._got_num_channels = true;
request._num_channels = _num_channels;
// fall through
case ST_explicit_2:
request._got_size = true;
request._x_size = _x_size;
request._y_size = _y_size;
break;
}
}
if (_got_margin) {
request._margin = _margin;
}
if (_got_coverage_threshold) {
request._coverage_threshold = _coverage_threshold;
}
if (_color_type != (PNMFileType *)NULL) {
request._properties._color_type = _color_type;
request._properties._alpha_type = _alpha_type;
}
if (_quality_level != EggTexture::QL_unspecified) {
request._properties._quality_level = _quality_level;
}
if (_format != EggTexture::F_unspecified) {
request._format = _format;
request._force_format = _force_format;
request._generic_format = false;
}
if (_generic_format) {
request._generic_format = true;
}
if (_keep_format) {
request._keep_format = true;
}
if (_alpha_mode != EggRenderMode::AM_unspecified) {
request._alpha_mode = _alpha_mode;
}
if (_wrap_u != EggTexture::WM_unspecified) {
request._wrap_u = _wrap_u;
}
if (_wrap_v != EggTexture::WM_unspecified) {
request._wrap_v = _wrap_v;
}
bool got_cont = false;
Keywords::const_iterator ki;
for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) {
switch (*ki) {
case KW_omit:
request._omit = true;
break;
case KW_nearest:
request._minfilter = EggTexture::FT_nearest;
request._magfilter = EggTexture::FT_nearest;
break;
case KW_linear:
request._minfilter = EggTexture::FT_linear;
request._magfilter = EggTexture::FT_linear;
break;
case KW_mipmap:
request._minfilter = EggTexture::FT_linear_mipmap_linear;
request._magfilter = EggTexture::FT_linear_mipmap_linear;
break;
case KW_anisotropic:
request._anisotropic_degree = _aniso_degree;
break;
case KW_cont:
got_cont = true;
break;
}
}
texture->_explicitly_assigned_groups.make_union
(texture->_explicitly_assigned_groups, _palette_groups);
texture->_explicitly_assigned_groups.remove_null();
if (got_cont) {
// If we have the "cont" keyword, we should keep scanning for
// another line, even though we matched this one.
return false;
}
// Otherwise, in the normal case, a match ends the search for
// matches.
texture->_is_surprise = false;
return true;
}
////////////////////////////////////////////////////////////////////
// Function: TxaLine::output
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
void TxaLine::
output(ostream &out) const {
Patterns::const_iterator pi;
for (pi = _texture_patterns.begin(); pi != _texture_patterns.end(); ++pi) {
out << (*pi) << " ";
}
for (pi = _egg_patterns.begin(); pi != _egg_patterns.end(); ++pi) {
out << (*pi) << " ";
}
out << ":";
switch (_size_type) {
case ST_none:
break;
case ST_scale:
out << " " << _scale << "%";
break;
case ST_explicit_2:
out << " " << _x_size << " " << _y_size;
break;
case ST_explicit_3:
out << " " << _x_size << " " << _y_size << " " << _num_channels;
break;
}
if (_got_margin) {
out << " margin " << _margin;
}
if (_got_coverage_threshold) {
out << " coverage " << _coverage_threshold;
}
Keywords::const_iterator ki;
for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) {
switch (*ki) {
case KW_omit:
out << " omit";
break;
case KW_nearest:
out << " nearest";
break;
case KW_linear:
out << " linear";
break;
case KW_mipmap:
out << " mipmap";
break;
case KW_cont:
out << " cont";
break;
case KW_anisotropic:
out << " aniso " << _aniso_degree;
break;
}
}
PaletteGroups::const_iterator gi;
for (gi = _palette_groups.begin(); gi != _palette_groups.end(); ++gi) {
out << " " << (*gi)->get_name();
}
if (_format != EggTexture::F_unspecified) {
out << " " << _format;
if (_force_format) {
out << " (forced)";
}
}
if (_color_type != (PNMFileType *)NULL) {
out << " " << _color_type->get_suggested_extension();
if (_alpha_type != (PNMFileType *)NULL) {
out << "," << _alpha_type->get_suggested_extension();
}
}
}
| 18,177 | 5,733 |
// license:BSD-3-Clause
// copyright-holders:Alex Pasadyn,Zsolt Vasvari,Aaron Giles
/***************************************************************************
Gottlieb Exterminator hardware
***************************************************************************/
#include "emu.h"
#include "includes/exterm.h"
/*************************************
*
* Palette setup
*
*************************************/
void exterm_state::exterm_palette(palette_device &palette) const
{
// initialize 555 RGB lookup
for (int i = 0; i < 32768; i++)
palette.set_pen_color(i + 0x800, pal5bit(i >> 10), pal5bit(i >> 5), pal5bit(i >> 0));
}
/*************************************
*
* Master shift register
*
*************************************/
TMS340X0_TO_SHIFTREG_CB_MEMBER(exterm_state::to_shiftreg_master)
{
memcpy(shiftreg, &m_master_videoram[address >> 4], 256 * sizeof(uint16_t));
}
TMS340X0_FROM_SHIFTREG_CB_MEMBER(exterm_state::from_shiftreg_master)
{
memcpy(&m_master_videoram[address >> 4], shiftreg, 256 * sizeof(uint16_t));
}
TMS340X0_TO_SHIFTREG_CB_MEMBER(exterm_state::to_shiftreg_slave)
{
memcpy(shiftreg, &m_slave_videoram[address >> 4], 256 * 2 * sizeof(uint8_t));
}
TMS340X0_FROM_SHIFTREG_CB_MEMBER(exterm_state::from_shiftreg_slave)
{
memcpy(&m_slave_videoram[address >> 4], shiftreg, 256 * 2 * sizeof(uint8_t));
}
/*************************************
*
* Main video refresh
*
*************************************/
TMS340X0_SCANLINE_IND16_CB_MEMBER(exterm_state::scanline_update)
{
uint16_t *const bgsrc = &m_master_videoram[(params->rowaddr << 8) & 0xff00];
uint16_t *const dest = &bitmap.pix(scanline);
tms340x0_device::display_params fgparams;
int coladdr = params->coladdr;
int fgcoladdr = 0;
/* get parameters for the slave CPU */
m_slave->get_display_params(&fgparams);
/* compute info about the slave vram */
uint16_t *fgsrc = nullptr;
if (fgparams.enabled && scanline >= fgparams.veblnk && scanline < fgparams.vsblnk && fgparams.heblnk < fgparams.hsblnk)
{
fgsrc = &m_slave_videoram[((fgparams.rowaddr << 8) + (fgparams.yoffset << 7)) & 0xff80];
fgcoladdr = (fgparams.coladdr >> 1);
}
/* copy the non-blanked portions of this scanline */
for (int x = params->heblnk; x < params->hsblnk; x += 2)
{
uint16_t bgdata, fgdata = 0;
if (fgsrc != nullptr)
fgdata = fgsrc[fgcoladdr++ & 0x7f];
bgdata = bgsrc[coladdr++ & 0xff];
if ((bgdata & 0xe000) == 0xe000)
dest[x + 0] = bgdata & 0x7ff;
else if ((fgdata & 0x00ff) != 0)
dest[x + 0] = fgdata & 0x00ff;
else
dest[x + 0] = (bgdata & 0x8000) ? (bgdata & 0x7ff) : (bgdata + 0x800);
bgdata = bgsrc[coladdr++ & 0xff];
if ((bgdata & 0xe000) == 0xe000)
dest[x + 1] = bgdata & 0x7ff;
else if ((fgdata & 0xff00) != 0)
dest[x + 1] = fgdata >> 8;
else
dest[x + 1] = (bgdata & 0x8000) ? (bgdata & 0x7ff) : (bgdata + 0x800);
}
}
| 2,893 | 1,303 |
#define BOOST_TEST_DYN_LINK
#ifdef __unix__
#include <boost/test/unit_test.hpp>
#elif defined(_WIN32) || defined(WIN32)
#include <boost/test/included/unit_test.hpp>
#endif
#include<string>
#include<exception>
#include<boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include"utilities/utilities.hpp"
BOOST_AUTO_TEST_SUITE( pTimeToTimestampTests )
BOOST_AUTO_TEST_CASE( convertsToTimestamp ) {
std::string isoTime = "20020131T235959";
std::string expectedTimestamp = "2002-Jan-31 23:59:59";
boost::posix_time::ptime exampleTime(boost::posix_time::from_iso_string(isoTime));
BOOST_CHECK_EQUAL(zpr::pTimeToTimestamp(exampleTime), expectedTimestamp);
}
BOOST_AUTO_TEST_SUITE_END() | 798 | 328 |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_sysadmin_show_diag.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_sysadmin_show_diag {
Diag::Diag()
:
default_(std::make_shared<Diag::Default>())
, fans(std::make_shared<Diag::Fans>())
, power_supply(std::make_shared<Diag::PowerSupply>())
, chassis(std::make_shared<Diag::Chassis>())
, summary(std::make_shared<Diag::Summary>())
, eeprom(std::make_shared<Diag::Eeprom>())
, detail(std::make_shared<Diag::Detail>())
{
default_->parent = this;
fans->parent = this;
power_supply->parent = this;
chassis->parent = this;
summary->parent = this;
eeprom->parent = this;
detail->parent = this;
yang_name = "diag"; yang_parent_name = "Cisco-IOS-XR-sysadmin-show-diag"; is_top_level_class = true; has_list_ancestor = false;
}
Diag::~Diag()
{
}
bool Diag::has_data() const
{
if (is_presence_container) return true;
return (default_ != nullptr && default_->has_data())
|| (fans != nullptr && fans->has_data())
|| (power_supply != nullptr && power_supply->has_data())
|| (chassis != nullptr && chassis->has_data())
|| (summary != nullptr && summary->has_data())
|| (eeprom != nullptr && eeprom->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Diag::has_operation() const
{
return is_set(yfilter)
|| (default_ != nullptr && default_->has_operation())
|| (fans != nullptr && fans->has_operation())
|| (power_supply != nullptr && power_supply->has_operation())
|| (chassis != nullptr && chassis->has_operation())
|| (summary != nullptr && summary->has_operation())
|| (eeprom != nullptr && eeprom->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Diag::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default")
{
if(default_ == nullptr)
{
default_ = std::make_shared<Diag::Default>();
}
return default_;
}
if(child_yang_name == "fans")
{
if(fans == nullptr)
{
fans = std::make_shared<Diag::Fans>();
}
return fans;
}
if(child_yang_name == "power-supply")
{
if(power_supply == nullptr)
{
power_supply = std::make_shared<Diag::PowerSupply>();
}
return power_supply;
}
if(child_yang_name == "chassis")
{
if(chassis == nullptr)
{
chassis = std::make_shared<Diag::Chassis>();
}
return chassis;
}
if(child_yang_name == "summary")
{
if(summary == nullptr)
{
summary = std::make_shared<Diag::Summary>();
}
return summary;
}
if(child_yang_name == "eeprom")
{
if(eeprom == nullptr)
{
eeprom = std::make_shared<Diag::Eeprom>();
}
return eeprom;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Diag::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_ != nullptr)
{
_children["default"] = default_;
}
if(fans != nullptr)
{
_children["fans"] = fans;
}
if(power_supply != nullptr)
{
_children["power-supply"] = power_supply;
}
if(chassis != nullptr)
{
_children["chassis"] = chassis;
}
if(summary != nullptr)
{
_children["summary"] = summary;
}
if(eeprom != nullptr)
{
_children["eeprom"] = eeprom;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Diag::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Diag::clone_ptr() const
{
return std::make_shared<Diag>();
}
std::string Diag::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Diag::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Diag::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Diag::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Diag::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default" || name == "fans" || name == "power-supply" || name == "chassis" || name == "summary" || name == "eeprom" || name == "detail")
return true;
return false;
}
Diag::Default::Default()
:
default_list(this, {"location"})
{
yang_name = "default"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Default::~Default()
{
}
bool Diag::Default::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<default_list.len(); index++)
{
if(default_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Default::has_operation() const
{
for (std::size_t index=0; index<default_list.len(); index++)
{
if(default_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Default::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Default::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Default::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Default::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default_list")
{
auto ent_ = std::make_shared<Diag::Default::DefaultList>();
ent_->parent = this;
default_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Default::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : default_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Default::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Default::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Default::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default_list")
return true;
return false;
}
Diag::Default::DefaultList::DefaultList()
:
location{YType::str, "location"}
,
default_data(std::make_shared<Diag::Default::DefaultList::DefaultData>())
{
default_data->parent = this;
yang_name = "default_list"; yang_parent_name = "default"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Default::DefaultList::~DefaultList()
{
}
bool Diag::Default::DefaultList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (default_data != nullptr && default_data->has_data());
}
bool Diag::Default::DefaultList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (default_data != nullptr && default_data->has_operation());
}
std::string Diag::Default::DefaultList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/default/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Default::DefaultList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Default::DefaultList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Default::DefaultList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default-data")
{
if(default_data == nullptr)
{
default_data = std::make_shared<Diag::Default::DefaultList::DefaultData>();
}
return default_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Default::DefaultList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_data != nullptr)
{
_children["default-data"] = default_data;
}
return _children;
}
void Diag::Default::DefaultList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Default::DefaultList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Default::DefaultList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default-data" || name == "location")
return true;
return false;
}
Diag::Default::DefaultList::DefaultData::DefaultData()
:
default_out_list{YType::str, "default_out_list"}
{
yang_name = "default-data"; yang_parent_name = "default_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Default::DefaultList::DefaultData::~DefaultData()
{
}
bool Diag::Default::DefaultList::DefaultData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : default_out_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Default::DefaultList::DefaultData::has_operation() const
{
for (auto const & leaf : default_out_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(default_out_list.yfilter);
}
std::string Diag::Default::DefaultList::DefaultData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Default::DefaultList::DefaultData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto default_out_list_name_datas = default_out_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Default::DefaultList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Default::DefaultList::DefaultData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Default::DefaultList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "default_out_list")
{
default_out_list.append(value);
}
}
void Diag::Default::DefaultList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "default_out_list")
{
default_out_list.yfilter = yfilter;
}
}
bool Diag::Default::DefaultList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default_out_list")
return true;
return false;
}
Diag::Fans::Fans()
:
fans_list(this, {"location"})
{
yang_name = "fans"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Fans::~Fans()
{
}
bool Diag::Fans::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<fans_list.len(); index++)
{
if(fans_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Fans::has_operation() const
{
for (std::size_t index=0; index<fans_list.len(); index++)
{
if(fans_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Fans::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Fans::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "fans";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Fans::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Fans::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "fans_list")
{
auto ent_ = std::make_shared<Diag::Fans::FansList>();
ent_->parent = this;
fans_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Fans::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : fans_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Fans::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Fans::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Fans::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "fans_list")
return true;
return false;
}
Diag::Fans::FansList::FansList()
:
location{YType::str, "location"}
,
default_data(std::make_shared<Diag::Fans::FansList::DefaultData>())
{
default_data->parent = this;
yang_name = "fans_list"; yang_parent_name = "fans"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Fans::FansList::~FansList()
{
}
bool Diag::Fans::FansList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (default_data != nullptr && default_data->has_data());
}
bool Diag::Fans::FansList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (default_data != nullptr && default_data->has_operation());
}
std::string Diag::Fans::FansList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/fans/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Fans::FansList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "fans_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Fans::FansList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Fans::FansList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default-data")
{
if(default_data == nullptr)
{
default_data = std::make_shared<Diag::Fans::FansList::DefaultData>();
}
return default_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Fans::FansList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_data != nullptr)
{
_children["default-data"] = default_data;
}
return _children;
}
void Diag::Fans::FansList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Fans::FansList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Fans::FansList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default-data" || name == "location")
return true;
return false;
}
Diag::Fans::FansList::DefaultData::DefaultData()
:
default_out_list{YType::str, "default_out_list"}
{
yang_name = "default-data"; yang_parent_name = "fans_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Fans::FansList::DefaultData::~DefaultData()
{
}
bool Diag::Fans::FansList::DefaultData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : default_out_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Fans::FansList::DefaultData::has_operation() const
{
for (auto const & leaf : default_out_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(default_out_list.yfilter);
}
std::string Diag::Fans::FansList::DefaultData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Fans::FansList::DefaultData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto default_out_list_name_datas = default_out_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Fans::FansList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Fans::FansList::DefaultData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Fans::FansList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "default_out_list")
{
default_out_list.append(value);
}
}
void Diag::Fans::FansList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "default_out_list")
{
default_out_list.yfilter = yfilter;
}
}
bool Diag::Fans::FansList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default_out_list")
return true;
return false;
}
Diag::PowerSupply::PowerSupply()
:
pwr_list(this, {"location"})
{
yang_name = "power-supply"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::PowerSupply::~PowerSupply()
{
}
bool Diag::PowerSupply::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<pwr_list.len(); index++)
{
if(pwr_list[index]->has_data())
return true;
}
return false;
}
bool Diag::PowerSupply::has_operation() const
{
for (std::size_t index=0; index<pwr_list.len(); index++)
{
if(pwr_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::PowerSupply::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::PowerSupply::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "power-supply";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::PowerSupply::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::PowerSupply::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "pwr_list")
{
auto ent_ = std::make_shared<Diag::PowerSupply::PwrList>();
ent_->parent = this;
pwr_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::PowerSupply::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : pwr_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::PowerSupply::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::PowerSupply::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::PowerSupply::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "pwr_list")
return true;
return false;
}
Diag::PowerSupply::PwrList::PwrList()
:
location{YType::str, "location"}
,
default_data(std::make_shared<Diag::PowerSupply::PwrList::DefaultData>())
{
default_data->parent = this;
yang_name = "pwr_list"; yang_parent_name = "power-supply"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::PowerSupply::PwrList::~PwrList()
{
}
bool Diag::PowerSupply::PwrList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (default_data != nullptr && default_data->has_data());
}
bool Diag::PowerSupply::PwrList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (default_data != nullptr && default_data->has_operation());
}
std::string Diag::PowerSupply::PwrList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/power-supply/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::PowerSupply::PwrList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "pwr_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::PowerSupply::PwrList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::PowerSupply::PwrList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default-data")
{
if(default_data == nullptr)
{
default_data = std::make_shared<Diag::PowerSupply::PwrList::DefaultData>();
}
return default_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::PowerSupply::PwrList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_data != nullptr)
{
_children["default-data"] = default_data;
}
return _children;
}
void Diag::PowerSupply::PwrList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::PowerSupply::PwrList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::PowerSupply::PwrList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default-data" || name == "location")
return true;
return false;
}
Diag::PowerSupply::PwrList::DefaultData::DefaultData()
:
default_out_list{YType::str, "default_out_list"}
{
yang_name = "default-data"; yang_parent_name = "pwr_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::PowerSupply::PwrList::DefaultData::~DefaultData()
{
}
bool Diag::PowerSupply::PwrList::DefaultData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : default_out_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::PowerSupply::PwrList::DefaultData::has_operation() const
{
for (auto const & leaf : default_out_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(default_out_list.yfilter);
}
std::string Diag::PowerSupply::PwrList::DefaultData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::PowerSupply::PwrList::DefaultData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto default_out_list_name_datas = default_out_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::PowerSupply::PwrList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::PowerSupply::PwrList::DefaultData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::PowerSupply::PwrList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "default_out_list")
{
default_out_list.append(value);
}
}
void Diag::PowerSupply::PwrList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "default_out_list")
{
default_out_list.yfilter = yfilter;
}
}
bool Diag::PowerSupply::PwrList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default_out_list")
return true;
return false;
}
Diag::Chassis::Chassis()
:
chassis_cnt(std::make_shared<Diag::Chassis::ChassisCnt>())
, chassis_eeprom_cnt(std::make_shared<Diag::Chassis::ChassisEepromCnt>())
{
chassis_cnt->parent = this;
chassis_eeprom_cnt->parent = this;
yang_name = "chassis"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Chassis::~Chassis()
{
}
bool Diag::Chassis::has_data() const
{
if (is_presence_container) return true;
return (chassis_cnt != nullptr && chassis_cnt->has_data())
|| (chassis_eeprom_cnt != nullptr && chassis_eeprom_cnt->has_data());
}
bool Diag::Chassis::has_operation() const
{
return is_set(yfilter)
|| (chassis_cnt != nullptr && chassis_cnt->has_operation())
|| (chassis_eeprom_cnt != nullptr && chassis_eeprom_cnt->has_operation());
}
std::string Diag::Chassis::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Chassis::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "chassis";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "chassis_cnt")
{
if(chassis_cnt == nullptr)
{
chassis_cnt = std::make_shared<Diag::Chassis::ChassisCnt>();
}
return chassis_cnt;
}
if(child_yang_name == "chassis_eeprom_cnt")
{
if(chassis_eeprom_cnt == nullptr)
{
chassis_eeprom_cnt = std::make_shared<Diag::Chassis::ChassisEepromCnt>();
}
return chassis_eeprom_cnt;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(chassis_cnt != nullptr)
{
_children["chassis_cnt"] = chassis_cnt;
}
if(chassis_eeprom_cnt != nullptr)
{
_children["chassis_eeprom_cnt"] = chassis_eeprom_cnt;
}
return _children;
}
void Diag::Chassis::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Chassis::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Chassis::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "chassis_cnt" || name == "chassis_eeprom_cnt")
return true;
return false;
}
Diag::Chassis::ChassisCnt::ChassisCnt()
:
chassis_list(this, {"location"})
{
yang_name = "chassis_cnt"; yang_parent_name = "chassis"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Chassis::ChassisCnt::~ChassisCnt()
{
}
bool Diag::Chassis::ChassisCnt::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<chassis_list.len(); index++)
{
if(chassis_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Chassis::ChassisCnt::has_operation() const
{
for (std::size_t index=0; index<chassis_list.len(); index++)
{
if(chassis_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Chassis::ChassisCnt::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Chassis::ChassisCnt::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "chassis_cnt";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisCnt::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisCnt::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "chassis_list")
{
auto ent_ = std::make_shared<Diag::Chassis::ChassisCnt::ChassisList>();
ent_->parent = this;
chassis_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisCnt::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : chassis_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Chassis::ChassisCnt::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Chassis::ChassisCnt::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Chassis::ChassisCnt::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "chassis_list")
return true;
return false;
}
Diag::Chassis::ChassisCnt::ChassisList::ChassisList()
:
location{YType::str, "location"}
,
default_data(std::make_shared<Diag::Chassis::ChassisCnt::ChassisList::DefaultData>())
{
default_data->parent = this;
yang_name = "chassis_list"; yang_parent_name = "chassis_cnt"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Chassis::ChassisCnt::ChassisList::~ChassisList()
{
}
bool Diag::Chassis::ChassisCnt::ChassisList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (default_data != nullptr && default_data->has_data());
}
bool Diag::Chassis::ChassisCnt::ChassisList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (default_data != nullptr && default_data->has_operation());
}
std::string Diag::Chassis::ChassisCnt::ChassisList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/chassis_cnt/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Chassis::ChassisCnt::ChassisList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "chassis_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisCnt::ChassisList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisCnt::ChassisList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "default-data")
{
if(default_data == nullptr)
{
default_data = std::make_shared<Diag::Chassis::ChassisCnt::ChassisList::DefaultData>();
}
return default_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisCnt::ChassisList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(default_data != nullptr)
{
_children["default-data"] = default_data;
}
return _children;
}
void Diag::Chassis::ChassisCnt::ChassisList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Chassis::ChassisCnt::ChassisList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Chassis::ChassisCnt::ChassisList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default-data" || name == "location")
return true;
return false;
}
Diag::Chassis::ChassisCnt::ChassisList::DefaultData::DefaultData()
:
default_out_list{YType::str, "default_out_list"}
{
yang_name = "default-data"; yang_parent_name = "chassis_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Chassis::ChassisCnt::ChassisList::DefaultData::~DefaultData()
{
}
bool Diag::Chassis::ChassisCnt::ChassisList::DefaultData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : default_out_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Chassis::ChassisCnt::ChassisList::DefaultData::has_operation() const
{
for (auto const & leaf : default_out_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(default_out_list.yfilter);
}
std::string Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "default-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto default_out_list_name_datas = default_out_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), default_out_list_name_datas.begin(), default_out_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisCnt::ChassisList::DefaultData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Chassis::ChassisCnt::ChassisList::DefaultData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "default_out_list")
{
default_out_list.append(value);
}
}
void Diag::Chassis::ChassisCnt::ChassisList::DefaultData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "default_out_list")
{
default_out_list.yfilter = yfilter;
}
}
bool Diag::Chassis::ChassisCnt::ChassisList::DefaultData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "default_out_list")
return true;
return false;
}
Diag::Chassis::ChassisEepromCnt::ChassisEepromCnt()
:
chassis_eeprom_list(this, {"location"})
{
yang_name = "chassis_eeprom_cnt"; yang_parent_name = "chassis"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Chassis::ChassisEepromCnt::~ChassisEepromCnt()
{
}
bool Diag::Chassis::ChassisEepromCnt::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<chassis_eeprom_list.len(); index++)
{
if(chassis_eeprom_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Chassis::ChassisEepromCnt::has_operation() const
{
for (std::size_t index=0; index<chassis_eeprom_list.len(); index++)
{
if(chassis_eeprom_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Chassis::ChassisEepromCnt::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Chassis::ChassisEepromCnt::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "chassis_eeprom_cnt";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisEepromCnt::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisEepromCnt::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "chassis_eeprom_list")
{
auto ent_ = std::make_shared<Diag::Chassis::ChassisEepromCnt::ChassisEepromList>();
ent_->parent = this;
chassis_eeprom_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisEepromCnt::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : chassis_eeprom_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Chassis::ChassisEepromCnt::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Chassis::ChassisEepromCnt::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Chassis::ChassisEepromCnt::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "chassis_eeprom_list")
return true;
return false;
}
Diag::Chassis::ChassisEepromCnt::ChassisEepromList::ChassisEepromList()
:
location{YType::str, "location"}
,
eeprom_data(std::make_shared<Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData>())
{
eeprom_data->parent = this;
yang_name = "chassis_eeprom_list"; yang_parent_name = "chassis_eeprom_cnt"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Chassis::ChassisEepromCnt::ChassisEepromList::~ChassisEepromList()
{
}
bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (eeprom_data != nullptr && eeprom_data->has_data());
}
bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (eeprom_data != nullptr && eeprom_data->has_operation());
}
std::string Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/chassis/chassis_eeprom_cnt/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "chassis_eeprom_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "eeprom-data")
{
if(eeprom_data == nullptr)
{
eeprom_data = std::make_shared<Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData>();
}
return eeprom_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(eeprom_data != nullptr)
{
_children["eeprom-data"] = eeprom_data;
}
return _children;
}
void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "eeprom-data" || name == "location")
return true;
return false;
}
Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::EepromData()
:
raw_list{YType::str, "raw_list"}
{
yang_name = "eeprom-data"; yang_parent_name = "chassis_eeprom_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::~EepromData()
{
}
bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : raw_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::has_operation() const
{
for (auto const & leaf : raw_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(raw_list.yfilter);
}
std::string Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "eeprom-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto raw_list_name_datas = raw_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), raw_list_name_datas.begin(), raw_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "raw_list")
{
raw_list.append(value);
}
}
void Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "raw_list")
{
raw_list.yfilter = yfilter;
}
}
bool Diag::Chassis::ChassisEepromCnt::ChassisEepromList::EepromData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "raw_list")
return true;
return false;
}
Diag::Summary::Summary()
:
summary_list(this, {"location"})
{
yang_name = "summary"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Summary::~Summary()
{
}
bool Diag::Summary::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<summary_list.len(); index++)
{
if(summary_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Summary::has_operation() const
{
for (std::size_t index=0; index<summary_list.len(); index++)
{
if(summary_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Summary::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Summary::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "summary";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Summary::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Summary::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "summary_list")
{
auto ent_ = std::make_shared<Diag::Summary::SummaryList>();
ent_->parent = this;
summary_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Summary::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : summary_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Summary::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Summary::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Summary::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "summary_list")
return true;
return false;
}
Diag::Summary::SummaryList::SummaryList()
:
location{YType::str, "location"}
,
summary_data(std::make_shared<Diag::Summary::SummaryList::SummaryData>())
{
summary_data->parent = this;
yang_name = "summary_list"; yang_parent_name = "summary"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Summary::SummaryList::~SummaryList()
{
}
bool Diag::Summary::SummaryList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (summary_data != nullptr && summary_data->has_data());
}
bool Diag::Summary::SummaryList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (summary_data != nullptr && summary_data->has_operation());
}
std::string Diag::Summary::SummaryList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/summary/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Summary::SummaryList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "summary_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Summary::SummaryList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Summary::SummaryList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "summary-data")
{
if(summary_data == nullptr)
{
summary_data = std::make_shared<Diag::Summary::SummaryList::SummaryData>();
}
return summary_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Summary::SummaryList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(summary_data != nullptr)
{
_children["summary-data"] = summary_data;
}
return _children;
}
void Diag::Summary::SummaryList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Summary::SummaryList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Summary::SummaryList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "summary-data" || name == "location")
return true;
return false;
}
Diag::Summary::SummaryList::SummaryData::SummaryData()
:
summary_out_list{YType::str, "summary_out_list"}
{
yang_name = "summary-data"; yang_parent_name = "summary_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Summary::SummaryList::SummaryData::~SummaryData()
{
}
bool Diag::Summary::SummaryList::SummaryData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : summary_out_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Summary::SummaryList::SummaryData::has_operation() const
{
for (auto const & leaf : summary_out_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(summary_out_list.yfilter);
}
std::string Diag::Summary::SummaryList::SummaryData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "summary-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Summary::SummaryList::SummaryData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto summary_out_list_name_datas = summary_out_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), summary_out_list_name_datas.begin(), summary_out_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Summary::SummaryList::SummaryData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Summary::SummaryList::SummaryData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Summary::SummaryList::SummaryData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "summary_out_list")
{
summary_out_list.append(value);
}
}
void Diag::Summary::SummaryList::SummaryData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "summary_out_list")
{
summary_out_list.yfilter = yfilter;
}
}
bool Diag::Summary::SummaryList::SummaryData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "summary_out_list")
return true;
return false;
}
Diag::Eeprom::Eeprom()
:
eeprom_list(this, {"location"})
{
yang_name = "eeprom"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Eeprom::~Eeprom()
{
}
bool Diag::Eeprom::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<eeprom_list.len(); index++)
{
if(eeprom_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Eeprom::has_operation() const
{
for (std::size_t index=0; index<eeprom_list.len(); index++)
{
if(eeprom_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Eeprom::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Eeprom::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "eeprom";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Eeprom::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Eeprom::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "eeprom_list")
{
auto ent_ = std::make_shared<Diag::Eeprom::EepromList>();
ent_->parent = this;
eeprom_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Eeprom::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : eeprom_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Eeprom::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Eeprom::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Eeprom::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "eeprom_list")
return true;
return false;
}
Diag::Eeprom::EepromList::EepromList()
:
location{YType::str, "location"}
,
eeprom_data(std::make_shared<Diag::Eeprom::EepromList::EepromData>())
{
eeprom_data->parent = this;
yang_name = "eeprom_list"; yang_parent_name = "eeprom"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Eeprom::EepromList::~EepromList()
{
}
bool Diag::Eeprom::EepromList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (eeprom_data != nullptr && eeprom_data->has_data());
}
bool Diag::Eeprom::EepromList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (eeprom_data != nullptr && eeprom_data->has_operation());
}
std::string Diag::Eeprom::EepromList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/eeprom/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Eeprom::EepromList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "eeprom_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Eeprom::EepromList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Eeprom::EepromList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "eeprom-data")
{
if(eeprom_data == nullptr)
{
eeprom_data = std::make_shared<Diag::Eeprom::EepromList::EepromData>();
}
return eeprom_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Eeprom::EepromList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(eeprom_data != nullptr)
{
_children["eeprom-data"] = eeprom_data;
}
return _children;
}
void Diag::Eeprom::EepromList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Eeprom::EepromList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Eeprom::EepromList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "eeprom-data" || name == "location")
return true;
return false;
}
Diag::Eeprom::EepromList::EepromData::EepromData()
:
raw_list{YType::str, "raw_list"}
{
yang_name = "eeprom-data"; yang_parent_name = "eeprom_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Eeprom::EepromList::EepromData::~EepromData()
{
}
bool Diag::Eeprom::EepromList::EepromData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : raw_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Eeprom::EepromList::EepromData::has_operation() const
{
for (auto const & leaf : raw_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(raw_list.yfilter);
}
std::string Diag::Eeprom::EepromList::EepromData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "eeprom-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Eeprom::EepromList::EepromData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto raw_list_name_datas = raw_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), raw_list_name_datas.begin(), raw_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Eeprom::EepromList::EepromData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Eeprom::EepromList::EepromData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Eeprom::EepromList::EepromData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "raw_list")
{
raw_list.append(value);
}
}
void Diag::Eeprom::EepromList::EepromData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "raw_list")
{
raw_list.yfilter = yfilter;
}
}
bool Diag::Eeprom::EepromList::EepromData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "raw_list")
return true;
return false;
}
Diag::Detail::Detail()
:
detail_list(this, {"location"})
{
yang_name = "detail"; yang_parent_name = "diag"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Detail::~Detail()
{
}
bool Diag::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<detail_list.len(); index++)
{
if(detail_list[index]->has_data())
return true;
}
return false;
}
bool Diag::Detail::has_operation() const
{
for (std::size_t index=0; index<detail_list.len(); index++)
{
if(detail_list[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Diag::Detail::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "detail_list")
{
auto ent_ = std::make_shared<Diag::Detail::DetailList>();
ent_->parent = this;
detail_list.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : detail_list.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Diag::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Diag::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Diag::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "detail_list")
return true;
return false;
}
Diag::Detail::DetailList::DetailList()
:
location{YType::str, "location"}
,
detail_data(std::make_shared<Diag::Detail::DetailList::DetailData>())
{
detail_data->parent = this;
yang_name = "detail_list"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = false;
}
Diag::Detail::DetailList::~DetailList()
{
}
bool Diag::Detail::DetailList::has_data() const
{
if (is_presence_container) return true;
return location.is_set
|| (detail_data != nullptr && detail_data->has_data());
}
bool Diag::Detail::DetailList::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(location.yfilter)
|| (detail_data != nullptr && detail_data->has_operation());
}
std::string Diag::Detail::DetailList::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-show-diag:diag/detail/" << get_segment_path();
return path_buffer.str();
}
std::string Diag::Detail::DetailList::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail_list";
ADD_KEY_TOKEN(location, "location");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Detail::DetailList::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Detail::DetailList::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "detail-data")
{
if(detail_data == nullptr)
{
detail_data = std::make_shared<Diag::Detail::DetailList::DetailData>();
}
return detail_data;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Detail::DetailList::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(detail_data != nullptr)
{
_children["detail-data"] = detail_data;
}
return _children;
}
void Diag::Detail::DetailList::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "location")
{
location = value;
location.value_namespace = name_space;
location.value_namespace_prefix = name_space_prefix;
}
}
void Diag::Detail::DetailList::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "location")
{
location.yfilter = yfilter;
}
}
bool Diag::Detail::DetailList::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "detail-data" || name == "location")
return true;
return false;
}
Diag::Detail::DetailList::DetailData::DetailData()
:
detail_out_list{YType::str, "detail_out_list"}
{
yang_name = "detail-data"; yang_parent_name = "detail_list"; is_top_level_class = false; has_list_ancestor = true;
}
Diag::Detail::DetailList::DetailData::~DetailData()
{
}
bool Diag::Detail::DetailList::DetailData::has_data() const
{
if (is_presence_container) return true;
for (auto const & leaf : detail_out_list.getYLeafs())
{
if(leaf.is_set)
return true;
}
return false;
}
bool Diag::Detail::DetailList::DetailData::has_operation() const
{
for (auto const & leaf : detail_out_list.getYLeafs())
{
if(is_set(leaf.yfilter))
return true;
}
return is_set(yfilter)
|| ydk::is_set(detail_out_list.yfilter);
}
std::string Diag::Detail::DetailList::DetailData::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail-data";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Diag::Detail::DetailList::DetailData::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
auto detail_out_list_name_datas = detail_out_list.get_name_leafdata();
leaf_name_data.insert(leaf_name_data.end(), detail_out_list_name_datas.begin(), detail_out_list_name_datas.end());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Diag::Detail::DetailList::DetailData::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Diag::Detail::DetailList::DetailData::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Diag::Detail::DetailList::DetailData::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "detail_out_list")
{
detail_out_list.append(value);
}
}
void Diag::Detail::DetailList::DetailData::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "detail_out_list")
{
detail_out_list.yfilter = yfilter;
}
}
bool Diag::Detail::DetailList::DetailData::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "detail_out_list")
return true;
return false;
}
}
}
| 72,695 | 26,472 |
๏ปฟ/********************************************************************************
* ReactPhysics3D physics library, http://www.reactphysics3d.com *
* Copyright (c) 2010-2020 Daniel Chappuis *
*********************************************************************************
* *
* This software is provided 'as-is', without any express or implied warranty. *
* In no event will the authors be held liable for any damages arising from the *
* use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not claim *
* that you wrote the original software. If you use this software in a *
* product, an acknowledgment in the product documentation would be *
* appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source distribution. *
* *
********************************************************************************/
// Libraries
#include <reactphysics3d/systems/CollisionDetectionSystem.h>
#include <reactphysics3d/engine/PhysicsWorld.h>
#include <reactphysics3d/collision/OverlapCallback.h>
#include <reactphysics3d/collision/shapes/BoxShape.h>
#include <reactphysics3d/collision/shapes/ConcaveShape.h>
#include <reactphysics3d/collision/ContactManifoldInfo.h>
#include <reactphysics3d/constraint/ContactPoint.h>
#include <reactphysics3d/body/RigidBody.h>
#include <reactphysics3d/configuration.h>
#include <reactphysics3d/collision/CollisionCallback.h>
#include <reactphysics3d/collision/OverlapCallback.h>
#include <reactphysics3d/collision/narrowphase/NarrowPhaseInfoBatch.h>
#include <reactphysics3d/collision/ContactManifold.h>
#include <reactphysics3d/utils/Profiler.h>
#include <reactphysics3d/engine/EventListener.h>
#include <reactphysics3d/collision/RaycastInfo.h>
#include <reactphysics3d/containers/Pair.h>
#include <cassert>
#include <iostream>
// We want to use the ReactPhysics3D namespace
using namespace reactphysics3d;
using namespace std;
// Constructor
CollisionDetectionSystem::CollisionDetectionSystem(PhysicsWorld* world, ColliderComponents& collidersComponents, TransformComponents& transformComponents,
CollisionBodyComponents& collisionBodyComponents, RigidBodyComponents& rigidBodyComponents,
MemoryManager& memoryManager, HalfEdgeStructure& triangleHalfEdgeStructure)
: mMemoryManager(memoryManager), mCollidersComponents(collidersComponents), mRigidBodyComponents(rigidBodyComponents),
mCollisionDispatch(mMemoryManager.getPoolAllocator()), mWorld(world),
mNoCollisionPairs(mMemoryManager.getPoolAllocator()),
mOverlappingPairs(mMemoryManager, mCollidersComponents, collisionBodyComponents, rigidBodyComponents,
mNoCollisionPairs, mCollisionDispatch),
mBroadPhaseOverlappingNodes(mMemoryManager.getHeapAllocator(), 32),
mBroadPhaseSystem(*this, mCollidersComponents, transformComponents, rigidBodyComponents),
mMapBroadPhaseIdToColliderEntity(memoryManager.getPoolAllocator()),
mNarrowPhaseInput(mMemoryManager.getSingleFrameAllocator(), mOverlappingPairs), mPotentialContactPoints(mMemoryManager.getSingleFrameAllocator()),
mPotentialContactManifolds(mMemoryManager.getSingleFrameAllocator()), mContactPairs1(mMemoryManager.getPoolAllocator()),
mContactPairs2(mMemoryManager.getPoolAllocator()), mPreviousContactPairs(&mContactPairs1), mCurrentContactPairs(&mContactPairs2),
mLostContactPairs(mMemoryManager.getSingleFrameAllocator()), mPreviousMapPairIdToContactPairIndex(mMemoryManager.getHeapAllocator()),
mContactManifolds1(mMemoryManager.getPoolAllocator()), mContactManifolds2(mMemoryManager.getPoolAllocator()),
mPreviousContactManifolds(&mContactManifolds1), mCurrentContactManifolds(&mContactManifolds2),
mContactPoints1(mMemoryManager.getPoolAllocator()), mContactPoints2(mMemoryManager.getPoolAllocator()),
mPreviousContactPoints(&mContactPoints1), mCurrentContactPoints(&mContactPoints2), mCollisionBodyContactPairsIndices(mMemoryManager.getSingleFrameAllocator()),
mNbPreviousPotentialContactManifolds(0), mNbPreviousPotentialContactPoints(0), mTriangleHalfEdgeStructure(triangleHalfEdgeStructure) {
#ifdef IS_RP3D_PROFILING_ENABLED
mProfiler = nullptr;
mCollisionDispatch.setProfiler(mProfiler);
mOverlappingPairs.setProfiler(mProfiler);
#endif
}
// Compute the collision detection
void CollisionDetectionSystem::computeCollisionDetection() {
RP3D_PROFILE("CollisionDetectionSystem::computeCollisionDetection()", mProfiler);
// Compute the broad-phase collision detection
computeBroadPhase();
// Compute the middle-phase collision detection
computeMiddlePhase(mNarrowPhaseInput, true);
// Compute the narrow-phase collision detection
computeNarrowPhase();
}
// Compute the broad-phase collision detection
void CollisionDetectionSystem::computeBroadPhase() {
RP3D_PROFILE("CollisionDetectionSystem::computeBroadPhase()", mProfiler);
assert(mBroadPhaseOverlappingNodes.size() == 0);
// Ask the broad-phase to compute all the shapes overlapping with the shapes that
// have moved or have been added in the last frame. This call can only add new
// overlapping pairs in the collision detection.
mBroadPhaseSystem.computeOverlappingPairs(mMemoryManager, mBroadPhaseOverlappingNodes);
// Create new overlapping pairs if necessary
updateOverlappingPairs(mBroadPhaseOverlappingNodes);
// Remove non overlapping pairs
removeNonOverlappingPairs();
mBroadPhaseOverlappingNodes.clear();
}
// Remove pairs that are not overlapping anymore
void CollisionDetectionSystem::removeNonOverlappingPairs() {
RP3D_PROFILE("CollisionDetectionSystem::removeNonOverlappingPairs()", mProfiler);
// For each convex pairs
for (uint64 i=0; i < mOverlappingPairs.mConvexPairs.size(); i++) {
OverlappingPairs::ConvexOverlappingPair& overlappingPair = mOverlappingPairs.mConvexPairs[i];
// Check if we need to test overlap. If so, test if the two shapes are still overlapping.
// Otherwise, we destroy the overlapping pair
if (overlappingPair.needToTestOverlap) {
if(mBroadPhaseSystem.testOverlappingShapes(overlappingPair.broadPhaseId1, overlappingPair.broadPhaseId2)) {
overlappingPair.needToTestOverlap = false;
}
else {
// If the two colliders of the pair were colliding in the previous frame
if (overlappingPair.collidingInPreviousFrame) {
// Create a new lost contact pair
addLostContactPair(overlappingPair);
}
mOverlappingPairs.removePair(i, true);
i--;
}
}
}
// For each concave pairs
for (uint64 i=0; i < mOverlappingPairs.mConcavePairs.size(); i++) {
OverlappingPairs::ConcaveOverlappingPair& overlappingPair = mOverlappingPairs.mConcavePairs[i];
// Check if we need to test overlap. If so, test if the two shapes are still overlapping.
// Otherwise, we destroy the overlapping pair
if (overlappingPair.needToTestOverlap) {
if(mBroadPhaseSystem.testOverlappingShapes(overlappingPair.broadPhaseId1, overlappingPair.broadPhaseId2)) {
overlappingPair.needToTestOverlap = false;
}
else {
// If the two colliders of the pair were colliding in the previous frame
if (overlappingPair.collidingInPreviousFrame) {
// Create a new lost contact pair
addLostContactPair(overlappingPair);
}
mOverlappingPairs.removePair(i, false);
i--;
}
}
}
}
// Add a lost contact pair (pair of colliders that are not in contact anymore)
void CollisionDetectionSystem::addLostContactPair(OverlappingPairs::OverlappingPair& overlappingPair) {
const uint32 collider1Index = mCollidersComponents.getEntityIndex(overlappingPair.collider1);
const uint32 collider2Index = mCollidersComponents.getEntityIndex(overlappingPair.collider2);
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index];
const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index];
const bool isTrigger = isCollider1Trigger || isCollider2Trigger;
// Create a lost contact pair
ContactPair lostContactPair(overlappingPair.pairID, body1Entity, body2Entity, overlappingPair.collider1, overlappingPair.collider2, mLostContactPairs.size(),
true, isTrigger, mMemoryManager.getHeapAllocator());
mLostContactPairs.add(lostContactPair);
}
// Take an array of overlapping nodes in the broad-phase and create new overlapping pairs if necessary
void CollisionDetectionSystem::updateOverlappingPairs(const Array<Pair<int32, int32>>& overlappingNodes) {
RP3D_PROFILE("CollisionDetectionSystem::updateOverlappingPairs()", mProfiler);
// For each overlapping pair of nodes
const uint32 nbOverlappingNodes = overlappingNodes.size();
for (uint32 i=0; i < nbOverlappingNodes; i++) {
Pair<int32, int32> nodePair = overlappingNodes[i];
assert(nodePair.first != -1);
assert(nodePair.second != -1);
// Skip pairs with same overlapping nodes
if (nodePair.first != nodePair.second) {
// Get the two colliders
const Entity collider1Entity = mMapBroadPhaseIdToColliderEntity[nodePair.first];
const Entity collider2Entity = mMapBroadPhaseIdToColliderEntity[nodePair.second];
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
// Get the two bodies
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
// If the two colliders are from the same body, skip it
if (body1Entity != body2Entity) {
const uint32 nbEnabledColliderComponents = mCollidersComponents.getNbEnabledComponents();
const bool isBody1Enabled = collider1Index < nbEnabledColliderComponents;
const bool isBody2Enabled = collider2Index < nbEnabledColliderComponents;
bool isBody1Static = false;
bool isBody2Static = false;
uint32 rigidBody1Index, rigidBody2Index;
if (mRigidBodyComponents.hasComponentGetIndex(body1Entity, rigidBody1Index)) {
isBody1Static = mRigidBodyComponents.mBodyTypes[rigidBody1Index] == BodyType::STATIC;
}
if (mRigidBodyComponents.hasComponentGetIndex(body2Entity, rigidBody2Index)) {
isBody2Static = mRigidBodyComponents.mBodyTypes[rigidBody2Index] == BodyType::STATIC;
}
const bool isBody1Active = isBody1Enabled && !isBody1Static;
const bool isBody2Active = isBody2Enabled && !isBody2Static;
if (isBody1Active || isBody2Active) {
// Check if the bodies are in the set of bodies that cannot collide between each other
// TODO OPTI : What not use the pairId here ??
const bodypair bodiesIndex = OverlappingPairs::computeBodiesIndexPair(body1Entity, body2Entity);
if (!mNoCollisionPairs.contains(bodiesIndex)) {
// Compute the overlapping pair ID
const uint64 pairId = pairNumbers(std::max(nodePair.first, nodePair.second), std::min(nodePair.first, nodePair.second));
// Check if the overlapping pair already exists
OverlappingPairs::OverlappingPair* overlappingPair = mOverlappingPairs.getOverlappingPair(pairId);
if (overlappingPair == nullptr) {
const unsigned short shape1CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider1Index];
const unsigned short shape2CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider2Index];
const unsigned short shape1CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider1Index];
const unsigned short shape2CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider2Index];
// Check if the collision filtering allows collision between the two shapes
if ((shape1CollideWithMaskBits & shape2CollisionCategoryBits) != 0 &&
(shape1CollisionCategoryBits & shape2CollideWithMaskBits) != 0) {
Collider* shape1 = mCollidersComponents.mColliders[collider1Index];
Collider* shape2 = mCollidersComponents.mColliders[collider2Index];
// Check that at least one collision shape is convex
const bool isShape1Convex = shape1->getCollisionShape()->isConvex();
const bool isShape2Convex = shape2->getCollisionShape()->isConvex();
if (isShape1Convex || isShape2Convex) {
// Add the new overlapping pair
mOverlappingPairs.addPair(collider1Index, collider2Index, isShape1Convex && isShape2Convex);
}
}
}
else {
// We do not need to test the pair for overlap because it has just been reported that they still overlap
overlappingPair->needToTestOverlap = false;
}
}
}
}
}
}
}
// Compute the middle-phase collision detection
void CollisionDetectionSystem::computeMiddlePhase(NarrowPhaseInput& narrowPhaseInput, bool needToReportContacts) {
RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler);
// Reserve memory for the narrow-phase input using cached capacity from previous frame
narrowPhaseInput.reserveMemory();
// Remove the obsolete last frame collision infos and mark all the others as obsolete
mOverlappingPairs.clearObsoleteLastFrameCollisionInfos();
// For each possible convex vs convex pair of bodies
const uint64 nbConvexVsConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint64 i=0; i < nbConvexVsConvexPairs; i++) {
OverlappingPairs::ConvexOverlappingPair& overlappingPair = mOverlappingPairs.mConvexPairs[i];
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider2) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != mCollidersComponents.getBroadPhaseId(overlappingPair.collider2));
const Entity collider1Entity = overlappingPair.collider1;
const Entity collider2Entity = overlappingPair.collider2;
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index];
CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index];
NarrowPhaseAlgorithmType algorithmType = overlappingPair.narrowPhaseAlgorithmType;
const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index];
const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index];
const bool reportContacts = needToReportContacts && !isCollider1Trigger && !isCollider2Trigger;
// No middle-phase is necessary, simply create a narrow phase info
// for the narrow-phase collision detection
narrowPhaseInput.addNarrowPhaseTest(overlappingPair.pairID, collider1Entity, collider2Entity, collisionShape1, collisionShape2,
mCollidersComponents.mLocalToWorldTransforms[collider1Index],
mCollidersComponents.mLocalToWorldTransforms[collider2Index],
algorithmType, reportContacts, &overlappingPair.lastFrameCollisionInfo,
mMemoryManager.getSingleFrameAllocator());
overlappingPair.collidingInCurrentFrame = false;
}
// For each possible convex vs concave pair of bodies
const uint64 nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint64 i=0; i < nbConcavePairs; i++) {
OverlappingPairs::ConcaveOverlappingPair& overlappingPair = mOverlappingPairs.mConcavePairs[i];
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider2) != -1);
assert(mCollidersComponents.getBroadPhaseId(overlappingPair.collider1) != mCollidersComponents.getBroadPhaseId(overlappingPair.collider2));
computeConvexVsConcaveMiddlePhase(overlappingPair, mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, needToReportContacts);
overlappingPair.collidingInCurrentFrame = false;
}
}
// Compute the middle-phase collision detection
void CollisionDetectionSystem::computeMiddlePhaseCollisionSnapshot(Array<uint64>& convexPairs, Array<uint64>& concavePairs,
NarrowPhaseInput& narrowPhaseInput, bool reportContacts) {
RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler);
// Reserve memory for the narrow-phase input using cached capacity from previous frame
narrowPhaseInput.reserveMemory();
// Remove the obsolete last frame collision infos and mark all the others as obsolete
mOverlappingPairs.clearObsoleteLastFrameCollisionInfos();
// For each possible convex vs convex pair of bodies
const uint64 nbConvexPairs = convexPairs.size();
for (uint64 p=0; p < nbConvexPairs; p++) {
const uint64 pairId = convexPairs[p];
const uint64 pairIndex = mOverlappingPairs.mMapConvexPairIdToPairIndex[pairId];
assert(pairIndex < mOverlappingPairs.mConvexPairs.size());
const Entity collider1Entity = mOverlappingPairs.mConvexPairs[pairIndex].collider1;
const Entity collider2Entity = mOverlappingPairs.mConvexPairs[pairIndex].collider2;
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != -1);
assert(mCollidersComponents.getBroadPhaseId(collider2Entity) != -1);
assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != mCollidersComponents.getBroadPhaseId(collider2Entity));
CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index];
CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index];
NarrowPhaseAlgorithmType algorithmType = mOverlappingPairs.mConvexPairs[pairIndex].narrowPhaseAlgorithmType;
// No middle-phase is necessary, simply create a narrow phase info
// for the narrow-phase collision detection
narrowPhaseInput.addNarrowPhaseTest(pairId, collider1Entity, collider2Entity, collisionShape1, collisionShape2,
mCollidersComponents.mLocalToWorldTransforms[collider1Index],
mCollidersComponents.mLocalToWorldTransforms[collider2Index],
algorithmType, reportContacts, &mOverlappingPairs.mConvexPairs[pairIndex].lastFrameCollisionInfo, mMemoryManager.getSingleFrameAllocator());
}
// For each possible convex vs concave pair of bodies
const uint nbConcavePairs = concavePairs.size();
for (uint p=0; p < nbConcavePairs; p++) {
const uint64 pairId = concavePairs[p];
const uint64 pairIndex = mOverlappingPairs.mMapConcavePairIdToPairIndex[pairId];
assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider1) != -1);
assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider2) != -1);
assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider1) != mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mConcavePairs[pairIndex].collider2));
computeConvexVsConcaveMiddlePhase(mOverlappingPairs.mConcavePairs[pairIndex], mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, reportContacts);
}
}
// Compute the concave vs convex middle-phase algorithm for a given pair of bodies
void CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase(OverlappingPairs::ConcaveOverlappingPair& overlappingPair, MemoryAllocator& allocator, NarrowPhaseInput& narrowPhaseInput, bool reportContacts) {
RP3D_PROFILE("CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase()", mProfiler);
const Entity collider1 = overlappingPair.collider1;
const Entity collider2 = overlappingPair.collider2;
const uint collider1Index = mCollidersComponents.getEntityIndex(collider1);
const uint collider2Index = mCollidersComponents.getEntityIndex(collider2);
Transform& shape1LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider1Index];
Transform& shape2LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider2Index];
Transform convexToConcaveTransform;
// Collision shape 1 is convex, collision shape 2 is concave
ConvexShape* convexShape;
ConcaveShape* concaveShape;
if (overlappingPair.isShape1Convex) {
convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider1Index]);
concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider2Index]);
convexToConcaveTransform = shape2LocalToWorldTransform.getInverse() * shape1LocalToWorldTransform;
}
else { // Collision shape 2 is convex, collision shape 1 is concave
convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider2Index]);
concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider1Index]);
convexToConcaveTransform = shape1LocalToWorldTransform.getInverse() * shape2LocalToWorldTransform;
}
assert(convexShape->isConvex());
assert(!concaveShape->isConvex());
assert(overlappingPair.narrowPhaseAlgorithmType != NarrowPhaseAlgorithmType::None);
// Compute the convex shape AABB in the local-space of the convex shape
AABB aabb;
convexShape->computeAABB(aabb, convexToConcaveTransform);
// Compute the concave shape triangles that are overlapping with the convex mesh AABB
Array<Vector3> triangleVertices(allocator, 64);
Array<Vector3> triangleVerticesNormals(allocator, 64);
Array<uint> shapeIds(allocator, 64);
concaveShape->computeOverlappingTriangles(aabb, triangleVertices, triangleVerticesNormals, shapeIds, allocator);
assert(triangleVertices.size() == triangleVerticesNormals.size());
assert(shapeIds.size() == triangleVertices.size() / 3);
assert(triangleVertices.size() % 3 == 0);
assert(triangleVerticesNormals.size() % 3 == 0);
const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index];
const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index];
reportContacts = reportContacts && !isCollider1Trigger && !isCollider2Trigger;
CollisionShape* shape1;
CollisionShape* shape2;
if (overlappingPair.isShape1Convex) {
shape1 = convexShape;
}
else {
shape2 = convexShape;
}
// For each overlapping triangle
const uint32 nbShapeIds = shapeIds.size();
for (uint32 i=0; i < nbShapeIds; i++) {
// Create a triangle collision shape (the allocated memory for the TriangleShape will be released in the
// destructor of the corresponding NarrowPhaseInfo.
TriangleShape* triangleShape = new (allocator.allocate(sizeof(TriangleShape)))
TriangleShape(&(triangleVertices[i * 3]), &(triangleVerticesNormals[i * 3]), shapeIds[i], mTriangleHalfEdgeStructure, allocator);
#ifdef IS_RP3D_PROFILING_ENABLED
// Set the profiler to the triangle shape
triangleShape->setProfiler(mProfiler);
#endif
if (overlappingPair.isShape1Convex) {
shape2 = triangleShape;
}
else {
shape1 = triangleShape;
}
// Add a collision info for the two collision shapes into the overlapping pair (if not present yet)
LastFrameCollisionInfo* lastFrameInfo = overlappingPair.addLastFrameInfoIfNecessary(shape1->getId(), shape2->getId());
// Create a narrow phase info for the narrow-phase collision detection
narrowPhaseInput.addNarrowPhaseTest(overlappingPair.pairID, collider1, collider2, shape1, shape2,
shape1LocalToWorldTransform, shape2LocalToWorldTransform,
overlappingPair.narrowPhaseAlgorithmType, reportContacts, lastFrameInfo, allocator);
}
}
// Execute the narrow-phase collision detection algorithm on batches
bool CollisionDetectionSystem::testNarrowPhaseCollision(NarrowPhaseInput& narrowPhaseInput,
bool clipWithPreviousAxisIfStillColliding, MemoryAllocator& allocator) {
bool contactFound = false;
// Get the narrow-phase collision detection algorithms for each kind of collision shapes
SphereVsSphereAlgorithm* sphereVsSphereAlgo = mCollisionDispatch.getSphereVsSphereAlgorithm();
SphereVsCapsuleAlgorithm* sphereVsCapsuleAlgo = mCollisionDispatch.getSphereVsCapsuleAlgorithm();
CapsuleVsCapsuleAlgorithm* capsuleVsCapsuleAlgo = mCollisionDispatch.getCapsuleVsCapsuleAlgorithm();
SphereVsConvexPolyhedronAlgorithm* sphereVsConvexPolyAlgo = mCollisionDispatch.getSphereVsConvexPolyhedronAlgorithm();
CapsuleVsConvexPolyhedronAlgorithm* capsuleVsConvexPolyAlgo = mCollisionDispatch.getCapsuleVsConvexPolyhedronAlgorithm();
ConvexPolyhedronVsConvexPolyhedronAlgorithm* convexPolyVsConvexPolyAlgo = mCollisionDispatch.getConvexPolyhedronVsConvexPolyhedronAlgorithm();
// get the narrow-phase batches to test for collision for contacts
NarrowPhaseInfoBatch& sphereVsSphereBatchContacts = narrowPhaseInput.getSphereVsSphereBatch();
NarrowPhaseInfoBatch& sphereVsCapsuleBatchContacts = narrowPhaseInput.getSphereVsCapsuleBatch();
NarrowPhaseInfoBatch& capsuleVsCapsuleBatchContacts = narrowPhaseInput.getCapsuleVsCapsuleBatch();
NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatchContacts = narrowPhaseInput.getSphereVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatchContacts = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatchContacts = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch();
// Compute the narrow-phase collision detection for each kind of collision shapes (for contacts)
if (sphereVsSphereBatchContacts.getNbObjects() > 0) {
contactFound |= sphereVsSphereAlgo->testCollision(sphereVsSphereBatchContacts, 0, sphereVsSphereBatchContacts.getNbObjects(), allocator);
}
if (sphereVsCapsuleBatchContacts.getNbObjects() > 0) {
contactFound |= sphereVsCapsuleAlgo->testCollision(sphereVsCapsuleBatchContacts, 0, sphereVsCapsuleBatchContacts.getNbObjects(), allocator);
}
if (capsuleVsCapsuleBatchContacts.getNbObjects() > 0) {
contactFound |= capsuleVsCapsuleAlgo->testCollision(capsuleVsCapsuleBatchContacts, 0, capsuleVsCapsuleBatchContacts.getNbObjects(), allocator);
}
if (sphereVsConvexPolyhedronBatchContacts.getNbObjects() > 0) {
contactFound |= sphereVsConvexPolyAlgo->testCollision(sphereVsConvexPolyhedronBatchContacts, 0, sphereVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator);
}
if (capsuleVsConvexPolyhedronBatchContacts.getNbObjects() > 0) {
contactFound |= capsuleVsConvexPolyAlgo->testCollision(capsuleVsConvexPolyhedronBatchContacts, 0, capsuleVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator);
}
if (convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects() > 0) {
contactFound |= convexPolyVsConvexPolyAlgo->testCollision(convexPolyhedronVsConvexPolyhedronBatchContacts, 0, convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator);
}
return contactFound;
}
// Process the potential contacts after narrow-phase collision detection
void CollisionDetectionSystem::processAllPotentialContacts(NarrowPhaseInput& narrowPhaseInput, bool updateLastFrameInfo,
Array<ContactPointInfo>& potentialContactPoints,
Array<ContactManifoldInfo>& potentialContactManifolds,
Array<ContactPair>* contactPairs) {
assert(contactPairs->size() == 0);
Map<uint64, uint> mapPairIdToContactPairIndex(mMemoryManager.getHeapAllocator(), mPreviousMapPairIdToContactPairIndex.size());
// get the narrow-phase batches to test for collision
NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch();
NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch();
NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch();
NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch();
// Process the potential contacts
processPotentialContacts(sphereVsSphereBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(sphereVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(capsuleVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(sphereVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(capsuleVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
processPotentialContacts(convexPolyhedronVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints,
potentialContactManifolds, mapPairIdToContactPairIndex, contactPairs);
}
// Compute the narrow-phase collision detection
void CollisionDetectionSystem::computeNarrowPhase() {
RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhase()", mProfiler);
MemoryAllocator& allocator = mMemoryManager.getSingleFrameAllocator();
// Swap the previous and current contacts arrays
swapPreviousAndCurrentContacts();
mPotentialContactManifolds.reserve(mNbPreviousPotentialContactManifolds);
mPotentialContactPoints.reserve(mNbPreviousPotentialContactPoints);
// Test the narrow-phase collision detection on the batches to be tested
testNarrowPhaseCollision(mNarrowPhaseInput, true, allocator);
// Process all the potential contacts after narrow-phase collision
processAllPotentialContacts(mNarrowPhaseInput, true, mPotentialContactPoints,
mPotentialContactManifolds, mCurrentContactPairs);
// Reduce the number of contact points in the manifolds
reducePotentialContactManifolds(mCurrentContactPairs, mPotentialContactManifolds, mPotentialContactPoints);
// Add the contact pairs to the bodies
addContactPairsToBodies();
assert(mCurrentContactManifolds->size() == 0);
assert(mCurrentContactPoints->size() == 0);
}
// Add the contact pairs to the corresponding bodies
void CollisionDetectionSystem::addContactPairsToBodies() {
const uint32 nbContactPairs = mCurrentContactPairs->size();
for (uint32 p=0 ; p < nbContactPairs; p++) {
ContactPair& contactPair = (*mCurrentContactPairs)[p];
const bool isBody1Rigid = mRigidBodyComponents.hasComponent(contactPair.body1Entity);
const bool isBody2Rigid = mRigidBodyComponents.hasComponent(contactPair.body2Entity);
// Add the associated contact pair to both bodies of the pair (used to create islands later)
if (isBody1Rigid) {
mRigidBodyComponents.addContacPair(contactPair.body1Entity, p);
}
if (isBody2Rigid) {
mRigidBodyComponents.addContacPair(contactPair.body2Entity, p);
}
// If at least of body is a CollisionBody
if (!isBody1Rigid || !isBody2Rigid) {
// Add the pair index to the array of pairs with CollisionBody
mCollisionBodyContactPairsIndices.add(p);
}
}
}
// Compute the map from contact pairs ids to contact pair for the next frame
void CollisionDetectionSystem::computeMapPreviousContactPairs() {
mPreviousMapPairIdToContactPairIndex.clear();
const uint32 nbCurrentContactPairs = mCurrentContactPairs->size();
for (uint32 i=0; i < nbCurrentContactPairs; i++) {
mPreviousMapPairIdToContactPairIndex.add(Pair<uint64, uint>((*mCurrentContactPairs)[i].pairId, i));
}
}
// Compute the narrow-phase collision detection for the testOverlap() methods.
/// This method returns true if contacts are found.
bool CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot(NarrowPhaseInput& narrowPhaseInput, OverlapCallback* callback) {
RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot()", mProfiler);
MemoryAllocator& allocator = mMemoryManager.getPoolAllocator();
// Test the narrow-phase collision detection on the batches to be tested
bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator);
if (collisionFound && callback != nullptr) {
// Compute the overlapping colliders
Array<ContactPair> contactPairs(allocator);
Array<ContactPair> lostContactPairs(allocator); // Always empty in this case (snapshot)
computeOverlapSnapshotContactPairs(narrowPhaseInput, contactPairs);
// Report overlapping colliders
OverlapCallback::CallbackData callbackData(contactPairs, lostContactPairs, false, *mWorld);
(*callback).onOverlap(callbackData);
}
return collisionFound;
}
// Process the potential overlapping bodies for the testOverlap() methods
void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInput& narrowPhaseInput, Array<ContactPair>& contactPairs) const {
Set<uint64> setOverlapContactPairId(mMemoryManager.getHeapAllocator());
// get the narrow-phase batches to test for collision
NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch();
NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch();
NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch();
NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch();
NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch();
// Process the potential contacts
computeOverlapSnapshotContactPairs(sphereVsSphereBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(sphereVsCapsuleBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(capsuleVsCapsuleBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(sphereVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(capsuleVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId);
computeOverlapSnapshotContactPairs(convexPolyhedronVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId);
}
// Notify that the overlapping pairs where a given collider is involved need to be tested for overlap
void CollisionDetectionSystem::notifyOverlappingPairsToTestOverlap(Collider* collider) {
// Get the overlapping pairs involved with this collider
Array<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity());
const uint32 nbPairs = overlappingPairs.size();
for (uint32 i=0; i < nbPairs; i++) {
// Notify that the overlapping pair needs to be testbed for overlap
mOverlappingPairs.setNeedToTestOverlap(overlappingPairs[i], true);
}
}
// Convert the potential overlapping bodies for the testOverlap() methods
void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, Array<ContactPair>& contactPairs,
Set<uint64>& setOverlapContactPairId) const {
RP3D_PROFILE("CollisionDetectionSystem::computeSnapshotContactPairs()", mProfiler);
// For each narrow phase info object
for(uint i=0; i < narrowPhaseInfoBatch.getNbObjects(); i++) {
// If there is a collision
if (narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding) {
// If the contact pair does not already exist
if (!setOverlapContactPairId.contains(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId)) {
const Entity collider1Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity1;
const Entity collider2Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity2;
const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index];
// Create a new contact pair
ContactPair contactPair(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId, body1Entity, body2Entity, collider1Entity, collider2Entity, contactPairs.size(), isTrigger, false, mMemoryManager.getHeapAllocator());
contactPairs.add(contactPair);
setOverlapContactPairId.add(narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId);
}
}
narrowPhaseInfoBatch.resetContactPoints(i);
}
}
// Compute the narrow-phase collision detection for the testCollision() methods.
// This method returns true if contacts are found.
bool CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot(NarrowPhaseInput& narrowPhaseInput, CollisionCallback& callback) {
RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot()", mProfiler);
MemoryAllocator& allocator = mMemoryManager.getHeapAllocator();
// Test the narrow-phase collision detection on the batches to be tested
bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator);
// If collision has been found, create contacts
if (collisionFound) {
Array<ContactPointInfo> potentialContactPoints(allocator);
Array<ContactManifoldInfo> potentialContactManifolds(allocator);
Array<ContactPair> contactPairs(allocator);
Array<ContactPair> lostContactPairs(allocator); // Not used during collision snapshots
Array<ContactManifold> contactManifolds(allocator);
Array<ContactPoint> contactPoints(allocator);
// Process all the potential contacts after narrow-phase collision
processAllPotentialContacts(narrowPhaseInput, true, potentialContactPoints, potentialContactManifolds, &contactPairs);
// Reduce the number of contact points in the manifolds
reducePotentialContactManifolds(&contactPairs, potentialContactManifolds, potentialContactPoints);
// Create the actual contact manifolds and contact points
createSnapshotContacts(contactPairs, contactManifolds, contactPoints, potentialContactManifolds, potentialContactPoints);
// Report the contacts to the user
reportContacts(callback, &contactPairs, &contactManifolds, &contactPoints, lostContactPairs);
}
return collisionFound;
}
// Swap the previous and current contacts arrays
void CollisionDetectionSystem::swapPreviousAndCurrentContacts() {
if (mPreviousContactPairs == &mContactPairs1) {
mPreviousContactPairs = &mContactPairs2;
mPreviousContactManifolds = &mContactManifolds2;
mPreviousContactPoints = &mContactPoints2;
mCurrentContactPairs = &mContactPairs1;
mCurrentContactManifolds = &mContactManifolds1;
mCurrentContactPoints = &mContactPoints1;
}
else {
mPreviousContactPairs = &mContactPairs1;
mPreviousContactManifolds = &mContactManifolds1;
mPreviousContactPoints = &mContactPoints1;
mCurrentContactPairs = &mContactPairs2;
mCurrentContactManifolds = &mContactManifolds2;
mCurrentContactPoints = &mContactPoints2;
}
}
// Create the actual contact manifolds and contacts points
void CollisionDetectionSystem::createContacts() {
RP3D_PROFILE("CollisionDetectionSystem::createContacts()", mProfiler);
mCurrentContactManifolds->reserve(mCurrentContactPairs->size());
mCurrentContactPoints->reserve(mCurrentContactManifolds->size());
// We go through all the contact pairs and add the pairs with a least a CollisionBody at the end of the
// mProcessContactPairsOrderIslands array because those pairs have not been added during the islands
// creation (only the pairs with two RigidBodies are added during island creation)
mWorld->mProcessContactPairsOrderIslands.addRange(mCollisionBodyContactPairsIndices);
assert(mWorld->mProcessContactPairsOrderIslands.size() == (*mCurrentContactPairs).size());
// Process the contact pairs in the order defined by the islands such that the contact manifolds and
// contact points of a given island are packed together in the array of manifolds and contact points
const uint32 nbContactPairsToProcess = mWorld->mProcessContactPairsOrderIslands.size();
for (uint p=0; p < nbContactPairsToProcess; p++) {
uint32 contactPairIndex = mWorld->mProcessContactPairsOrderIslands[p];
ContactPair& contactPair = (*mCurrentContactPairs)[contactPairIndex];
contactPair.contactManifoldsIndex = mCurrentContactManifolds->size();
contactPair.nbContactManifolds = contactPair.potentialContactManifoldsIndices.size();
contactPair.contactPointsIndex = mCurrentContactPoints->size();
// For each potential contact manifold of the pair
for (uint32 m=0; m < contactPair.nbContactManifolds; m++) {
ContactManifoldInfo& potentialManifold = mPotentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]];
// Start index and number of contact points for this manifold
const uint32 contactPointsIndex = mCurrentContactPoints->size();
const uint32 nbContactPoints = static_cast<uint32>(potentialManifold.potentialContactPointsIndices.size());
contactPair.nbToTalContactPoints += nbContactPoints;
// Create and add the contact manifold
mCurrentContactManifolds->emplace(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity,
contactPair.collider2Entity, contactPointsIndex, nbContactPoints);
assert(potentialManifold.potentialContactPointsIndices.size() > 0);
// For each contact point of the manifold
for (uint c=0; c < nbContactPoints; c++) {
ContactPointInfo& potentialContactPoint = mPotentialContactPoints[potentialManifold.potentialContactPointsIndices[c]];
// Create and add the contact point
mCurrentContactPoints->emplace(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold);
}
}
}
// Initialize the current contacts with the contacts from the previous frame (for warmstarting)
initContactsWithPreviousOnes();
// Compute the lost contacts (contact pairs that were colliding in previous frame but not in this one)
computeLostContactPairs();
mPreviousContactPoints->clear();
mPreviousContactManifolds->clear();
mPreviousContactPairs->clear();
mNbPreviousPotentialContactManifolds = mPotentialContactManifolds.capacity();
mNbPreviousPotentialContactPoints = mPotentialContactPoints.capacity();
// Reset the potential contacts
mPotentialContactPoints.clear(true);
mPotentialContactManifolds.clear(true);
// Compute the map from contact pairs ids to contact pair for the next frame
computeMapPreviousContactPairs();
mCollisionBodyContactPairsIndices.clear(true);
mNarrowPhaseInput.clear();
}
// Compute the lost contact pairs (contact pairs in contact in the previous frame but not in the current one)
void CollisionDetectionSystem::computeLostContactPairs() {
// For each convex pair
const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint32 i=0; i < nbConvexPairs; i++) {
// If the two colliders of the pair were colliding in the previous frame but not in the current one
if (mOverlappingPairs.mConvexPairs[i].collidingInPreviousFrame && !mOverlappingPairs.mConvexPairs[i].collidingInCurrentFrame) {
// If both bodies still exist
if (mCollidersComponents.hasComponent(mOverlappingPairs.mConvexPairs[i].collider1) && mCollidersComponents.hasComponent(mOverlappingPairs.mConvexPairs[i].collider2)) {
// Create a lost contact pair
addLostContactPair(mOverlappingPairs.mConvexPairs[i]);
}
}
}
// For each convex pair
const uint32 nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint32 i=0; i < nbConcavePairs; i++) {
// If the two colliders of the pair were colliding in the previous frame but not in the current one
if (mOverlappingPairs.mConcavePairs[i].collidingInPreviousFrame && !mOverlappingPairs.mConcavePairs[i].collidingInCurrentFrame) {
// If both bodies still exist
if (mCollidersComponents.hasComponent(mOverlappingPairs.mConcavePairs[i].collider1) && mCollidersComponents.hasComponent(mOverlappingPairs.mConcavePairs[i].collider2)) {
// Create a lost contact pair
addLostContactPair(mOverlappingPairs.mConcavePairs[i]);
}
}
}
}
// Create the actual contact manifolds and contacts points for testCollision() methods
void CollisionDetectionSystem::createSnapshotContacts(Array<ContactPair>& contactPairs,
Array<ContactManifold>& contactManifolds,
Array<ContactPoint>& contactPoints,
Array<ContactManifoldInfo>& potentialContactManifolds,
Array<ContactPointInfo>& potentialContactPoints) {
RP3D_PROFILE("CollisionDetectionSystem::createSnapshotContacts()", mProfiler);
contactManifolds.reserve(contactPairs.size());
contactPoints.reserve(contactManifolds.size());
// For each contact pair
const uint32 nbContactPairs = contactPairs.size();
for (uint32 p=0; p < nbContactPairs; p++) {
ContactPair& contactPair = contactPairs[p];
assert(contactPair.potentialContactManifoldsIndices.size() > 0);
contactPair.contactManifoldsIndex = contactManifolds.size();
contactPair.nbContactManifolds = contactPair.potentialContactManifoldsIndices.size();
contactPair.contactPointsIndex = contactPoints.size();
// For each potential contact manifold of the pair
for (uint32 m=0; m < contactPair.nbContactManifolds; m++) {
ContactManifoldInfo& potentialManifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]];
// Start index and number of contact points for this manifold
const uint32 contactPointsIndex = contactPoints.size();
const uint32 nbContactPoints = static_cast<uint32>(potentialManifold.potentialContactPointsIndices.size());
contactPair.nbToTalContactPoints += nbContactPoints;
// Create and add the contact manifold
contactManifolds.emplace(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity,
contactPair.collider2Entity, contactPointsIndex, nbContactPoints);
assert(nbContactPoints > 0);
// For each contact point of the manifold
for (uint32 c=0; c < nbContactPoints; c++) {
ContactPointInfo& potentialContactPoint = potentialContactPoints[potentialManifold.potentialContactPointsIndices[c]];
// Create a new contact point
ContactPoint contactPoint(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold);
// Add the contact point
contactPoints.add(contactPoint);
}
}
}
}
// Initialize the current contacts with the contacts from the previous frame (for warmstarting)
void CollisionDetectionSystem::initContactsWithPreviousOnes() {
const decimal persistentContactDistThresholdSqr = mWorld->mConfig.persistentContactDistanceThreshold * mWorld->mConfig.persistentContactDistanceThreshold;
// For each contact pair of the current frame
const uint32 nbCurrentContactPairs = mCurrentContactPairs->size();
for (uint32 i=0; i < nbCurrentContactPairs; i++) {
ContactPair& currentContactPair = (*mCurrentContactPairs)[i];
// Find the corresponding contact pair in the previous frame (if any)
auto itPrevContactPair = mPreviousMapPairIdToContactPairIndex.find(currentContactPair.pairId);
// If we have found a corresponding contact pair in the previous frame
if (itPrevContactPair != mPreviousMapPairIdToContactPairIndex.end()) {
const uint previousContactPairIndex = itPrevContactPair->second;
ContactPair& previousContactPair = (*mPreviousContactPairs)[previousContactPairIndex];
// --------------------- Contact Manifolds --------------------- //
const uint contactManifoldsIndex = currentContactPair.contactManifoldsIndex;
const uint nbContactManifolds = currentContactPair.nbContactManifolds;
// For each current contact manifold of the current contact pair
for (uint m=contactManifoldsIndex; m < contactManifoldsIndex + nbContactManifolds; m++) {
assert(m < mCurrentContactManifolds->size());
ContactManifold& currentContactManifold = (*mCurrentContactManifolds)[m];
assert(currentContactManifold.nbContactPoints > 0);
ContactPoint& currentContactPoint = (*mCurrentContactPoints)[currentContactManifold.contactPointsIndex];
const Vector3& currentContactPointNormal = currentContactPoint.getNormal();
// Find a similar contact manifold among the contact manifolds from the previous frame (for warmstarting)
const uint previousContactManifoldIndex = previousContactPair.contactManifoldsIndex;
const uint previousNbContactManifolds = previousContactPair.nbContactManifolds;
for (uint p=previousContactManifoldIndex; p < previousContactManifoldIndex + previousNbContactManifolds; p++) {
ContactManifold& previousContactManifold = (*mPreviousContactManifolds)[p];
assert(previousContactManifold.nbContactPoints > 0);
ContactPoint& previousContactPoint = (*mPreviousContactPoints)[previousContactManifold.contactPointsIndex];
// If the previous contact manifold has a similar contact normal with the current manifold
if (previousContactPoint.getNormal().dot(currentContactPointNormal) >= mWorld->mConfig.cosAngleSimilarContactManifold) {
// Transfer data from the previous contact manifold to the current one
currentContactManifold.frictionVector1 = previousContactManifold.frictionVector1;
currentContactManifold.frictionVector2 = previousContactManifold.frictionVector2;
currentContactManifold.frictionImpulse1 = previousContactManifold.frictionImpulse1;
currentContactManifold.frictionImpulse2 = previousContactManifold.frictionImpulse2;
currentContactManifold.frictionTwistImpulse = previousContactManifold.frictionTwistImpulse;
break;
}
}
}
// --------------------- Contact Points --------------------- //
const uint contactPointsIndex = currentContactPair.contactPointsIndex;
const uint nbTotalContactPoints = currentContactPair.nbToTalContactPoints;
// For each current contact point of the current contact pair
for (uint c=contactPointsIndex; c < contactPointsIndex + nbTotalContactPoints; c++) {
assert(c < mCurrentContactPoints->size());
ContactPoint& currentContactPoint = (*mCurrentContactPoints)[c];
const Vector3& currentContactPointLocalShape1 = currentContactPoint.getLocalPointOnShape1();
// Find a similar contact point among the contact points from the previous frame (for warmstarting)
const uint previousContactPointsIndex = previousContactPair.contactPointsIndex;
const uint previousNbContactPoints = previousContactPair.nbToTalContactPoints;
for (uint p=previousContactPointsIndex; p < previousContactPointsIndex + previousNbContactPoints; p++) {
const ContactPoint& previousContactPoint = (*mPreviousContactPoints)[p];
// If the previous contact point is very close to th current one
const decimal distSquare = (currentContactPointLocalShape1 - previousContactPoint.getLocalPointOnShape1()).lengthSquare();
if (distSquare <= persistentContactDistThresholdSqr) {
// Transfer data from the previous contact point to the current one
currentContactPoint.setPenetrationImpulse(previousContactPoint.getPenetrationImpulse());
currentContactPoint.setIsRestingContact(previousContactPoint.getIsRestingContact());
break;
}
}
}
}
}
}
// Remove a body from the collision detection
void CollisionDetectionSystem::removeCollider(Collider* collider) {
const int colliderBroadPhaseId = collider->getBroadPhaseId();
assert(colliderBroadPhaseId != -1);
assert(mMapBroadPhaseIdToColliderEntity.containsKey(colliderBroadPhaseId));
// Remove all the overlapping pairs involving this collider
Array<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity());
while(overlappingPairs.size() > 0) {
// TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds array of the two bodies involved
// Remove the overlapping pair
mOverlappingPairs.removePair(overlappingPairs[0]);
}
mMapBroadPhaseIdToColliderEntity.remove(colliderBroadPhaseId);
// Remove the body from the broad-phase
mBroadPhaseSystem.removeCollider(collider);
}
// Ray casting method
void CollisionDetectionSystem::raycast(RaycastCallback* raycastCallback, const Ray& ray, unsigned short raycastWithCategoryMaskBits) const {
RP3D_PROFILE("CollisionDetectionSystem::raycast()", mProfiler);
RaycastTest rayCastTest(raycastCallback);
// Ask the broad-phase algorithm to call the testRaycastAgainstShape()
// callback method for each collider hit by the ray in the broad-phase
mBroadPhaseSystem.raycast(ray, rayCastTest, raycastWithCategoryMaskBits);
}
// Convert the potential contact into actual contacts
void CollisionDetectionSystem::processPotentialContacts(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, bool updateLastFrameInfo,
Array<ContactPointInfo>& potentialContactPoints,
Array<ContactManifoldInfo>& potentialContactManifolds,
Map<uint64, uint>& mapPairIdToContactPairIndex,
Array<ContactPair>* contactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::processPotentialContacts()", mProfiler);
const uint nbObjects = narrowPhaseInfoBatch.getNbObjects();
if (updateLastFrameInfo) {
// For each narrow phase info object
for(uint i=0; i < nbObjects; i++) {
narrowPhaseInfoBatch.narrowPhaseInfos[i].lastFrameCollisionInfo->wasColliding = narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding;
// The previous frame collision info is now valid
narrowPhaseInfoBatch.narrowPhaseInfos[i].lastFrameCollisionInfo->isValid = true;
}
}
// For each narrow phase info object
for(uint i=0; i < nbObjects; i++) {
// If the two colliders are colliding
if (narrowPhaseInfoBatch.narrowPhaseInfos[i].isColliding) {
const uint64 pairId = narrowPhaseInfoBatch.narrowPhaseInfos[i].overlappingPairId;
OverlappingPairs::OverlappingPair* overlappingPair = mOverlappingPairs.getOverlappingPair(pairId);
assert(overlappingPair != nullptr);
overlappingPair->collidingInCurrentFrame = true;
const Entity collider1Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity1;
const Entity collider2Entity = narrowPhaseInfoBatch.narrowPhaseInfos[i].colliderEntity2;
const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity);
const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity);
const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index];
const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index];
// If we have a convex vs convex collision (if we consider the base collision shapes of the colliders)
if (mCollidersComponents.mCollisionShapes[collider1Index]->isConvex() && mCollidersComponents.mCollisionShapes[collider2Index]->isConvex()) {
// Create a new ContactPair
const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index];
assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity));
const uint32 newContactPairIndex = contactPairs->size();
contactPairs->emplace(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity,
newContactPairIndex, overlappingPair->collidingInPreviousFrame, isTrigger, mMemoryManager.getHeapAllocator());
ContactPair* pairContact = &((*contactPairs)[newContactPairIndex]);
// Create a new potential contact manifold for the overlapping pair
uint32 contactManifoldIndex = static_cast<uint>(potentialContactManifolds.size());
potentialContactManifolds.emplace(pairId, mMemoryManager.getHeapAllocator());
ContactManifoldInfo& contactManifoldInfo = potentialContactManifolds[contactManifoldIndex];
const uint32 contactPointIndexStart = static_cast<uint>(potentialContactPoints.size());
// Add the potential contacts
for (uint j=0; j < narrowPhaseInfoBatch.narrowPhaseInfos[i].nbContactPoints; j++) {
// Add the contact point to the manifold
contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndexStart + j);
// Add the contact point to the array of potential contact points
const ContactPointInfo& contactPoint = narrowPhaseInfoBatch.narrowPhaseInfos[i].contactPoints[j];
potentialContactPoints.add(contactPoint);
}
// Add the contact manifold to the overlapping pair contact
assert(pairId == contactManifoldInfo.pairId);
pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex);
}
else {
// If there is not already a contact pair for this overlapping pair
auto it = mapPairIdToContactPairIndex.find(pairId);
ContactPair* pairContact = nullptr;
if (it == mapPairIdToContactPairIndex.end()) {
// Create a new ContactPair
const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index];
assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity));
const uint32 newContactPairIndex = contactPairs->size();
contactPairs->emplace(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity,
newContactPairIndex, overlappingPair->collidingInPreviousFrame, isTrigger, mMemoryManager.getHeapAllocator());
pairContact = &((*contactPairs)[newContactPairIndex]);
mapPairIdToContactPairIndex.add(Pair<uint64, uint>(pairId, newContactPairIndex));
}
else { // If a ContactPair already exists for this overlapping pair, we use this one
assert(it->first == pairId);
const uint pairContactIndex = it->second;
pairContact = &((*contactPairs)[pairContactIndex]);
}
assert(pairContact != nullptr);
// Add the potential contacts
for (uint j=0; j < narrowPhaseInfoBatch.narrowPhaseInfos[i].nbContactPoints; j++) {
const ContactPointInfo& contactPoint = narrowPhaseInfoBatch.narrowPhaseInfos[i].contactPoints[j];
// Add the contact point to the array of potential contact points
const uint32 contactPointIndex = potentialContactPoints.size();
potentialContactPoints.add(contactPoint);
bool similarManifoldFound = false;
// For each contact manifold of the overlapping pair
const uint32 nbPotentialManifolds = pairContact->potentialContactManifoldsIndices.size();
for (uint m=0; m < nbPotentialManifolds; m++) {
uint contactManifoldIndex = pairContact->potentialContactManifoldsIndices[m];
// Get the first contact point of the current manifold
assert(potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.size() > 0);
const uint manifoldContactPointIndex = potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices[0];
const ContactPointInfo& manifoldContactPoint = potentialContactPoints[manifoldContactPointIndex];
// If we have found a corresponding manifold for the new contact point
// (a manifold with a similar contact normal direction)
if (manifoldContactPoint.normal.dot(contactPoint.normal) >= mWorld->mConfig.cosAngleSimilarContactManifold) {
// Add the contact point to the manifold
potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.add(contactPointIndex);
similarManifoldFound = true;
break;
}
}
// If we have not found a manifold with a similar contact normal for the contact point
if (!similarManifoldFound) {
// Create a new potential contact manifold for the overlapping pair
uint32 contactManifoldIndex = potentialContactManifolds.size();
potentialContactManifolds.emplace(pairId, mMemoryManager.getHeapAllocator());
ContactManifoldInfo& contactManifoldInfo = potentialContactManifolds[contactManifoldIndex];
// Add the contact point to the manifold
contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndex);
assert(pairContact != nullptr);
// Add the contact manifold to the overlapping pair contact
assert(pairContact->pairId == contactManifoldInfo.pairId);
pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex);
}
assert(pairContact->potentialContactManifoldsIndices.size() > 0);
}
}
narrowPhaseInfoBatch.resetContactPoints(i);
}
}
}
// Clear the obsolete manifolds and contact points and reduce the number of contacts points of the remaining manifolds
void CollisionDetectionSystem::reducePotentialContactManifolds(Array<ContactPair>* contactPairs,
Array<ContactManifoldInfo>& potentialContactManifolds,
const Array<ContactPointInfo>& potentialContactPoints) const {
RP3D_PROFILE("CollisionDetectionSystem::reducePotentialContactManifolds()", mProfiler);
// Reduce the number of potential contact manifolds in a contact pair
const uint32 nbContactPairs = contactPairs->size();
for (uint32 i=0; i < nbContactPairs; i++) {
ContactPair& contactPair = (*contactPairs)[i];
// While there are too many manifolds in the contact pair
while(contactPair.potentialContactManifoldsIndices.size() > NB_MAX_CONTACT_MANIFOLDS) {
// Look for a manifold with the smallest contact penetration depth.
decimal minDepth = DECIMAL_LARGEST;
int minDepthManifoldIndex = -1;
for (uint32 j=0; j < contactPair.potentialContactManifoldsIndices.size(); j++) {
ContactManifoldInfo& manifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[j]];
// Get the largest contact point penetration depth of the manifold
const decimal depth = computePotentialManifoldLargestContactDepth(manifold, potentialContactPoints);
if (depth < minDepth) {
minDepth = depth;
minDepthManifoldIndex = static_cast<int>(j);
}
}
// Remove the non optimal manifold
assert(minDepthManifoldIndex >= 0);
contactPair.removePotentialManifoldAtIndex(minDepthManifoldIndex);
}
}
// Reduce the number of potential contact points in the manifolds
for (uint32 i=0; i < nbContactPairs; i++) {
const ContactPair& pairContact = (*contactPairs)[i];
// For each potential contact manifold
for (uint32 j=0; j < pairContact.potentialContactManifoldsIndices.size(); j++) {
ContactManifoldInfo& manifold = potentialContactManifolds[pairContact.potentialContactManifoldsIndices[j]];
// If there are two many contact points in the manifold
if (manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD) {
Transform shape1LocalToWorldTransoform = mCollidersComponents.getLocalToWorldTransform(pairContact.collider1Entity);
// Reduce the number of contact points in the manifold
reduceContactPoints(manifold, shape1LocalToWorldTransoform, potentialContactPoints);
}
assert(manifold.potentialContactPointsIndices.size() <= MAX_CONTACT_POINTS_IN_MANIFOLD);
// Remove the duplicated contact points in the manifold (if any)
removeDuplicatedContactPointsInManifold(manifold, potentialContactPoints);
}
}
}
// Return the largest depth of all the contact points of a potential manifold
decimal CollisionDetectionSystem::computePotentialManifoldLargestContactDepth(const ContactManifoldInfo& manifold,
const Array<ContactPointInfo>& potentialContactPoints) const {
decimal largestDepth = 0.0f;
const uint32 nbContactPoints = static_cast<uint32>(manifold.potentialContactPointsIndices.size());
assert(nbContactPoints > 0);
for (uint32 i=0; i < nbContactPoints; i++) {
decimal depth = potentialContactPoints[manifold.potentialContactPointsIndices[i]].penetrationDepth;
if (depth > largestDepth) {
largestDepth = depth;
}
}
return largestDepth;
}
// Reduce the number of contact points of a potential contact manifold
// This is based on the technique described by Dirk Gregorius in his
// "Contacts Creation" GDC presentation. This method will reduce the number of
// contact points to a maximum of 4 points (but it can be less).
void CollisionDetectionSystem::reduceContactPoints(ContactManifoldInfo& manifold, const Transform& shape1ToWorldTransform,
const Array<ContactPointInfo>& potentialContactPoints) const {
assert(manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD);
// The following algorithm only works to reduce to a maximum of 4 contact points
assert(MAX_CONTACT_POINTS_IN_MANIFOLD == 4);
// Array of the candidate contact points indices in the manifold. Every time that we have found a
// point we want to keep, we will remove it from this array
Array<uint> candidatePointsIndices(manifold.potentialContactPointsIndices);
assert(manifold.potentialContactPointsIndices.size() == candidatePointsIndices.size());
int8 nbReducedPoints = 0;
uint pointsToKeepIndices[MAX_CONTACT_POINTS_IN_MANIFOLD];
for (int8 i=0; i<MAX_CONTACT_POINTS_IN_MANIFOLD; i++) {
pointsToKeepIndices[i] = 0;
}
// Compute the initial contact point we need to keep.
// The first point we keep is always the point in a given
// constant direction (in order to always have same contact points
// between frames for better stability)
const Transform worldToShape1Transform = shape1ToWorldTransform.getInverse();
// Compute the contact normal of the manifold (we use the first contact point)
// in the local-space of the first collision shape
const Vector3 contactNormalShape1Space = worldToShape1Transform.getOrientation() * potentialContactPoints[candidatePointsIndices[0]].normal;
// Compute a search direction
const Vector3 searchDirection(1, 1, 1);
decimal maxDotProduct = DECIMAL_SMALLEST;
uint elementIndexToKeep = 0;
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
decimal dotProduct = searchDirection.dot(element.localPoint1);
if (dotProduct > maxDotProduct) {
maxDotProduct = dotProduct;
elementIndexToKeep = i;
nbReducedPoints = 1;
}
}
pointsToKeepIndices[0] = candidatePointsIndices[elementIndexToKeep];
removeItemAtInArray(candidatePointsIndices, elementIndexToKeep);
//candidatePointsIndices.removeAt(elementIndexToKeep);
assert(nbReducedPoints == 1);
// Compute the second contact point we need to keep.
// The second point we keep is the one farthest away from the first point.
decimal maxDistance = decimal(0.0);
elementIndexToKeep = 0;
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]];
assert(candidatePointsIndices[i] != pointsToKeepIndices[0]);
const decimal distance = (pointToKeep0.localPoint1 - element.localPoint1).lengthSquare();
if (distance >= maxDistance) {
maxDistance = distance;
elementIndexToKeep = i;
nbReducedPoints = 2;
}
}
pointsToKeepIndices[1] = candidatePointsIndices[elementIndexToKeep];
removeItemAtInArray(candidatePointsIndices, elementIndexToKeep);
assert(nbReducedPoints == 2);
// Compute the third contact point we need to keep.
// The third point is the one producing the triangle with the larger area
// with first and second point.
// We compute the most positive or most negative triangle area (depending on winding)
uint thirdPointMaxAreaIndex = 0;
uint thirdPointMinAreaIndex = 0;
decimal minArea = decimal(0.0);
decimal maxArea = decimal(0.0);
bool isPreviousAreaPositive = true;
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]];
const ContactPointInfo& pointToKeep1 = potentialContactPoints[pointsToKeepIndices[1]];
assert(candidatePointsIndices[i] != pointsToKeepIndices[0]);
assert(candidatePointsIndices[i] != pointsToKeepIndices[1]);
const Vector3 newToFirst = pointToKeep0.localPoint1 - element.localPoint1;
const Vector3 newToSecond = pointToKeep1.localPoint1 - element.localPoint1;
// Compute the triangle area
decimal area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space);
if (area >= maxArea) {
maxArea = area;
thirdPointMaxAreaIndex = i;
}
if (area <= minArea) {
minArea = area;
thirdPointMinAreaIndex = i;
}
}
assert(minArea <= decimal(0.0));
assert(maxArea >= decimal(0.0));
if (maxArea > (-minArea)) {
isPreviousAreaPositive = true;
pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMaxAreaIndex];
removeItemAtInArray(candidatePointsIndices, thirdPointMaxAreaIndex);
}
else {
isPreviousAreaPositive = false;
pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMinAreaIndex];
removeItemAtInArray(candidatePointsIndices, thirdPointMinAreaIndex);
}
nbReducedPoints = 3;
// Compute the 4th point by choosing the triangle that adds the most
// triangle area to the previous triangle and has opposite sign area (opposite winding)
decimal largestArea = decimal(0.0); // Largest area (positive or negative)
elementIndexToKeep = 0;
nbReducedPoints = 4;
decimal area;
// For each remaining candidate points
for (uint i=0; i < candidatePointsIndices.size(); i++) {
const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]];
assert(candidatePointsIndices[i] != pointsToKeepIndices[0]);
assert(candidatePointsIndices[i] != pointsToKeepIndices[1]);
assert(candidatePointsIndices[i] != pointsToKeepIndices[2]);
// For each edge of the triangle made by the first three points
for (uint j=0; j<3; j++) {
uint edgeVertex1Index = j;
uint edgeVertex2Index = j < 2 ? j + 1 : 0;
const ContactPointInfo& pointToKeepEdgeV1 = potentialContactPoints[pointsToKeepIndices[edgeVertex1Index]];
const ContactPointInfo& pointToKeepEdgeV2 = potentialContactPoints[pointsToKeepIndices[edgeVertex2Index]];
const Vector3 newToFirst = pointToKeepEdgeV1.localPoint1 - element.localPoint1;
const Vector3 newToSecond = pointToKeepEdgeV2.localPoint1 - element.localPoint1;
// Compute the triangle area
area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space);
// We are looking at the triangle with maximal area (positive or negative).
// If the previous area is positive, we are looking at negative area now.
// If the previous area is negative, we are looking at the positive area now.
if (isPreviousAreaPositive && area <= largestArea) {
largestArea = area;
elementIndexToKeep = i;
}
else if (!isPreviousAreaPositive && area >= largestArea) {
largestArea = area;
elementIndexToKeep = i;
}
}
}
pointsToKeepIndices[3] = candidatePointsIndices[elementIndexToKeep];
removeItemAtInArray(candidatePointsIndices, elementIndexToKeep);
// Only keep the four selected contact points in the manifold
manifold.potentialContactPointsIndices.clear();
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[0]);
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[1]);
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[2]);
manifold.potentialContactPointsIndices.add(pointsToKeepIndices[3]);
}
// Remove the duplicated contact points in a given contact manifold
void CollisionDetectionSystem::removeDuplicatedContactPointsInManifold(ContactManifoldInfo& manifold,
const Array<ContactPointInfo>& potentialContactPoints) const {
RP3D_PROFILE("CollisionDetectionSystem::removeDuplicatedContactPointsInManifold()", mProfiler);
const decimal distThresholdSqr = SAME_CONTACT_POINT_DISTANCE_THRESHOLD * SAME_CONTACT_POINT_DISTANCE_THRESHOLD;
// For each contact point of the manifold
for (uint32 i=0; i < manifold.potentialContactPointsIndices.size(); i++) {
for (uint32 j=i+1; j < manifold.potentialContactPointsIndices.size(); j++) {
const ContactPointInfo& point1 = potentialContactPoints[manifold.potentialContactPointsIndices[i]];
const ContactPointInfo& point2 = potentialContactPoints[manifold.potentialContactPointsIndices[j]];
// Compute the distance between the two contact points
const decimal distSqr = (point2.localPoint1 - point1.localPoint1).lengthSquare();
// We have a found a duplicated contact point
if (distSqr < distThresholdSqr) {
// Remove the duplicated contact point
manifold.potentialContactPointsIndices.removeAtAndReplaceByLast(j);
j--;
}
}
}
}
// Remove an element in an array (and replace it by the last one in the array)
void CollisionDetectionSystem::removeItemAtInArray(Array<uint>& array, uint32 index) const {
assert(index < array.size());
assert(array.size() > 0);
array.removeAtAndReplaceByLast(index);
}
// Report contacts and triggers
void CollisionDetectionSystem::reportContactsAndTriggers() {
// Report contacts and triggers to the user
if (mWorld->mEventListener != nullptr) {
reportContacts(*(mWorld->mEventListener), mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs);
reportTriggers(*(mWorld->mEventListener), mCurrentContactPairs, mLostContactPairs);
}
// Report contacts for debug rendering (if enabled)
if (mWorld->mIsDebugRenderingEnabled) {
reportDebugRenderingContacts(mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs);
}
mOverlappingPairs.updateCollidingInPreviousFrame();
mLostContactPairs.clear(true);
}
// Report all contacts to the user
void CollisionDetectionSystem::reportContacts(CollisionCallback& callback, Array<ContactPair>* contactPairs,
Array<ContactManifold>* manifolds, Array<ContactPoint>* contactPoints, Array<ContactPair>& lostContactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::reportContacts()", mProfiler);
// If there are contacts
if (contactPairs->size() + lostContactPairs.size() > 0) {
CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld);
// Call the callback method to report the contacts
callback.onContact(callbackData);
}
}
// Report all triggers to the user
void CollisionDetectionSystem::reportTriggers(EventListener& eventListener, Array<ContactPair>* contactPairs, Array<ContactPair>& lostContactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::reportTriggers()", mProfiler);
// If there are contacts
if (contactPairs->size() + lostContactPairs.size() > 0) {
OverlapCallback::CallbackData callbackData(*contactPairs, lostContactPairs, true, *mWorld);
// Call the callback method to report the overlapping shapes
eventListener.onTrigger(callbackData);
}
}
// Report all contacts for debug rendering
void CollisionDetectionSystem::reportDebugRenderingContacts(Array<ContactPair>* contactPairs, Array<ContactManifold>* manifolds, Array<ContactPoint>* contactPoints, Array<ContactPair>& lostContactPairs) {
RP3D_PROFILE("CollisionDetectionSystem::reportDebugRenderingContacts()", mProfiler);
// If there are contacts
if (contactPairs->size() + lostContactPairs.size() > 0) {
CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld);
// Call the callback method to report the contacts
mWorld->mDebugRenderer.onContact(callbackData);
}
}
// Return true if two bodies overlap (collide)
bool CollisionDetectionSystem::testOverlap(CollisionBody* body1, CollisionBody* body2) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false);
// Compute the narrow-phase collision detection
return computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, nullptr);
}
return false;
}
// Report all the bodies that overlap (collide) in the world
void CollisionDetectionSystem::testOverlap(OverlapCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Compute the middle-phase collision detection
computeMiddlePhase(narrowPhaseInput, false);
// Compute the narrow-phase collision detection and report overlapping shapes
computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback);
}
// Report all the bodies that overlap (collide) with the body in parameter
void CollisionDetectionSystem::testOverlap(CollisionBody* body, OverlapCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false);
// Compute the narrow-phase collision detection
computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback);
}
}
// Test collision and report contacts between two bodies.
void CollisionDetectionSystem::testCollision(CollisionBody* body1, CollisionBody* body2, CollisionCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true);
// Compute the narrow-phase collision detection and report contacts
computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback);
}
}
// Test collision and report all the contacts involving the body in parameter
void CollisionDetectionSystem::testCollision(CollisionBody* body, CollisionCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Filter the overlapping pairs to get only the ones with the selected body involved
Array<uint64> convexPairs(mMemoryManager.getPoolAllocator());
Array<uint64> concavePairs(mMemoryManager.getPoolAllocator());
filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs);
if (convexPairs.size() > 0 || concavePairs.size() > 0) {
// Compute the middle-phase collision detection
computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true);
// Compute the narrow-phase collision detection and report contacts
computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback);
}
}
// Test collision and report contacts between each colliding bodies in the world
void CollisionDetectionSystem::testCollision(CollisionCallback& callback) {
NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs);
// Compute the broad-phase collision detection
computeBroadPhase();
// Compute the middle-phase collision detection
computeMiddlePhase(narrowPhaseInput, true);
// Compute the narrow-phase collision detection and report contacts
computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback);
}
// Filter the overlapping pairs to keep only the pairs where a given body is involved
void CollisionDetectionSystem::filterOverlappingPairs(Entity bodyEntity, Array<uint64>& convexPairs, Array<uint64>& concavePairs) const {
// For each convex pairs
const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint32 i=0; i < nbConvexPairs; i++) {
if (mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider1) == bodyEntity ||
mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider2) == bodyEntity) {
convexPairs.add(mOverlappingPairs.mConvexPairs[i].pairID);
}
}
// For each concave pairs
const uint32 nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint32 i=0; i < nbConcavePairs; i++) {
if (mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider1) == bodyEntity ||
mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider2) == bodyEntity) {
concavePairs.add(mOverlappingPairs.mConcavePairs[i].pairID);
}
}
}
// Filter the overlapping pairs to keep only the pairs where two given bodies are involved
void CollisionDetectionSystem::filterOverlappingPairs(Entity body1Entity, Entity body2Entity, Array<uint64>& convexPairs, Array<uint64>& concavePairs) const {
// For each convex pair
const uint32 nbConvexPairs = mOverlappingPairs.mConvexPairs.size();
for (uint32 i=0; i < nbConvexPairs; i++) {
const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider1);
const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mConvexPairs[i].collider2);
if ((collider1Body == body1Entity && collider2Body == body2Entity) ||
(collider1Body == body2Entity && collider2Body == body1Entity)) {
convexPairs.add(mOverlappingPairs.mConvexPairs[i].pairID);
}
}
// For each concave pair
const uint nbConcavePairs = mOverlappingPairs.mConcavePairs.size();
for (uint i=0; i < nbConcavePairs; i++) {
const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider1);
const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mConcavePairs[i].collider2);
if ((collider1Body == body1Entity && collider2Body == body2Entity) ||
(collider1Body == body2Entity && collider2Body == body1Entity)) {
concavePairs.add(mOverlappingPairs.mConcavePairs[i].pairID);
}
}
}
// Return the world event listener
EventListener* CollisionDetectionSystem::getWorldEventListener() {
return mWorld->mEventListener;
}
// Return the world-space AABB of a given collider
const AABB CollisionDetectionSystem::getWorldAABB(const Collider* collider) const {
assert(collider->getBroadPhaseId() > -1);
return mBroadPhaseSystem.getFatAABB(collider->getBroadPhaseId());
}
| 93,895 | 26,029 |
#include "imposcpy.hpp"
#include <iostream>
int main(int argc, char** argv)
{
// map_impacts(5.2, 0.8, -0.63, 100, 0.5, 2, 4000, "impact-map.png", "errors.txt");
map_doa(5.2, 0.8, -0.63, 100, 4, 10, 10, 1000, "doa.png", "errors.txt");
return 0;
}
| 253 | 154 |
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <fstream>
#include <future>
#include <gtest/gtest.h>
#include <iostream>
#include <fstream>
#include "ability_handler.h"
#include "ability_info.h"
#include "ability_local_record.h"
#include "ability_start_setting.h"
#include "app_log_wrapper.h"
#include "common_event.h"
#include "common_event_manager.h"
#include "context_deal.h"
#include "distributed_kv_data_manager.h"
#include "form_db_info.h"
#include "form_data_mgr.h"
#include "form_item_info.h"
#include "form_storage_mgr.h"
#include "form_event.h"
#include "form_st_common_info.h"
#include "iservice_registry.h"
#include "nlohmann/json.hpp"
#include "self_starting_test_config_parser.h"
#include "system_ability_definition.h"
#include "system_test_form_util.h"
using OHOS::AAFwk::Want;
using namespace testing::ext;
using namespace std::chrono_literals;
using namespace OHOS::STtools;
namespace OHOS {
namespace AppExecFwk {
static SelfStartingTestInfo selfStarting;
static SelfStartingTestConfigParser selfStartingParser;
const int ADD_FORM_A_NUMBER = 10;
const int ADD_FORM_LENGTH = 20;
class FmsSelfStartingTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
static bool SubscribeEvent();
bool CompareA();
bool CompareB();
void SetUp();
void TearDown();
void StartAbilityKitTest(const std::string &abilityName, const std::string &bundleName);
void TerminateAbility(const std::string &eventName, const std::string &abilityName);
void ClearStorage();
bool CheckKvStore();
void TryTwice(const std::function<DistributedKv::Status()> &func);
class FormEventSubscriber : public CommonEventSubscriber {
public:
explicit FormEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {};
virtual void OnReceiveEvent(const CommonEventData &data) override;
~FormEventSubscriber() = default;
};
static sptr<AAFwk::IAbilityManager> abilityMs;
static FormEvent event;
static std::vector<std::string> eventList;
static std::shared_ptr<FormEventSubscriber> subscriber_;
};
std::vector<std::string> FmsSelfStartingTest::eventList = {
FORM_EVENT_ABILITY_ONACTIVED, FORM_EVENT_RECV_SELF_STARTING_TEST_0100, FORM_EVENT_RECV_SELF_STARTING_TEST_0200,
FORM_EVENT_RECV_SELF_STARTING_TEST_0300
};
FormEvent FmsSelfStartingTest::event = FormEvent();
sptr<AAFwk::IAbilityManager> FmsSelfStartingTest::abilityMs = nullptr;
std::shared_ptr<FmsSelfStartingTest::FormEventSubscriber> FmsSelfStartingTest::subscriber_ = nullptr;
void FmsSelfStartingTest::FormEventSubscriber::OnReceiveEvent(const CommonEventData &data)
{
GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction();
GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData();
GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode();
SystemTestFormUtil::Completed(event, data.GetWant().GetAction(), data.GetCode(), data.GetData());
}
void FmsSelfStartingTest::SetUpTestCase()
{
if (!SubscribeEvent()) {
GTEST_LOG_(INFO) << "SubscribeEvent error";
}
SelfStartingTestConfigParser selfStartingTcp;
selfStartingTcp.ParseForSelfStartingTest(FMS_TEST_CONFIG_FILE_PATH, selfStarting);
std::cout << "self starting test status : "
<< "addFormStatus : " << selfStarting.addFormStatus <<
", deleteFormStatus:" << selfStarting.deleteFormStatus <<
", compareStatus:" << selfStarting.compareStatus << std::endl;
if (selfStarting.addFormStatus) {
selfStartingParser.ClearStorage();
for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) {
Want want;
want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1);
want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME1);
want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME1);
want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE);
want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_FALSE);
want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME1, FORM_PROVIDER_ABILITY_NAME1);
APP_LOGI("%{public}s, formCount: %{public}d", __func__, iCount + 1);
want.SetParam(Constants::PARAM_FORM_ADD_COUNT, iCount + 1);
// Set Want info end
int errorCode = STtools::SystemTestFormUtil::DistributedDataAddForm(want);
if (errorCode != 0) {
GTEST_LOG_(INFO) << "add form failed, iCount:" << iCount << ", errorCode:" << errorCode;
}
sleep(1);
}
}
if (selfStarting.addFormStatus) {
for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) {
Want want;
want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, FORM_DIMENSION_1);
want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME2);
want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME2);
want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE);
want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, FORM_TEMP_FORM_FLAG_TRUE);
want.SetElementName(FORM_TEST_DEVICEID, FORM_PROVIDER_BUNDLE_NAME2, FORM_PROVIDER_ABILITY_NAME2);
APP_LOGI("%{public}s, formCount: %{public}d", __func__, iCount + 1);
want.SetParam(Constants::PARAM_FORM_ADD_COUNT, iCount + 1);
// Set Want info end
int errorCode = STtools::SystemTestFormUtil::DistributedDataAddForm(want);
if (errorCode != 0) {
GTEST_LOG_(INFO) << "add form failed, iCount:" << iCount << ", errorCode:" << errorCode;
}
sleep(1);
}
}
}
bool FmsSelfStartingTest::CompareA()
{
bool compare = true;
for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) {
int64_t formId = iCount + 1;
InnerFormInfo innerFormInfo;
selfStartingParser.GetStorageFormInfoById(std::to_string(formId), innerFormInfo);
if (innerFormInfo.GetFormId() != formId) {
compare = false;
break;
}
if (innerFormInfo.GetModuleName() != PARAM_PROVIDER_MODULE_NAME1) {
compare = false;
break;
}
if (innerFormInfo.GetBundleName() != FORM_PROVIDER_BUNDLE_NAME1) {
compare = false;
break;
}
if (innerFormInfo.GetAbilityName() != FORM_PROVIDER_ABILITY_NAME1) {
compare = false;
break;
}
if (innerFormInfo.GetFormName() != PARAM_FORM_NAME1) {
compare = false;
break;
}
}
return compare;
}
bool FmsSelfStartingTest::CompareB()
{
bool compare = true;
for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) {
int64_t formId = iCount + 1;
InnerFormInfo innerFormInfo;
selfStartingParser.GetStorageFormInfoById(std::to_string(formId), innerFormInfo);
if (innerFormInfo.GetFormId() != formId) {
compare = false;
break;
}
if (innerFormInfo.GetModuleName() != PARAM_PROVIDER_MODULE_NAME2) {
compare = false;
break;
}
if (innerFormInfo.GetBundleName() != FORM_PROVIDER_BUNDLE_NAME2) {
compare = false;
break;
}
if (innerFormInfo.GetAbilityName() != FORM_PROVIDER_ABILITY_NAME2) {
compare = false;
break;
}
if (innerFormInfo.GetFormName() != PARAM_FORM_NAME2) {
compare = false;
break;
}
}
return compare;
}
void FmsSelfStartingTest::TearDownTestCase()
{
GTEST_LOG_(INFO) << "UnSubscribeCommonEvent calld";
CommonEventManager::UnSubscribeCommonEvent(subscriber_);
if (selfStarting.deleteFormStatus) {
for (int iCount = 0; iCount < ADD_FORM_A_NUMBER; iCount++) {
int64_t formId = iCount + 1;
int errorCode = STtools::SystemTestFormUtil::DistributedDataDeleteForm(std::to_string(formId));
if (errorCode != 0) {
GTEST_LOG_(INFO) << "delete form failed, iCount:" << iCount << ", errorCode:" << errorCode;
}
}
}
if (selfStarting.deleteFormStatus) {
for (int iCount = ADD_FORM_A_NUMBER; iCount < ADD_FORM_LENGTH; iCount++) {
int64_t formId = iCount + 1;
int errorCode = STtools::SystemTestFormUtil::DistributedDataDeleteForm(std::to_string(formId));
if (errorCode != 0) {
GTEST_LOG_(INFO) << "delete form failed, iCount:" << ", errorCode:" << errorCode;
}
}
selfStartingParser.ClearStorage();
}
}
void FmsSelfStartingTest::SetUp()
{
}
void FmsSelfStartingTest::TearDown()
{
GTEST_LOG_(INFO) << "CleanMsg calld";
SystemTestFormUtil::CleanMsg(event);
}
bool FmsSelfStartingTest::SubscribeEvent()
{
GTEST_LOG_(INFO) << "SubscribeEvent calld";
MatchingSkills matchingSkills;
for (const auto &e : eventList) {
matchingSkills.AddEvent(e);
}
CommonEventSubscribeInfo subscribeInfo(matchingSkills);
subscribeInfo.SetPriority(1);
subscriber_ = std::make_shared<FormEventSubscriber>(subscribeInfo);
return CommonEventManager::SubscribeCommonEvent(subscriber_);
}
/**
* @tc.number: FMS_Start_0300_03
* @tc.name: Form number 512
* @tc.desc:
*/
HWTEST_F(FmsSelfStartingTest, FMS_Start_0300_03, Function | MediumTest | Level1)
{
std::cout << "START FMS_Start_0300_03" << std::endl;
if (selfStarting.compareStatus) {
std::ifstream opbefore("/data/formmgr/beforeKill.txt");
std::ifstream opafter("/data/formmgr/afterKill.txt");
std::string beforeKill;
std::string afterKill;
while (!opbefore.eof()) {
beforeKill += opbefore.get();
}
while (!opafter.eof()) {
afterKill += opafter.get();
}
opbefore.close();
opafter.close();
EXPECT_TRUE(beforeKill != afterKill);
EXPECT_TRUE(CompareA());
EXPECT_TRUE(CompareB());
}
std::cout << "END FMS_Start_0300_03" << std::endl;
}
} // namespace AppExecFwk
} // namespace OHOS | 10,956 | 3,641 |
#include "socketclosedexception.h"
const char* SocketClosedException::what() const throw() {
return errormsg.c_str();
}
| 124 | 41 |
#include "DXUT.h"
#include "DXUTCamera.h"
#include "SDKmisc.h"
#include "LensflareManager.h"
extern float g_fAspectRatio;
extern ID3D11Device* g_pDevice;
extern CFirstPersonCamera g_Camera;
HRESULT CompileShader(PWCHAR strPath, D3D10_SHADER_MACRO* pMacros, char* strEntryPoint, char* strProfile, DWORD dwShaderFlags, ID3DBlob** ppVertexShaderBuffer);
struct CB_LENSFLARE_VS
{
D3DXVECTOR4 Position;
D3DXVECTOR4 ScaleRotate;
D3DXVECTOR4 Color;
};
CLensflareManager::CLensflareManager() : m_pPredicate(NULL), m_pOcclusionQuery(NULL), m_pNoDepthState(NULL), m_pAddativeBlendState(NULL), m_pNoColorBlendState(NULL),
m_pLensflareCB(NULL), m_pLensflareVS(NULL), m_pLensflarePS(NULL), m_pCoronaTexView(NULL), m_pFlareTexView(NULL),
m_fSunVisibility(0.0f), m_bQuerySunVisibility(true), m_fCoronaRotation(0.0f)
{
}
CLensflareManager::~CLensflareManager()
{
}
HRESULT CLensflareManager::Init()
{
HRESULT hr;
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION_PREDICATE;
queryDesc.MiscFlags = 0;
V_RETURN( g_pDevice->CreatePredicate(&queryDesc, &m_pPredicate) );
DXUT_SetDebugName( m_pPredicate, "Lens Flare - Predicate");
queryDesc.Query = D3D11_QUERY_OCCLUSION;
V_RETURN( g_pDevice->CreateQuery(&queryDesc, &m_pOcclusionQuery) );
DXUT_SetDebugName( m_pOcclusionQuery, "Lens Flare - Occlusion Query");
m_fSunVisibility = 0.0f;
m_bQuerySunVisibility = true;
// Create constant buffers
D3D11_BUFFER_DESC cbDesc;
ZeroMemory( &cbDesc, sizeof(cbDesc) );
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.ByteWidth = CLensflareManager::m_TotalFlares * sizeof( CB_LENSFLARE_VS );
V_RETURN( g_pDevice->CreateBuffer( &cbDesc, NULL, &m_pLensflareCB ) );
DXUT_SetDebugName( m_pLensflareCB, "Lensflare CB" );
// Compile the shaders
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Lensflare.hlsl" ) );
ID3DBlob* pShaderBuffer = NULL;
V_RETURN( CompileShader(str, NULL, "LensflareVS", "vs_5_0", dwShaderFlags, &pShaderBuffer) );
V_RETURN( g_pDevice->CreateVertexShader( pShaderBuffer->GetBufferPointer(),
pShaderBuffer->GetBufferSize(), NULL, &m_pLensflareVS ) );
DXUT_SetDebugName( m_pLensflareVS, "LensflareVS" );
SAFE_RELEASE( pShaderBuffer );
V_RETURN( CompileShader(str, NULL, "LensflarePS", "ps_5_0", dwShaderFlags, &pShaderBuffer) );
V_RETURN( g_pDevice->CreatePixelShader( pShaderBuffer->GetBufferPointer(),
pShaderBuffer->GetBufferSize(), NULL, &m_pLensflarePS ) );
DXUT_SetDebugName( m_pLensflarePS, "LensfalrePS" );
SAFE_RELEASE( pShaderBuffer );
// Load the corona texture
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"..\\Media\\Corona.dds" ) );
V_RETURN( D3DX11CreateShaderResourceViewFromFile( g_pDevice, str, NULL, NULL, &m_pCoronaTexView, NULL ) );
// Load the flares texture
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"..\\Media\\Flare.dds" ) );
V_RETURN( D3DX11CreateShaderResourceViewFromFile( g_pDevice, str, NULL, NULL, &m_pFlareTexView, NULL ) );
D3D11_DEPTH_STENCIL_DESC descDepth;
descDepth.DepthEnable = FALSE;
descDepth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
descDepth.DepthFunc = D3D11_COMPARISON_LESS;
descDepth.StencilEnable = FALSE;
descDepth.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
descDepth.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
const D3D11_DEPTH_STENCILOP_DESC defaultStencilOp = { D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_ALWAYS };
descDepth.FrontFace = defaultStencilOp;
descDepth.BackFace = defaultStencilOp;
V_RETURN( g_pDevice->CreateDepthStencilState(&descDepth, &m_pNoDepthState) );
DXUT_SetDebugName( m_pNoDepthState, "Lens Flare - No Depth DS" );
D3D11_BLEND_DESC descBlend;
descBlend.AlphaToCoverageEnable = FALSE;
descBlend.IndependentBlendEnable = FALSE;
D3D11_RENDER_TARGET_BLEND_DESC TRBlenddDesc =
{
TRUE,
D3D11_BLEND_ONE, D3D11_BLEND_ONE, D3D11_BLEND_OP_ADD,
D3D11_BLEND_ONE, D3D11_BLEND_ONE, D3D11_BLEND_OP_ADD,
D3D11_COLOR_WRITE_ENABLE_ALL,
};
for (UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
descBlend.RenderTarget[ i ] = TRBlenddDesc;
V_RETURN( g_pDevice->CreateBlendState(&descBlend, &m_pAddativeBlendState) );
DXUT_SetDebugName( m_pAddativeBlendState, "Lenst Flare - Addative Blending BS" );
TRBlenddDesc.BlendEnable = FALSE;
TRBlenddDesc.RenderTargetWriteMask = 0;
for (UINT i = 0; i < D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
descBlend.RenderTarget[ i ] = TRBlenddDesc;
V_RETURN( g_pDevice->CreateBlendState(&descBlend, &m_pNoColorBlendState) );
DXUT_SetDebugName( m_pNoColorBlendState, "Lens Flare - No Color BS" );
m_arrFlares[0].fOffset = 0.0f;
m_arrFlares[0].fScale = 0.028f;
m_arrFlares[0].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f);
m_arrFlares[1].fOffset = 0.0f;
m_arrFlares[1].fScale = 0.028f;
m_arrFlares[1].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f);
m_arrFlares[2].fOffset = 0.0f;
m_arrFlares[2].fScale = 0.028f;
m_arrFlares[2].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f);
m_arrFlares[3].fOffset = 0.0f;
m_arrFlares[3].fScale = 0.028f;
m_arrFlares[3].Color = D3DXVECTOR4(0.2f, 0.18f, 0.15f, 0.25f);
m_arrFlares[4].fOffset = 0.5f;
m_arrFlares[4].fScale = 0.075f;
m_arrFlares[4].Color = D3DXVECTOR4(0.2f, 0.3f, 0.55f, 1.0f);
m_arrFlares[5].fOffset = 1.0f;
m_arrFlares[5].fScale = 0.054f;
m_arrFlares[5].Color = D3DXVECTOR4(0.024f, 0.2f, 0.52f, 1.0f);
m_arrFlares[6].fOffset = 1.35f;
m_arrFlares[6].fScale = 0.095f;
m_arrFlares[6].Color = D3DXVECTOR4(0.032f, 0.1f, 0.5f, 1.0f);
m_arrFlares[7].fOffset = 0.9f;
m_arrFlares[7].fScale = 0.065f;
m_arrFlares[7].Color = D3DXVECTOR4(0.13f, 0.14f, 0.58f, 1.0f);
m_arrFlares[8].fOffset = 1.55f;
m_arrFlares[8].fScale = 0.038f;
m_arrFlares[8].Color = D3DXVECTOR4(0.16f, 0.21, 0.44, 1.0f);
m_arrFlares[9].fOffset = 0.25f;
m_arrFlares[9].fScale = 0.1f;
m_arrFlares[9].Color = D3DXVECTOR4(0.23f, 0.21, 0.44, 0.85f);
return hr;
}
void CLensflareManager::Deinit()
{
SAFE_RELEASE( m_pPredicate );
SAFE_RELEASE( m_pOcclusionQuery );
SAFE_RELEASE( m_pNoDepthState );
SAFE_RELEASE( m_pAddativeBlendState );
SAFE_RELEASE( m_pNoColorBlendState );
SAFE_RELEASE( m_pLensflareCB );
SAFE_RELEASE( m_pLensflareVS );
SAFE_RELEASE( m_pLensflarePS );
SAFE_RELEASE( m_pCoronaTexView );
SAFE_RELEASE( m_pFlareTexView );
}
void CLensflareManager::Update(const D3DXVECTOR3& sunWorldPos, float fElapsedTime)
{
D3DXMATRIX mView = *g_Camera.GetViewMatrix();
D3DXMATRIX mProj = *g_Camera.GetProjMatrix();
D3DXMATRIX mViewProjection = mView * mProj;
for(int i=0; i < m_TotalLights; i++)
{
m_SunWorldPos = sunWorldPos;
D3DXVECTOR3 ProjPos;
D3DXVec3TransformCoord (&ProjPos, &m_SunWorldPos, &mViewProjection);
m_SunPos2D.x = ProjPos.x;
m_SunPos2D.y = ProjPos.y;
}
const float fCoronaRotationSpeed = 0.01f * D3DX_PI;
m_fCoronaRotation += fElapsedTime * fCoronaRotationSpeed;
}
void CLensflareManager::Render(ID3D11DeviceContext* pd3dImmediateContext)
{
HRESULT hr;
pd3dImmediateContext->SetPredication(m_pPredicate, FALSE);
m_bQuerySunVisibility = false;
UINT64 sunVisibility;
if(pd3dImmediateContext->GetData(m_pOcclusionQuery, (void*)&sunVisibility, sizeof(sunVisibility), 0) == S_OK)
{
m_fSunVisibility = (float)sunVisibility / 700.0f;
m_bQuerySunVisibility = true;
}
ID3D11DepthStencilState* pPrevDepthState;
pd3dImmediateContext->OMGetDepthStencilState(&pPrevDepthState, NULL);
pd3dImmediateContext->OMSetDepthStencilState(m_pNoDepthState, 0);
ID3D11BlendState* pPrevBlendState;
FLOAT prevBlendFactor[ 4 ];
UINT prevSampleMask;
pd3dImmediateContext->OMGetBlendState(&pPrevBlendState, prevBlendFactor, &prevSampleMask);
pd3dImmediateContext->OMSetBlendState(m_pAddativeBlendState, prevBlendFactor, prevSampleMask);
pd3dImmediateContext->IASetInputLayout( NULL );
pd3dImmediateContext->IASetVertexBuffers(0, 0, NULL, NULL, NULL);
pd3dImmediateContext->VSSetShader( m_pLensflareVS, NULL, 0 );
pd3dImmediateContext->PSSetShader( m_pLensflarePS, NULL, 0 );
// Fill the corona values
D3D11_MAPPED_SUBRESOURCE MappedResource;
V( pd3dImmediateContext->Map( m_pLensflareCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_LENSFLARE_VS* pCB = ( CB_LENSFLARE_VS* )MappedResource.pData;
for(int j=0; j < m_TotalCoronaFlares; j++)
{
pCB[j].Position = D3DXVECTOR4(m_SunPos2D.x, m_SunPos2D.y, 0.0f, 0.0f);
float fSin = sinf(m_fCoronaRotation + static_cast<float>(j) * D3DX_PI / 4.0f + D3DX_PI / 5.0f);
float fCos = cosf(m_fCoronaRotation + static_cast<float>(j) * D3DX_PI / 4.0f + D3DX_PI / 5.0f);
const float coronaWidthScale = 14.0f;
float fScaleX = m_arrFlares[j].fScale * coronaWidthScale;
float fScaleY = m_arrFlares[j].fScale;
pCB[j].ScaleRotate = D3DXVECTOR4(fScaleX * fCos, fScaleY * -fSin, fScaleX * fSin * g_fAspectRatio, fScaleY * fCos * g_fAspectRatio);
pCB[j].Color = m_arrFlares[j].Color * m_fSunVisibility;
}
pd3dImmediateContext->Unmap( m_pLensflareCB, 0 );
// Render the corona
pd3dImmediateContext->PSSetShaderResources( 0, 1, &m_pCoronaTexView );
pd3dImmediateContext->VSSetConstantBuffers( 0, 1, &m_pLensflareCB );
pd3dImmediateContext->Draw(6 * m_TotalCoronaFlares, 0);
// Fill the flare values
D3DXVECTOR2 dirFlares = D3DXVECTOR2(0.0f, 0.0f) - m_SunPos2D;
float fLength = D3DXVec2LengthSq(&dirFlares);
dirFlares = dirFlares * (1.0f / fLength);
V( pd3dImmediateContext->Map( m_pLensflareCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
pCB = ( CB_LENSFLARE_VS* )MappedResource.pData;
for(int j=3; j < m_TotalFlares; j++)
{
float fOffset = m_arrFlares[j].fOffset * fLength;
D3DXVECTOR2 flarePos2D = fOffset * dirFlares + m_SunPos2D;
pCB[j-3].Position = D3DXVECTOR4(flarePos2D.x, flarePos2D.y, 0.0f, 0.0f);
float fScale = m_arrFlares[j].fScale;
pCB[j-3].ScaleRotate = D3DXVECTOR4(fScale, 0.0f, 0.0f, fScale * g_fAspectRatio);
pCB[j-3].Color = m_arrFlares[j].Color * m_fSunVisibility;
}
pd3dImmediateContext->Unmap( m_pLensflareCB, 0 );
// Render the flares
pd3dImmediateContext->PSSetShaderResources( 0, 1, &m_pFlareTexView );
pd3dImmediateContext->VSSetConstantBuffers( 0, 1, &m_pLensflareCB );
pd3dImmediateContext->Draw(6 * (m_TotalFlares - m_TotalCoronaFlares), 0);
// Restore the blend state
pd3dImmediateContext->OMSetDepthStencilState(pPrevDepthState, 0);
SAFE_RELEASE( pPrevDepthState );
pd3dImmediateContext->OMSetBlendState(pPrevBlendState, prevBlendFactor, prevSampleMask);
SAFE_RELEASE( pPrevBlendState );
pd3dImmediateContext->SetPredication(NULL, FALSE);
}
void CLensflareManager::BeginSunVisibility(ID3D11DeviceContext* pd3dImmediateContext)
{
pd3dImmediateContext->OMGetBlendState(&m_pPrevBlendState, m_prevBlendFactor, &m_prevSampleMask);
pd3dImmediateContext->OMSetBlendState(m_pNoColorBlendState, m_prevBlendFactor, m_prevSampleMask);
pd3dImmediateContext->Begin(m_pPredicate);
if(m_bQuerySunVisibility)
{
pd3dImmediateContext->Begin(m_pOcclusionQuery);
}
}
void CLensflareManager::EndSunVisibility(ID3D11DeviceContext* pd3dImmediateContext)
{
pd3dImmediateContext->End(m_pPredicate);
if(m_bQuerySunVisibility)
{
pd3dImmediateContext->End(m_pOcclusionQuery);
}
// Restore the previous blend state
pd3dImmediateContext->OMSetBlendState(m_pPrevBlendState, m_prevBlendFactor, m_prevSampleMask);
SAFE_RELEASE(m_pPrevBlendState);
}
| 11,937 | 5,672 |
#include <iostream>
#include <do>
int main()
{
// print all `unsigned char` values
do (unsigned char c = 0) {
std::cout << +c << std::endl;
} while( ++c );
}
| 164 | 66 |
๏ปฟ#include "stdafx.h"
#include "BirdsEyeTransform.h"
#include "ADTF3_OpenCV_helper.h"
#include <opencv/cv.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/cudaimgproc.hpp>
/// This defines a data triggered filter and exposes it via a plugin class factory.
/// The Triggerfunction cSimpleDataStatistics will be embedded to the Filter
/// and called repeatedly (last parameter of this macro)!
ADTF_TRIGGER_FUNCTION_FILTER_PLUGIN(CID_CARIOSITY_DATA_TRIGGERED_FILTER,
"Birds Eye Transform",
fcBirdsEyeTransform,
adtf::filter::pin_trigger({ "in" }));
fcBirdsEyeTransform::fcBirdsEyeTransform() {
//Register Properties
RegisterPropertyVariable("ROIOffsetX [%]", m_ROIOffsetX);
RegisterPropertyVariable("ROIOffsetY [%]", m_ROIOffsetY);
RegisterPropertyVariable("ROIWidth [%]", m_ROIWidth);
RegisterPropertyVariable("ROIHeight [%]", m_ROIHeight);
RegisterPropertyVariable("Output Height [Pixel]", m_OutputHeight);
RegisterPropertyVariable("side inset at top [%]", m_topSideInset);
RegisterPropertyVariable("side inset at bottom [%]", m_bottomSideInset);
RegisterPropertyVariable("Show ROI, no transform", m_showROIDebug);
//create and set inital input format type
m_InPinVideoFormat.m_strFormatName = ADTF_IMAGE_FORMAT(RGB_24);
adtf::ucom::object_ptr<IStreamType> pTypeInput = adtf::ucom::make_object_ptr<cStreamType>(stream_meta_type_image());
set_stream_type_image_format(*pTypeInput, m_InPinVideoFormat);
//Register input pin
Register(m_oReaderVideo, "in", pTypeInput);
//Register output pins
adtf::ucom::object_ptr<IStreamType> pTypeOutput = adtf::ucom::make_object_ptr<cStreamType>(stream_meta_type_image());
set_stream_type_image_format(*pTypeOutput, m_OutPinVideoFormat);
Register(m_oWriterVideo, "out", pTypeOutput);
//register callback for type changes
m_oReaderVideo.SetAcceptTypeCallback([this](const adtf::ucom::ant::iobject_ptr<const adtf::streaming::ant::IStreamType>& pType) -> tResult
{
return ChangeType(m_oReaderVideo, *pType.Get());
});
}
tResult fcBirdsEyeTransform::Configure()
{
//get clock object
RETURN_IF_FAILED(_runtime->GetObject(m_pClock));
RETURN_NOERROR;
}
tResult fcBirdsEyeTransform::ChangeType(adtf::streaming::cDynamicSampleReader& inputPin, const adtf::streaming::ant::IStreamType& oType) {
if (oType == adtf::streaming::stream_meta_type_image())
{
adtf::ucom::object_ptr<const adtf::streaming::IStreamType> pTypeInput;
// get pType from input reader
inputPin >> pTypeInput;
adtf::streaming::get_stream_type_image_format(m_InPinVideoFormat, *pTypeInput);
//set also output format
adtf::streaming::get_stream_type_image_format(m_OutPinVideoFormat, *pTypeInput);
// and set pType also to samplewriter
m_oWriterVideo << pTypeInput;
}
else
{
RETURN_ERROR(ERR_INVALID_TYPE);
}
RETURN_NOERROR;
}
tResult fcBirdsEyeTransform::Process(tTimeStamp tmTimeOfTrigger) {
object_ptr<const ISample> pReadSample;
if (IS_OK(m_oReaderVideo.GetNextSample(pReadSample))) {
object_ptr_shared_locked<const ISampleBuffer> pReadBuffer;
Mat outputImage;
cv::cuda::GpuMat dst, src;
//lock read buffer
if (IS_OK(pReadSample->Lock(pReadBuffer))) {
RETURN_IF_FAILED(checkRoi());
Size inputSize = cv::Size(m_InPinVideoFormat.m_ui32Width, m_InPinVideoFormat.m_ui32Height);
//create a opencv matrix from the media sample buffer
Mat inputImage(inputSize, CV_8UC3, (uchar*)pReadBuffer->GetPtr());
inputImage = inputImage.clone();
Rect roi(
inputSize.width * m_ROIOffsetX,
inputSize.height * m_ROIOffsetY,
inputSize.width * m_ROIWidth,
inputSize.height * m_ROIHeight
);
tInt64 aspectRatio = roi.width / roi.height;
Size outputSize = cv::Size(m_OutputHeight * aspectRatio , m_OutputHeight);
Point2f src_vertices[4];
src_vertices[0] = Point2f(roi.x, roi.y);
src_vertices[1] = Point2f(roi.x + roi.width, roi.y);
src_vertices[2] = Point2f(roi.x + roi.width, roi.y + roi.height);
src_vertices[3] = Point2f(roi.x, roi.y + roi.height);
Point2f dst_vertices[4];
dst_vertices[0] = Point2f(roi.x + roi.width * m_topSideInset, roi.y); // Point2f(inputSize.width * m_topSideInset, 0);
dst_vertices[1] = Point2f(roi.x + roi.width * (1.0f - m_topSideInset), roi.y); // Point2f(inputSize.width * (1.0f - m_topSideInset), 0);
dst_vertices[2] = Point2f(roi.x + (1.0f - m_bottomSideInset) * roi.width, roi.y + roi.height); // Point2f(inputSize.width * (1.0f - m_bottomSideInset), inputSize.height);
dst_vertices[3] = Point2f(roi.x + m_bottomSideInset * roi.width, roi.y + roi.height); // Point2f(inputSize.width * m_bottomSideInset, inputSize.height);
Mat M = getPerspectiveTransform(src_vertices, dst_vertices);
if(m_showROIDebug) {
outputImage = inputImage.clone();
line(outputImage, src_vertices[0], src_vertices[1], Scalar(0,255,255), 2);
line(outputImage, src_vertices[1], src_vertices[2], Scalar(0,255,255), 2);
line(outputImage, src_vertices[2], src_vertices[3], Scalar(0,255,255), 2);
line(outputImage, src_vertices[3], src_vertices[0], Scalar(0,255,255), 2);
line(outputImage, dst_vertices[0], dst_vertices[1], Scalar(255,255,255), 2);
line(outputImage, dst_vertices[1], dst_vertices[2], Scalar(255,255,255), 2);
line(outputImage, dst_vertices[2], dst_vertices[3], Scalar(255,255,255), 2);
line(outputImage, dst_vertices[3], dst_vertices[0], Scalar(255,255,255), 2);
resize(outputImage, outputImage, outputSize);
} else {
src.upload(inputImage);
cv::cuda::warpPerspective(src, dst, M, inputSize, INTER_LINEAR, BORDER_CONSTANT);
// cv::cuda::resize(dst, dst, outputSize);
dst.download(outputImage);
outputImage = outputImage(roi).clone();
}
pReadBuffer->Unlock();
}
//copy to outputimage
//Write processed Image to Output Pin
if (!outputImage.empty())
{
//update output format if matrix size does not fit to
if (outputImage.total() * outputImage.elemSize() != m_OutPinVideoFormat.m_szMaxByteSize)
{
setTypeFromMat(m_oWriterVideo, outputImage);
}
// write to pin
writeMatToPin(m_oWriterVideo, outputImage, m_pClock->GetStreamTime());
}
}
RETURN_NOERROR;
}
tResult fcBirdsEyeTransform::checkRoi(void)
{
// if width or heigt are not set ignore the roi
if (static_cast<tFloat32>(m_ROIWidth) == 0 || static_cast<tFloat32>(m_ROIHeight) == 0)
{
LOG_ERROR("ROI width or height is not set!");
RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI width or height is not set!");
}
//check if we are within the boundaries of the image
if ((static_cast<tFloat32>(m_ROIOffsetX) + static_cast<tFloat32>(m_ROIWidth)) > m_InPinVideoFormat.m_ui32Width)
{
LOG_ERROR("ROI is outside of image");
RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI is outside of image");
}
if ((static_cast<tFloat32>(m_ROIOffsetY) + static_cast<tFloat32>(m_ROIHeight)) > m_InPinVideoFormat.m_ui32Height)
{
LOG_ERROR("ROI is outside of image");
RETURN_ERROR_DESC(ERR_INVALID_ARG, "ROI is outside of image");
}
//create the rectangle
m_LaneRoi = cv::Rect2f(static_cast<tFloat32>(m_ROIOffsetX), static_cast<tFloat32>(m_ROIOffsetY), static_cast<tFloat32>(m_ROIWidth), static_cast<tFloat32>(m_ROIHeight));
RETURN_NOERROR;
} | 8,282 | 2,882 |
#pragma once
#include <limitless/fx/modules/module.hpp>
namespace Limitless::fx {
template<typename Particle>
class CustomMaterial : public Module<Particle> {
private:
std::array<std::unique_ptr<Distribution<float>>, 4> properties;
public:
CustomMaterial(std::unique_ptr<Distribution<float>> prop1,
std::unique_ptr<Distribution<float>> prop2,
std::unique_ptr<Distribution<float>> prop3,
std::unique_ptr<Distribution<float>> prop4 ) noexcept
: Module<Particle>(ModuleType::CustomMaterial)
, properties {std::move(prop1), std::move(prop2), std::move(prop3), std::move(prop4)} {}
~CustomMaterial() override = default;
CustomMaterial(const CustomMaterial& module)
: Module<Particle>(module.type){
for (size_t i = 0; i < module.properties.size(); ++i) {
if (module.properties[i]) {
properties[i] = std::unique_ptr<Distribution<float>>(module.properties[i]->clone());
}
}
}
auto& getProperties() noexcept { return properties; }
const auto& getProperties() const noexcept { return properties; }
void initialize([[maybe_unused]] AbstractEmitter& emitter, Particle& particle, [[maybe_unused]] size_t index) noexcept override {
for (size_t i = 0; i < properties.size(); ++i) {
if (properties[i]) {
particle.properties[i] = properties[i]->get();
}
}
}
[[nodiscard]] CustomMaterial* clone() const override {
return new CustomMaterial(*this);
}
};
} | 1,720 | 469 |
/**
* Copyright 2020 Kaloian Manassiev
*
* 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 "common/base.h"
#include "common/file_descriptor.h"
#include <boost/log/trivial.hpp>
#include <poll.h>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#include "common/exception.h"
namespace ruralpi {
FileDescriptor::FileDescriptor(const std::string &desc, int fd) : _desc(desc), _fd(fd) {
SYSCALL_MSG(_fd, boost::format("Could not open file descriptor (%d): %s") % _fd % _desc);
}
FileDescriptor::FileDescriptor(const FileDescriptor &) = default;
FileDescriptor::FileDescriptor(FileDescriptor &&other) { *this = std::move(other); }
FileDescriptor &FileDescriptor::operator=(FileDescriptor &&other) {
_desc = std::move(other._desc);
_fd = other._fd;
other._fd = -1;
return *this;
}
void FileDescriptor::makeNonBlocking() {
int flags = SYSCALL(::fcntl(_fd, F_GETFL));
SYSCALL(::fcntl(_fd, F_SETFL, flags | O_NONBLOCK));
}
int FileDescriptor::availableToRead() {
int nAvailable;
SYSCALL(::ioctl(_fd, FIONREAD, &nAvailable));
return nAvailable;
}
int FileDescriptor::readNonBlocking(void *buf, size_t nbytes) {
int nRead = ::read(_fd, buf, nbytes);
if (nRead < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))
return nRead;
SYSCALL_MSG(nRead, boost::format("Failed to read from file descriptor (%d): %s") % _fd % _desc);
return nRead;
}
int FileDescriptor::read(void *buf, size_t nbytes) {
while (true) {
int nRead = readNonBlocking(buf, nbytes);
if (nRead > 0) {
return nRead;
} else if (nRead == 0) {
throw SystemException(
boost::format("Failed to read from closed file descriptor (%d): %s") % _fd % _desc);
} else if (nRead < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
poll(Milliseconds(-1), POLLIN);
}
}
}
int FileDescriptor::writeNonBlocking(void const *buf, size_t nbytes) {
int nWritten = ::write(_fd, buf, nbytes);
if (nWritten < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))
return nWritten;
SYSCALL_MSG(nWritten,
boost::format("Failed to write to file descriptor (%d): %s") % _fd % _desc);
return nWritten;
}
int FileDescriptor::write(void const *buf, size_t nbytes) {
while (true) {
int nWritten = writeNonBlocking(buf, nbytes);
if (nWritten > 0) {
return nWritten;
} else if (nWritten == 0) {
throw SystemException(
boost::format("Failed to write to closed file descriptor (%d): %s") % _fd % _desc);
} else if (nWritten < 0 && (errno == EWOULDBLOCK || errno == EAGAIN)) {
poll(Milliseconds(-1), POLLOUT);
}
}
}
int FileDescriptor::poll(Milliseconds timeout, short events) {
pollfd fd;
fd.fd = _fd;
fd.events = events;
return SYSCALL(::poll(&fd, 1, timeout.count()));
}
std::string FileDescriptor::toString() const {
std::stringstream ss;
ss << _desc << " (fd " << _fd << ')';
return ss.str();
}
ScopedFileDescriptor::ScopedFileDescriptor(const std::string &desc, int fd)
: FileDescriptor(desc, fd) {
BOOST_LOG_TRIVIAL(debug) << boost::format("File descriptor created (%d): %s") % _fd % _desc;
}
ScopedFileDescriptor::ScopedFileDescriptor(ScopedFileDescriptor &&other) = default;
ScopedFileDescriptor &ScopedFileDescriptor::operator=(ScopedFileDescriptor &&) = default;
ScopedFileDescriptor::~ScopedFileDescriptor() { close(); }
void ScopedFileDescriptor::close() {
if (_fd > 0) {
BOOST_LOG_TRIVIAL(debug) << boost::format("File descriptor closed (%d): %s") % _fd % _desc;
if (::close(_fd) < 0) {
BOOST_LOG_TRIVIAL(debug)
<< (boost::format("File descriptor close failed (%d): %s") % _fd % _desc) << ": "
<< SystemException::getLastError();
}
_fd = -1;
return;
} else if (_fd == -1) {
return;
}
RASSERT_MSG(false, boost::format("Illegal file descriptor (%d): %s") % _fd % _desc.c_str());
}
} // namespace ruralpi
| 5,139 | 1,746 |
/*
* cvc_context.cpp
*
* Created on: Nov 7, 2014
* Author: Julian Kranz
*/
#include <summy/analysis/ismt/cvc_context.h>
#include <cvc4/cvc4.h>
#include <string>
#include <sstream>
using namespace std;
using namespace CVC4;
analysis::cvc_context::cvc_context(bool unsat_cores) : smtEngine(&manager) {
smtEngine.setOption("produce-models", SExpr("true"));
smtEngine.setOption("incremental", SExpr("true"));
if(unsat_cores) {
smtEngine.setOption("produce-unsat-cores", SExpr("true"));
// smtEngine.setOption("tear-down-incremental", SExpr("true"));
}
mem_type = manager.mkArrayType(manager.mkBitVectorType(61), manager.mkBitVectorType(64));
}
CVC4::Expr analysis::cvc_context::var(std::string name) {
auto i_it = var_map.find(name);
if(i_it != var_map.end()) return i_it->second;
else {
Expr i_exp = manager.mkVar(name, manager.mkBitVectorType(64));
var_map[name] = i_exp;
return i_exp;
}
}
CVC4::Expr analysis::cvc_context::memory(memory_map_t &m, string base, size_t rev) {
auto rev_it = m.find(rev);
if(rev_it != m.end()) return rev_it->second;
else {
stringstream name;
name << base << rev;
Expr mem = manager.mkVar(name.str(), mem_type);
m[rev] = mem;
return mem;
}
}
//CVC4::Expr analysis::cvc_context::var_def(std::string name) {
// return var(name + "_def");
//}
CVC4::Expr analysis::cvc_context::memory(size_t rev) {
return memory(mem_map, "m_", rev);
}
CVC4::Expr analysis::cvc_context::memory_def(size_t rev) {
return memory(mem_def_map, "m_def_", rev);
}
| 1,554 | 616 |
#ifndef _OP_MASKED_MULTI_HEAD_ATTENTION_HPP_
#define _OP_MASKED_MULTI_HEAD_ATTENTION_HPP_
#include "op/common.hpp"
#include "op/mmanager.hpp"
#include "op/meta_desc.hpp"
// #include "op/allocator.hpp"
namespace eet{
namespace op{
class MaskedMultiHeadAttention : public OpBase{
public:
MaskedMultiHeadAttention(MetaDesc desc,
const torch::Tensor& QKV_weights,
const torch::Tensor& Q_bias,
const torch::Tensor& K_bias,
const torch::Tensor& V_bias,
const torch::Tensor& Output_weights,
const torch::Tensor& Output_bias,
const torch::Tensor& layernorm_weights,
const torch::Tensor& layernorm_bias);
torch::Tensor forward(torch::Tensor& input,
const torch::Tensor& pre_padding_len,
const torch::Tensor& reorder_state,
bool pre_layernorm,
bool add_redusial,
bool first_pass);
// full decode
torch::Tensor forward_full(torch::Tensor& input,
const torch::Tensor& pre_padding_length,
bool pre_layernorm,
bool add_redusial);
// incremental decode
torch::Tensor forward_inc(torch::Tensor& input,
const torch::Tensor& pre_padding_len,
const torch::Tensor& reorder_state,
bool pre_layernorm,
bool add_redusial);
~MaskedMultiHeadAttention(){
// check_cuda_error(cudaFree(&fused_qkv_ptr_));
};
private:
// TODO layernorm
void layer_norm(const torch::Tensor& input_tensor,
Buffer& layernorm_query);
void qkv_weights_mul(void* input,
Buffer& qkv_buffer);
void qkv_add_bias(const Buffer& qkv_buffer,
Buffer& q_buf,
Buffer& k_buf,
Buffer& v_buf);
void q_k_mul(const Buffer& q_buf, const Buffer& k_buf,
Buffer& qk_buf);
void qk_softmax(Buffer& qk_buf,const int64_t *padding_len);
void attn_v_mul(const Buffer& qk_buf, const Buffer& v_buf,
Buffer& transpose_dst);
void transpose(const Buffer& transpose_dst, Buffer& dst);
void project(const Buffer& dst,
Buffer& res,
torch::Tensor& input,
bool pre_layernorm,
bool add_redusial);
void masked_attention(const Buffer& qkv_buffer,
Buffer& context_buf,
const int64_t *padding_len,
const int64_t *reorder_index);
void kv_transpose(torch::Tensor& d_K_buf, torch::Tensor& d_V_buf,Buffer& K_buf,Buffer& V_buf);
MetaDesc desc_;
// torch::Tensor output_;
torch::Tensor k_cache_, v_cache_;
cublasGemmAlgo_t qkv_weights_algo_, q_k_algo_, attn_v_algo_;
int cur_batch_size_;
int first_batch_size_;
int cur_seq_len_;
int size_per_head_;
int step_;
void* alpha_;
void* beta_;
void* atten_scaler_;
void* fused_qkv_ptr_;
void** qkv_input_;
void** qkv_kernel_;
void** qkv_buf_;
private:
void* qkv_weights_;
void* q_bias_;
void* k_bias_;
void* v_bias_;
void* output_weights_;
void* output_bias_;
void* layernorm_weights_;
void* layernorm_bias_;
};
}
}
#endif
| 4,334 | 1,196 |
// 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/lookalikes/lookalike_url_navigation_throttle.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "components/lookalikes/core/features.h"
#include "components/reputation/core/safety_tip_test_utils.h"
#include "components/url_formatter/spoof_checks/idn_spoof_checker.h"
#include "components/url_formatter/url_formatter.h"
#include "content/public/test/mock_navigation_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace lookalikes {
class LookalikeThrottleTest : public ChromeRenderViewHostTestHarness {};
// Tests that spoofy hostnames are properly handled in the throttle.
TEST_F(LookalikeThrottleTest, SpoofsBlocked) {
base::HistogramTester test;
reputation::InitializeSafetyTipConfig();
const struct TestCase {
const char* hostname;
bool expected_blocked;
url_formatter::IDNSpoofChecker::Result expected_spoof_check_result;
} kTestCases[] = {
// ASCII private domain.
{"private.hostname", false,
url_formatter::IDNSpoofChecker::Result::kNone},
// lษlocked.com, fails ICU spoof checks.
{"xn--llocked-9bd.com", true,
url_formatter::IDNSpoofChecker::Result::kICUSpoofChecks},
// รพook.com, contains a TLD specific character (รพ).
{"xn--ook-ooa.com", true,
url_formatter::IDNSpoofChecker::Result::kTLDSpecificCharacters},
// exampleยทcom.com, unsafe middle dot.
{"xn--examplecom-rra.com", true,
url_formatter::IDNSpoofChecker::Result::kUnsafeMiddleDot},
// scope.com, with scope in Cyrillic. Whole script confusable.
{"xn--e1argc3h.com", true,
url_formatter::IDNSpoofChecker::Result::kWholeScriptConfusable},
// Non-ASCII Latin with Non-Latin character
{"xn--caf-dma9024xvpg.kr", true,
url_formatter::IDNSpoofChecker::Result::
kNonAsciiLatinCharMixedWithNonLatin},
// testใผsite.com, has dangerous pattern (ใผ is CJK character).
{"xn--testsite-1g5g.com", true,
url_formatter::IDNSpoofChecker::Result::kDangerousPattern},
// TODO(crbug.com/1100485): Add an example for digit lookalikes.
// ๐.com, fails ICU spoof checks, but is allowed because consists of only
// emoji and ASCII.
{"xn--vi8h.com", false,
url_formatter::IDNSpoofChecker::Result::kICUSpoofChecks},
// sparkasse-gieรen.de, has a deviation character (ร). This is in punycode
// because GURL canonicalizes ร to ss.
{"xn--sparkasse-gieen-2ib.de", false,
url_formatter::IDNSpoofChecker::Result::kDeviationCharacters},
};
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
lookalikes::features::kLookalikeInterstitialForPunycode);
for (const TestCase& test_case : kTestCases) {
url_formatter::IDNConversionResult idn_result =
url_formatter::UnsafeIDNToUnicodeWithDetails(test_case.hostname);
ASSERT_EQ(test_case.expected_spoof_check_result,
idn_result.spoof_check_result)
<< test_case.hostname;
GURL url(std::string("http://") + test_case.hostname);
content::MockNavigationHandle handle(url, main_rfh());
handle.set_redirect_chain({url});
handle.set_page_transition(ui::PAGE_TRANSITION_TYPED);
auto throttle =
LookalikeUrlNavigationThrottle::MaybeCreateNavigationThrottle(&handle);
ASSERT_TRUE(throttle);
throttle->SetUseTestProfileForTesting();
EXPECT_EQ(content::NavigationThrottle::PROCEED,
throttle->WillStartRequest().action());
if (test_case.expected_blocked) {
EXPECT_EQ(content::NavigationThrottle::CANCEL,
throttle->WillProcessResponse().action())
<< "Failed: " << test_case.hostname;
} else {
EXPECT_EQ(content::NavigationThrottle::PROCEED,
throttle->WillProcessResponse().action())
<< "Failed: " << test_case.hostname;
}
}
}
} // namespace lookalikes
| 4,215 | 1,444 |
#include <cstddef>
#include <cstdint>
size_t AuxTranslationBinarySize_Gen8core = 1692;
uint32_t AuxTranslationBinary_Gen8core[423] = {
0x494e5443, 0x00000420, 0x0000000b, 0x00000008, 0x00000001, 0x00000000, 0x00000000, 0x2f674870,
0xad5c17e9, 0x304ea729, 0x0000000c, 0x000003a0, 0x000001c0, 0x00000000, 0x00000020, 0x000000cc,
0x00000140, 0x6c6c7566, 0x79706f43, 0x00000000, 0x00008006, 0x30000004, 0x16001000, 0x04c004c0,
0x202d8041, 0x00090800, 0x20004d01, 0x00007f07, 0x00800040, 0x20600a28, 0x12000100, 0x00b10020,
0x00802040, 0x20a00a28, 0x12000100, 0x00b10040, 0x20019640, 0x07030307, 0x00802040, 0x20a00a28,
0x0a8d00a0, 0x000000e0, 0x00800009, 0x21400a28, 0x1e8d0060, 0x00040004, 0x00802009, 0x21800a28,
0x1e8d00a0, 0x00040004, 0x0c800031, 0x21c03a68, 0x068d0140, 0x04805000, 0x20005601, 0x000a1e07,
0x0c802031, 0x22c03a68, 0x068d0180, 0x04805000, 0x00802001, 0x25000208, 0x008d0180, 0x00000000,
0x2002d601, 0x000e2007, 0x2002d601, 0x00102207, 0x2002d601, 0x00122407, 0x2002d601, 0x00142607,
0x00802001, 0x25400a28, 0x008d02c0, 0x00000000, 0x00802001, 0x25800a28, 0x008d0300, 0x00000000,
0x00802001, 0x25c00a28, 0x008d0340, 0x00000000, 0x00802001, 0x26000a28, 0x008d0380, 0x00000000,
0x0c800031, 0x20003a60, 0x068d03c0, 0x14025001, 0x0c802031, 0x20003a60, 0x068d0500, 0x14025001,
0x07600031, 0x20003a04, 0x068d0fe0, 0x82000010, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x000000c3, 0x00000000, 0x00000000, 0x00000003, 0x83ffc000, 0x03000000, 0x1fff007f, 0x0fe00000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x83ffc000, 0x03000000, 0x1fff007f, 0x0fe00000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x87ffc000, 0x03000000, 0x1fff007f, 0x0fe00000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000040, 0x00000080, 0x00000013,
0x0000000c, 0x00000000, 0x00000015, 0x00000018, 0x00000000, 0x00000000, 0x00000000, 0x000000c0,
0x00000008, 0x00000014, 0x000000c0, 0x00000003, 0x00000000, 0x00000011, 0x00000028, 0x00000010,
0x00000000, 0x00000000, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011,
0x00000028, 0x00000010, 0x00000000, 0x00000004, 0x00000004, 0x00000004, 0x00000000, 0x00000000,
0x00000000, 0x00000011, 0x00000028, 0x00000010, 0x00000000, 0x00000008, 0x00000004, 0x00000008,
0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002, 0x00000000, 0x0000000c,
0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x00000002,
0x00000000, 0x00000010, 0x00000004, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000011,
0x00000028, 0x00000002, 0x00000000, 0x00000014, 0x00000004, 0x00000008, 0x00000000, 0x00000000,
0x00000000, 0x00000011, 0x00000028, 0x0000002b, 0x00000000, 0x00000020, 0x00000004, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000002b, 0x00000001, 0x00000028,
0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011, 0x00000028, 0x0000001c,
0x00000000, 0x00000040, 0x00000004, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000011,
0x00000028, 0x0000001c, 0x00000000, 0x00000044, 0x00000004, 0x00000004, 0x00000000, 0x00000000,
0x00000000, 0x00000011, 0x00000028, 0x0000001c, 0x00000000, 0x00000048, 0x00000004, 0x00000008,
0x00000000, 0x00000000, 0x00000000, 0x0000001e, 0x00000024, 0x00000000, 0x00000000, 0x00000020,
0x00000008, 0xffffffff, 0xffffffff, 0x00000000, 0x0000001e, 0x00000024, 0x00000001, 0x00000040,
0x00000028, 0x00000008, 0xffffffff, 0xffffffff, 0x00000000, 0x00000026, 0x00000018, 0x00000080,
0x00000030, 0x00000008, 0x00000000, 0x00000019, 0x0000000c, 0x00000060, 0x00000016, 0x00000040,
0x00000000, 0x00000001, 0x00000001, 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000017, 0x00000064,
0x00000000, 0x00000000, 0x00000000, 0x00000020, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000001, 0x00000000, 0x00000080, 0x00000000, 0x00000000, 0x00000000, 0x0000001b,
0x00000010, 0x00000004, 0x00000000, 0x0000001a, 0x00000048, 0x00000000, 0x0000000c, 0x00000008,
0x00000004, 0x00000008, 0x00000008, 0x6c675f5f, 0x6c61626f, 0x00000000, 0x454e4f4e, 0x00000000,
0x00637273, 0x746e6975, 0x00383b2a, 0x736e6f63, 0x00000074, 0x0000001a, 0x00000048, 0x00000001,
0x0000000c, 0x00000008, 0x00000004, 0x00000008, 0x00000008, 0x6c675f5f, 0x6c61626f, 0x00000000,
0x454e4f4e, 0x00000000, 0x00747364, 0x746e6975, 0x00383b2a, 0x454e4f4e, 0x00000000};
#include "runtime/built_ins/registry/built_ins_registry.h"
namespace NEO {
static RegisterEmbeddedResource registerAuxTranslationBin(
createBuiltinResourceName(
EBuiltInOps::AuxTranslation,
BuiltinCode::getExtension(BuiltinCode::ECodeType::Binary), "Gen8core", 0)
.c_str(),
(const char *)AuxTranslationBinary_Gen8core,
AuxTranslationBinarySize_Gen8core);
}
| 5,872 | 5,336 |
#include "boost/bind.hpp"
#include "Utils/VsipVector.h"
#include "Difference.h"
#include "Difference_defaults.h"
using namespace SideCar::Algorithms;
using namespace SideCar::Messages;
Difference::Difference(Controller& controller, Logger::Log& log) :
Algorithm(controller, log),
bufferSize_(Parameter::PositiveIntValue::Make("bufferSize", "Buffer Size", kDefaultBufferSize)),
in0_(bufferSize_->getValue()), in1_(bufferSize_->getValue())
{
bufferSize_->connectChangedSignalTo(boost::bind(&Difference::bufferSizeChanged, this, _1));
}
bool
Difference::startup()
{
registerProcessor<Difference, Video>(0, &Difference::processIn0);
registerProcessor<Difference, Video>(1, &Difference::processIn1);
return registerParameter(bufferSize_);
}
bool
Difference::reset()
{
in0_.clear();
in1_.clear();
return true;
}
bool
Difference::processIn0(Video::Ref in)
{
in0_.add(in);
Video::Ref in1 = in1_.find(in->getSequenceCounter());
if (!in1) return true;
return process(in, in1);
}
bool
Difference::processIn1(Video::Ref in)
{
in1_.add(in);
Video::Ref in0 = in0_.find(in->getSequenceCounter());
if (!in0) return true;
return process(in0, in);
}
bool
Difference::process(Video::Ref in0, Video::Ref in1)
{
Video::Ref out(Video::Make(getName(), in0));
out->resize(in0->size(), 0);
// Calculate in0 - in1
//
VsipVector<Video> vIn0(*in0);
vIn0.admit(true);
VsipVector<Video> vIn1(*in1);
vIn1.admit(true);
VsipVector<Video> vOut(*out);
vOut.admit(false);
vOut.v = vIn0.v;
vIn0.release(false);
vOut.v -= vIn1.v;
vIn1.release(false);
vOut.release(true);
return send(out);
}
void
Difference::bufferSizeChanged(const Parameter::PositiveIntValue& value)
{
in0_.setCapacity(value.getValue());
in0_.clear();
in1_.setCapacity(value.getValue());
in1_.clear();
}
// DLL support
//
extern "C" ACE_Svc_Export Algorithm*
DifferenceMake(Controller& controller, Logger::Log& log)
{
return new Difference(controller, log);
}
| 2,059 | 729 |
#include <iostream>
#include "MemPool.h"
Pool::Pool(int size){
//create the pool, or char array...
pool = new unsigned char[size];
//create temp which is a temp pointer to the beginning of pool
int* temp=(int*)pool;
//The value of *temp becomes the size of our array
*temp=size;
//Out puts the size and where the char array is!
std::cout<<*temp<<" "<<temp<<std::endl;
//Create a new ptr in our pool which points nowhere but is casted as a int*
long* ptr_b=(long*)temp+1;
*ptr_b=(long)NULL;
//Create a new ptr in our pool which points nowhere but is casted as a int*
long* ptr_f=ptr_b+1;
*ptr_f=(long)NULL;
//Set our firstNode as the beginning of our empty array
firstNode=temp;
}
void* Pool::allocate (unsigned int bytes){
//find where we can start allocating!
int* temp=firstNode;
if(firstNode==NULL){
std::cout<<"You are out of memory!"<<std::endl;
return NULL;
}
//This is the next node where we can store data
long* next=(long*)temp+2;
//We need this loop to be able to loop through to find an appropriate space
//to allocate the variable.
while(true){
//This first if statement finds if the size of empty space is smaller than
//the wanted size. If true we need to check if the next slot is available.
//If so then we loop around and do the check again! If not there is no
//space available for the variable and we just return the NULL pointer.
if(*temp<bytes){
if(*next==(long)NULL){
std::cout<<"No space available for this item!"<<std::endl;
return NULL;
}
else{
temp=(int*) *next;
next=(long*)temp+2;
}
}
//This is when the variable fits perfectly into the slot! If our current
//slot is the only node we need to show that our memory is full and set
//the firstNode to Null returning our memory. If it is not but is the
//firstNode we change the memory area pointed to in next as the new
//firstNode.
else if(*temp==bytes){
std::cout<<"Warning your memory is getting full!!"<<std::endl;
if(temp==firstNode){
if(*next==(long)NULL){
std::cout<<"You're memory is now full!"<<std::endl;
//*temp alread is equivalent to the bytes
//there are no more nodes!
//and we need to send the pointer to the memory slot!
firstNode=NULL;
return temp+1;
}
else{
firstNode==(int*)*next;
return temp+1;
}
}
//Otherwise our node is in the middle and we need to close it and set
//the appropriate pointers to the right places.
else{
long* ptr_b=(long*)temp+1;
long* ptr_f=(long*)temp+2;
int* tempb=(int*)*ptr_b;
long* ptrb_f=(long*)tempb+2;
*ptrb_f=*ptr_f;
int* tempf=(int*)*ptr_f;
long* ptrf_b=(long*)tempf+1;
*ptrf_b=*ptr_b;
}
}
//This is when our space does not exactly equal the space wanted and we
//split the area.
else{
//std::cout<<"Help\n";
void* ptr=temp+1;
long* pb=(long*) temp+1;
long* pf=pb+1;
int* temp2=temp+1+(bytes/sizeof(int));
*temp2=*temp-bytes-sizeof(int);
*temp=bytes;
long* ptr_b=(long*)temp2+1;
*ptr_b=*pb;
long* ptr_f=ptr_b+1;
*ptr_f=*pf;
firstNode=temp2;
std::cout<<*temp<<' '<<ptr<<std::endl
<<*temp2<<' '<<temp2<<' '<<ptr_b<<' '<<ptr_f<<std::endl
<<firstNode<<std::endl;
return ptr;
}
}
}
//Deallocate function
void Pool::deallocate (void* ptr){
int* a=(int*) ptr;
a-=1;
int* b=firstNode;
long* next=(long*) b+2;
//if the firstNode is full we know our vector is full and have to make a
//a node that will become our firstNode
if(firstNode==NULL){
//size remains the same
long* aptr_b=(long*)a+1;
long* aptr_f=aptr_b+1;
*aptr_b=(long)NULL;
*aptr_f=(long)NULL;
firstNode=a;
}
//If the slot comes before our firstNode
else if(a<firstNode){
std::cout<<"1";
// std::cout<<a+(*a/sizeof(int))+1<<std::endl;
//Is the slot connected to the first node?
if(a+*a/sizeof(int)+1==b){
//Node pointers for a
std::cout<<"a"<<std::endl;
int* aptr_b=a+1;
int* aptr_f=aptr_b+1;
//Node pointers for b
int* c=b+1;
int* d=c+1;
*a=*a+*b+sizeof(int);
*aptr_b=*c;
*aptr_f=*d;
firstNode=a;
}
//When it is not connected to the firstNode
else{
std::cout<<"b"<<std::endl;
long* aptr_b=(long*) a+1;
long* aptr_f=aptr_b+1;
//The size stays the same! *a=*a
*aptr_b=(long)NULL;
*aptr_f=(long) b;
firstNode=a;
}
}
//When the deallocation spot comes after our firstNode
else{
//std::cout<<"else"<<std::endl;
//Finding where our slot is in the memory
while((long)a>*next){
std::cout<<"loop"<<std::endl;
if(a>(int*) *next){
b=(int*) *next;
next=(long*) b+2;
}
}
long* bptr_b=(long*) b+1;
long* bptr_f=bptr_b+1;
int* x=(int*) *bptr_f;
long* xptr_b=(long*) x+1;
long* xptr_f=xptr_b+1;
//These are our test cases
std::cout<<"2";
//connected on both sides to free space
if(a==b+*b/sizeof(int)+1 and x==a+*a/sizeof(int)+1){
std::cout<<"a"<<std::endl;
*b=*b+*a+*x+2*sizeof(int);
*bptr_f=*xptr_f;
}
//connected on the front side
else if(a==b+*b/sizeof(int)+1){
std::cout<<"b"<<std::endl;
*b=*b+*a+sizeof(int);
}
//connected on the back side
else if(x==a+*a/sizeof(int)+1){
std::cout<<"c"<<std::endl;
long* aptr_b=(long*)a+1;
long* aptr_f=aptr_b+1;
*a=*a+*x+sizeof(int);
*aptr_b=*xptr_b;
*aptr_f=*xptr_f;
}
//not connected to any free space
else{
std::cout<<"d"<<std::endl;
long* aptr_b=(long*)a+1;
long* aptr_f=aptr_b+1;
//size stays the same! *a=*a
*aptr_b=*xptr_b;
*aptr_f=*bptr_f;
*xptr_b=(long)a;
*bptr_f=(long)a;
}
}
}
void Pool::print_size(){
int* temp=firstNode;
std::cout<<*temp<<" "<<temp<<std::endl;
}
| 6,015 | 2,325 |
#include "xleaflet/ximage_overlay.hpp"
template class XLEAFLET_API xw::xmaterialize<xlf::ximage_overlay>;
template xw::xmaterialize<xlf::ximage_overlay>::xmaterialize();
template class XLEAFLET_API xw::xtransport<xw::xmaterialize<xlf::ximage_overlay>>;
template class XLEAFLET_API xw::xgenerator<xlf::ximage_overlay>;
template xw::xgenerator<xlf::ximage_overlay>::xgenerator();
template class XLEAFLET_API xw::xtransport<xw::xgenerator<xlf::ximage_overlay>>;
| 460 | 180 |
//
// Created by hao on 3/6/19.
//
#include "ObjLoader.h"
| 59 | 31 |
#include <xtd/drawing/color.h>
#include <xtd/argument_exception.h>
#include <xtd/xtd.tunit>
using namespace xtd;
using namespace xtd::drawing;
using namespace xtd::tunit;
namespace unit_tests {
class test_class_(test_color) {
public:
void test_method_(create_empty_color) {
color c;
assert::are_equal(color(), c);
assert::are_equal(color::empty, c);
assert::are_equal(0, c.a());
assert::are_equal(0, c.r());
assert::are_equal(0, c.g());
assert::are_equal(0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("0", c.name());
assert::are_equal("color [empty]", c.to_string());
assert::is_true(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0U, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_argb_0) {
color c = color::from_argb(0);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0, c.a());
assert::are_equal(0, c.r());
assert::are_equal(0, c.g());
assert::are_equal(0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("0", c.name());
assert::are_equal("color [a=0, r=0, g=0, b=0]", c.to_string());
assert::is_false(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0U, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_argb_0x12_0x34_0x56_0x78) {
color c = color::from_argb(0x12, 0x34, 0x56, 0x78);
assert::are_equal(color::from_argb(0x12345678), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0x12, c.a());
assert::are_equal(0x34, c.r());
assert::are_equal(0x56, c.g());
assert::are_equal(0x78, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("12345678", c.name());
assert::are_equal("color [a=18, r=52, g=86, b=120]", c.to_string());
assert::is_false(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0x12345678U, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_argb_0x12_0x34_0x56) {
color c = color::from_argb(0x12, 0x34, 0x56);
assert::are_equal(color::from_argb(0xFF123456), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x12, c.r());
assert::are_equal(0x34, c.g());
assert::are_equal(0x56, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("FF123456", c.name());
assert::are_equal("color [a=255, r=18, g=52, b=86]", c.to_string());
assert::is_false(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0xFF123456U, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_argb_0x20_color_blue) {
color c = color::from_argb(0x20, color::blue);
assert::are_equal(color::from_argb(0x20, color::blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0x20, c.a());
assert::are_equal(0x0, c.r());
assert::are_equal(0x0, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("200000FF", c.name());
assert::are_equal("color [a=32, r=0, g=0, b=255]", c.to_string());
assert::is_false(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0x200000FFU, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_argb_0x12345678) {
color c = color::from_argb(0x12345678);
assert::are_equal(color::from_argb(0x12345678), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0x12, c.a());
assert::are_equal(0x34, c.r());
assert::are_equal(0x56, c.g());
assert::are_equal(0x78, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("12345678", c.name());
assert::are_equal("color [a=18, r=52, g=86, b=120]", c.to_string());
assert::is_false(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0x12345678U, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_hsb_240_1_1) {
color c = color::from_hsb(240, 1.0f, 1.0f);
assert::are_equal(color::from_hsb(240, 1.0f, 1.0f), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("FF0000FF", c.name());
assert::are_equal(240, c.get_hue());
assert::are_equal(1.0f, c.get_saturation());
assert::are_equal(1.0f, c.get_brightness());
assert::are_equal("color [a=255, r=0, g=0, b=255]", c.to_string());
assert::is_false(c.is_empty());
assert::is_false(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_false(c.is_named_color());
assert::are_equal(0xFF0000FFU, c.to_argb());
assert::are_equal((known_color)0, c.to_known_color());
}
void test_method_(create_from_hsl_138_050_076) {
color c = color::from_hsl(138, 0.50f, 0.76f);
assert::are_equal(color::from_hsl(138, 0.50f, 0.76f), c, line_info_);
assert::are_not_equal(color(), c, line_info_);
assert::are_not_equal(color::empty, c, line_info_);
assert::are_equal(0xFF, c.a(), line_info_);
assert::are_equal(0xA3, c.r(), line_info_);
assert::are_equal(0xE0, c.g(), line_info_);
assert::are_equal(0xB5, c.b(), line_info_);
assert::are_equal(0, c.handle(), line_info_);
assert::are_equal("FFA3E0B5", c.name(), line_info_);
assert::are_equal(138.0f, c.get_hue(), 0.5f, line_info_);
assert::are_equal(0.50f, c.get_saturation(), 0.005f, line_info_);
assert::are_equal(0.76f, c.get_lightness(), 0.005f, line_info_);
assert::are_equal("color [a=255, r=163, g=224, b=181]", c.to_string(), line_info_);
assert::is_false(c.is_empty(), line_info_);
assert::is_false(c.is_known_color(), line_info_);
assert::is_false(c.is_system_color(), line_info_);
assert::is_false(c.is_named_color(), line_info_);
assert::are_equal(0xFFA3E0B5, c.to_argb(), line_info_);
assert::are_equal((known_color)0, c.to_known_color(), line_info_);
}
void test_method_(create_from_know_color_invalid) {
assert::throws<argument_exception>([] {color::from_known_color((known_color)7654);});
}
void test_method_(create_from_know_color_transparent) {
color c = color::from_known_color(known_color::transparent);
assert::are_equal(color::from_known_color(known_color::transparent), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0x00, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("transparent", c.name());
assert::are_equal("color [transparent]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0x00FFFFFFU, c.to_argb());
assert::are_equal(known_color::transparent, c.to_known_color());
}
void test_method_(create_from_know_color_alice_blue) {
color c = color::from_known_color(known_color::alice_blue);
assert::are_equal(color::from_known_color(known_color::alice_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xF8, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("alice_blue", c.name());
assert::are_equal("color [alice_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0F8FFU, c.to_argb());
assert::are_equal(known_color::alice_blue, c.to_known_color());
}
void test_method_(create_from_know_color_antique_white) {
color c = color::from_known_color(known_color::antique_white);
assert::are_equal(color::from_known_color(known_color::antique_white), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0xEB, c.g());
assert::are_equal(0xD7, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("antique_white", c.name());
assert::are_equal("color [antique_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFAEBD7U, c.to_argb());
assert::are_equal(known_color::antique_white, c.to_known_color());
}
void test_method_(create_from_know_color_aqua) {
color c = color::from_known_color(known_color::aqua);
assert::are_equal(color::from_known_color(known_color::aqua), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("aqua", c.name());
assert::are_equal("color [aqua]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FFFFU, c.to_argb());
assert::are_equal(known_color::aqua, c.to_known_color());
}
void test_method_(create_from_know_color_aquamarine) {
color c = color::from_known_color(known_color::aquamarine);
assert::are_equal(color::from_known_color(known_color::aquamarine), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7F, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xD4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("aquamarine", c.name());
assert::are_equal("color [aquamarine]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7FFFD4U, c.to_argb());
assert::are_equal(known_color::aquamarine, c.to_known_color());
}
void test_method_(create_from_know_color_azure) {
color c = color::from_known_color(known_color::azure);
assert::are_equal(color::from_known_color(known_color::azure), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("azure", c.name());
assert::are_equal("color [azure]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0FFFFU, c.to_argb());
assert::are_equal(known_color::azure, c.to_known_color());
}
void test_method_(create_from_know_color_beige) {
color c = color::from_known_color(known_color::beige);
assert::are_equal(color::from_known_color(known_color::beige), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xDC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("beige", c.name());
assert::are_equal("color [beige]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5F5DCU, c.to_argb());
assert::are_equal(known_color::beige, c.to_known_color());
}
void test_method_(create_from_know_color_bisque) {
color c = color::from_known_color(known_color::bisque);
assert::are_equal(color::from_known_color(known_color::bisque), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xE4, c.g());
assert::are_equal(0xC4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("bisque", c.name());
assert::are_equal("color [bisque]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFE4C4U, c.to_argb());
assert::are_equal(known_color::bisque, c.to_known_color());
}
void test_method_(create_from_know_color_black) {
color c = color::from_known_color(known_color::black);
assert::are_equal(color::from_known_color(known_color::black), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("black", c.name());
assert::are_equal("color [black]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF000000U, c.to_argb());
assert::are_equal(known_color::black, c.to_known_color());
}
void test_method_(create_from_know_color_blanched_almond) {
color c = color::from_known_color(known_color::blanched_almond);
assert::are_equal(color::from_known_color(known_color::blanched_almond), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xEB, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("blanched_almond", c.name());
assert::are_equal("color [blanched_almond]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFEBCDU, c.to_argb());
assert::are_equal(known_color::blanched_almond, c.to_known_color());
}
void test_method_(create_from_know_color_blue) {
color c = color::from_known_color(known_color::blue);
assert::are_equal(color::from_known_color(known_color::blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("blue", c.name());
assert::are_equal("color [blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF0000FFU, c.to_argb());
assert::are_equal(known_color::blue, c.to_known_color());
}
void test_method_(create_from_know_color_blue_violet) {
color c = color::from_known_color(known_color::blue_violet);
assert::are_equal(color::from_known_color(known_color::blue_violet), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8A, c.r());
assert::are_equal(0x2B, c.g());
assert::are_equal(0xE2, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("blue_violet", c.name());
assert::are_equal("color [blue_violet]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8A2BE2U, c.to_argb());
assert::are_equal(known_color::blue_violet, c.to_known_color());
}
void test_method_(create_from_know_color_brown) {
color c = color::from_known_color(known_color::brown);
assert::are_equal(color::from_known_color(known_color::brown), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xA5, c.r());
assert::are_equal(0x2A, c.g());
assert::are_equal(0x2A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("brown", c.name());
assert::are_equal("color [brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFA52A2AU, c.to_argb());
assert::are_equal(known_color::brown, c.to_known_color());
}
void test_method_(create_from_know_color_burly_wood) {
color c = color::from_known_color(known_color::burly_wood);
assert::are_equal(color::from_known_color(known_color::burly_wood), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDE, c.r());
assert::are_equal(0xB8, c.g());
assert::are_equal(0x87, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("burly_wood", c.name());
assert::are_equal("color [burly_wood]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDEB887U, c.to_argb());
assert::are_equal(known_color::burly_wood, c.to_known_color());
}
void test_method_(create_from_know_color_cadet_blue) {
color c = color::from_known_color(known_color::cadet_blue);
assert::are_equal(color::from_known_color(known_color::cadet_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x5F, c.r());
assert::are_equal(0x9E, c.g());
assert::are_equal(0xA0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cadet_blue", c.name());
assert::are_equal("color [cadet_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF5F9EA0U, c.to_argb());
assert::are_equal(known_color::cadet_blue, c.to_known_color());
}
void test_method_(create_from_know_color_chartreuse) {
color c = color::from_known_color(known_color::chartreuse);
assert::are_equal(color::from_known_color(known_color::chartreuse), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7F, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("chartreuse", c.name());
assert::are_equal("color [chartreuse]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7FFF00U, c.to_argb());
assert::are_equal(known_color::chartreuse, c.to_known_color());
}
void test_method_(create_from_know_color_chocolate) {
color c = color::from_known_color(known_color::chocolate);
assert::are_equal(color::from_known_color(known_color::chocolate), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD2, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0x1E, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("chocolate", c.name());
assert::are_equal("color [chocolate]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD2691EU, c.to_argb());
assert::are_equal(known_color::chocolate, c.to_known_color());
}
void test_method_(create_from_know_color_coral) {
color c = color::from_known_color(known_color::coral);
assert::are_equal(color::from_known_color(known_color::coral), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x7F, c.g());
assert::are_equal(0x50, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("coral", c.name());
assert::are_equal("color [coral]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF7F50U, c.to_argb());
assert::are_equal(known_color::coral, c.to_known_color());
}
void test_method_(create_from_know_color_cornflower_blue) {
color c = color::from_known_color(known_color::cornflower_blue);
assert::are_equal(color::from_known_color(known_color::cornflower_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x64, c.r());
assert::are_equal(0x95, c.g());
assert::are_equal(0xED, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cornflower_blue", c.name());
assert::are_equal("color [cornflower_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF6495EDU, c.to_argb());
assert::are_equal(known_color::cornflower_blue, c.to_known_color());
}
void test_method_(create_from_know_color_cornsilk) {
color c = color::from_known_color(known_color::cornsilk);
assert::are_equal(color::from_known_color(known_color::cornsilk), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xF8, c.g());
assert::are_equal(0xDC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cornsilk", c.name());
assert::are_equal("color [cornsilk]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFF8DCU, c.to_argb());
assert::are_equal(known_color::cornsilk, c.to_known_color());
}
void test_method_(create_from_know_color_crimson) {
color c = color::from_known_color(known_color::crimson);
assert::are_equal(color::from_known_color(known_color::crimson), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDC, c.r());
assert::are_equal(0x14, c.g());
assert::are_equal(0x3C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("crimson", c.name());
assert::are_equal("color [crimson]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDC143CU, c.to_argb());
assert::are_equal(known_color::crimson, c.to_known_color());
}
void test_method_(create_from_know_color_cyan) {
color c = color::from_known_color(known_color::cyan);
assert::are_equal(color::from_known_color(known_color::cyan), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cyan", c.name());
assert::are_equal("color [cyan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FFFFU, c.to_argb());
assert::are_equal(known_color::cyan, c.to_known_color());
}
void test_method_(create_from_know_color_dark_blue) {
color c = color::from_known_color(known_color::dark_blue);
assert::are_equal(color::from_known_color(known_color::dark_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_blue", c.name());
assert::are_equal("color [dark_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00008BU, c.to_argb());
assert::are_equal(known_color::dark_blue, c.to_known_color());
}
void test_method_(create_from_know_color_dark_cyan) {
color c = color::from_known_color(known_color::dark_cyan);
assert::are_equal(color::from_known_color(known_color::dark_cyan), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x8B, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_cyan", c.name());
assert::are_equal("color [dark_cyan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF008B8BU, c.to_argb());
assert::are_equal(known_color::dark_cyan, c.to_known_color());
}
void test_method_(create_from_know_color_dark_goldenrod) {
color c = color::from_known_color(known_color::dark_goldenrod);
assert::are_equal(color::from_known_color(known_color::dark_goldenrod), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB8, c.r());
assert::are_equal(0x86, c.g());
assert::are_equal(0x0B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_goldenrod", c.name());
assert::are_equal("color [dark_goldenrod]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB8860BU, c.to_argb());
assert::are_equal(known_color::dark_goldenrod, c.to_known_color());
}
void test_method_(create_from_know_color_dark_gray) {
color c = color::from_known_color(known_color::dark_gray);
assert::are_equal(color::from_known_color(known_color::dark_gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xA9, c.r());
assert::are_equal(0xA9, c.g());
assert::are_equal(0xA9, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_gray", c.name());
assert::are_equal("color [dark_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFA9A9A9U, c.to_argb());
assert::are_equal(known_color::dark_gray, c.to_known_color());
}
void test_method_(create_from_know_color_dark_green) {
color c = color::from_known_color(known_color::dark_green);
assert::are_equal(color::from_known_color(known_color::dark_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x64, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_green", c.name());
assert::are_equal("color [dark_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF006400U, c.to_argb());
assert::are_equal(known_color::dark_green, c.to_known_color());
}
void test_method_(create_from_know_color_dark_khaki) {
color c = color::from_known_color(known_color::dark_khaki);
assert::are_equal(color::from_known_color(known_color::dark_khaki), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xBD, c.r());
assert::are_equal(0xB7, c.g());
assert::are_equal(0x6B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_khaki", c.name());
assert::are_equal("color [dark_khaki]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFBDB76BU, c.to_argb());
assert::are_equal(known_color::dark_khaki, c.to_known_color());
}
void test_method_(create_from_know_color_dark_magenta) {
color c = color::from_known_color(known_color::dark_magenta);
assert::are_equal(color::from_known_color(known_color::dark_magenta), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8B, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_magenta", c.name());
assert::are_equal("color [dark_magenta]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8B008BU, c.to_argb());
assert::are_equal(known_color::dark_magenta, c.to_known_color());
}
void test_method_(create_from_know_color_dark_olive_green) {
color c = color::from_known_color(known_color::dark_olive_green);
assert::are_equal(color::from_known_color(known_color::dark_olive_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x55, c.r());
assert::are_equal(0x6B, c.g());
assert::are_equal(0x2F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_olive_green", c.name());
assert::are_equal("color [dark_olive_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF556B2FU, c.to_argb());
assert::are_equal(known_color::dark_olive_green, c.to_known_color());
}
void test_method_(create_from_know_color_dark_orange) {
color c = color::from_known_color(known_color::dark_orange);
assert::are_equal(color::from_known_color(known_color::dark_orange), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x8C, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_orange", c.name());
assert::are_equal("color [dark_orange]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF8C00U, c.to_argb());
assert::are_equal(known_color::dark_orange, c.to_known_color());
}
void test_method_(create_from_know_color_dark_orchid) {
color c = color::from_known_color(known_color::dark_orchid);
assert::are_equal(color::from_known_color(known_color::dark_orchid), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x99, c.r());
assert::are_equal(0x32, c.g());
assert::are_equal(0xCC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_orchid", c.name());
assert::are_equal("color [dark_orchid]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF9932CCU, c.to_argb());
assert::are_equal(known_color::dark_orchid, c.to_known_color());
}
void test_method_(create_from_know_color_dark_red) {
color c = color::from_known_color(known_color::dark_red);
assert::are_equal(color::from_known_color(known_color::dark_red), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8B, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_red", c.name());
assert::are_equal("color [dark_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8B0000U, c.to_argb());
assert::are_equal(known_color::dark_red, c.to_known_color());
}
void test_method_(create_from_know_color_dark_salmon) {
color c = color::from_known_color(known_color::dark_salmon);
assert::are_equal(color::from_known_color(known_color::dark_salmon), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xE9, c.r());
assert::are_equal(0x96, c.g());
assert::are_equal(0x7A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_salmon", c.name());
assert::are_equal("color [dark_salmon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFE9967AU, c.to_argb());
assert::are_equal(known_color::dark_salmon, c.to_known_color());
}
void test_method_(create_from_know_color_dark_sea_green) {
color c = color::from_known_color(known_color::dark_sea_green);
assert::are_equal(color::from_known_color(known_color::dark_sea_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8F, c.r());
assert::are_equal(0xBC, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_sea_green", c.name());
assert::are_equal("color [dark_sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8FBC8BU, c.to_argb());
assert::are_equal(known_color::dark_sea_green, c.to_known_color());
}
void test_method_(create_from_know_color_dark_slate_blue) {
color c = color::from_known_color(known_color::dark_slate_blue);
assert::are_equal(color::from_known_color(known_color::dark_slate_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x48, c.r());
assert::are_equal(0x3D, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_slate_blue", c.name());
assert::are_equal("color [dark_slate_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF483D8BU, c.to_argb());
assert::are_equal(known_color::dark_slate_blue, c.to_known_color());
}
void test_method_(create_from_know_color_dark_slate_gray) {
color c = color::from_known_color(known_color::dark_slate_gray);
assert::are_equal(color::from_known_color(known_color::dark_slate_gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x2F, c.r());
assert::are_equal(0x4F, c.g());
assert::are_equal(0x4F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_slate_gray", c.name());
assert::are_equal("color [dark_slate_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF2F4F4FU, c.to_argb());
assert::are_equal(known_color::dark_slate_gray, c.to_known_color());
}
void test_method_(create_from_know_color_dark_turquoise) {
color c = color::from_known_color(known_color::dark_turquoise);
assert::are_equal(color::from_known_color(known_color::dark_turquoise), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xCE, c.g());
assert::are_equal(0xD1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_turquoise", c.name());
assert::are_equal("color [dark_turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00CED1U, c.to_argb());
assert::are_equal(known_color::dark_turquoise, c.to_known_color());
}
void test_method_(create_from_know_color_dark_violet) {
color c = color::from_known_color(known_color::dark_violet);
assert::are_equal(color::from_known_color(known_color::dark_violet), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x94, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xD3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_violet", c.name());
assert::are_equal("color [dark_violet]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF9400D3U, c.to_argb());
assert::are_equal(known_color::dark_violet, c.to_known_color());
}
void test_method_(create_from_know_color_deep_pink) {
color c = color::from_known_color(known_color::deep_pink);
assert::are_equal(color::from_known_color(known_color::deep_pink), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x14, c.g());
assert::are_equal(0x93, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("deep_pink", c.name());
assert::are_equal("color [deep_pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF1493U, c.to_argb());
assert::are_equal(known_color::deep_pink, c.to_known_color());
}
void test_method_(create_from_know_color_deep_sky_blue) {
color c = color::from_known_color(known_color::deep_sky_blue);
assert::are_equal(color::from_known_color(known_color::deep_sky_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xBF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("deep_sky_blue", c.name());
assert::are_equal("color [deep_sky_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00BFFFU, c.to_argb());
assert::are_equal(known_color::deep_sky_blue, c.to_known_color());
}
void test_method_(create_from_know_color_dim_gray) {
color c = color::from_known_color(known_color::dim_gray);
assert::are_equal(color::from_known_color(known_color::dim_gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x69, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0x69, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dim_gray", c.name());
assert::are_equal("color [dim_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF696969U, c.to_argb());
assert::are_equal(known_color::dim_gray, c.to_known_color());
}
void test_method_(create_from_know_color_dodger_blue) {
color c = color::from_known_color(known_color::dodger_blue);
assert::are_equal(color::from_known_color(known_color::dodger_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x1E, c.r());
assert::are_equal(0x90, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dodger_blue", c.name());
assert::are_equal("color [dodger_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF1E90FFU, c.to_argb());
assert::are_equal(known_color::dodger_blue, c.to_known_color());
}
void test_method_(create_from_know_color_firebrick) {
color c = color::from_known_color(known_color::firebrick);
assert::are_equal(color::from_known_color(known_color::firebrick), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB2, c.r());
assert::are_equal(0x22, c.g());
assert::are_equal(0x22, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("firebrick", c.name());
assert::are_equal("color [firebrick]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB22222U, c.to_argb());
assert::are_equal(known_color::firebrick, c.to_known_color());
}
void test_method_(create_from_know_color_floral_white) {
color c = color::from_known_color(known_color::floral_white);
assert::are_equal(color::from_known_color(known_color::floral_white), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xF0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("floral_white", c.name());
assert::are_equal("color [floral_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFAF0U, c.to_argb());
assert::are_equal(known_color::floral_white, c.to_known_color());
}
void test_method_(create_from_know_color_forest_green) {
color c = color::from_known_color(known_color::forest_green);
assert::are_equal(color::from_known_color(known_color::forest_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x22, c.r());
assert::are_equal(0x8B, c.g());
assert::are_equal(0x22, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("forest_green", c.name());
assert::are_equal("color [forest_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF228B22U, c.to_argb());
assert::are_equal(known_color::forest_green, c.to_known_color());
}
void test_method_(create_from_know_color_fuchsia) {
color c = color::from_known_color(known_color::fuchsia);
assert::are_equal(color::from_known_color(known_color::fuchsia), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("fuchsia", c.name());
assert::are_equal("color [fuchsia]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF00FFU, c.to_argb());
assert::are_equal(known_color::fuchsia, c.to_known_color());
}
void test_method_(create_from_know_color_gainsboro) {
color c = color::from_known_color(known_color::gainsboro);
assert::are_equal(color::from_known_color(known_color::gainsboro), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDC, c.r());
assert::are_equal(0xDC, c.g());
assert::are_equal(0xDC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("gainsboro", c.name());
assert::are_equal("color [gainsboro]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDCDCDCU, c.to_argb());
assert::are_equal(known_color::gainsboro, c.to_known_color());
}
void test_method_(create_from_know_color_ghost_white) {
color c = color::from_known_color(known_color::ghost_white);
assert::are_equal(color::from_known_color(known_color::ghost_white), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF8, c.r());
assert::are_equal(0xF8, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("ghost_white", c.name());
assert::are_equal("color [ghost_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF8F8FFU, c.to_argb());
assert::are_equal(known_color::ghost_white, c.to_known_color());
}
void test_method_(create_from_know_color_gold) {
color c = color::from_known_color(known_color::gold);
assert::are_equal(color::from_known_color(known_color::gold), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xD7, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("gold", c.name());
assert::are_equal("color [gold]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFD700U, c.to_argb());
assert::are_equal(known_color::gold, c.to_known_color());
}
void test_method_(create_from_know_color_goldenrod) {
color c = color::from_known_color(known_color::goldenrod);
assert::are_equal(color::from_known_color(known_color::goldenrod), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDA, c.r());
assert::are_equal(0xA5, c.g());
assert::are_equal(0x20, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("goldenrod", c.name());
assert::are_equal("color [goldenrod]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDAA520U, c.to_argb());
assert::are_equal(known_color::goldenrod, c.to_known_color());
}
void test_method_(create_from_know_color_gray) {
color c = color::from_known_color(known_color::gray);
assert::are_equal(color::from_known_color(known_color::gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("gray", c.name());
assert::are_equal("color [gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF808080U, c.to_argb());
assert::are_equal(known_color::gray, c.to_known_color());
}
void test_method_(create_from_know_color_green) {
color c = color::from_known_color(known_color::green);
assert::are_equal(color::from_known_color(known_color::green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("green", c.name());
assert::are_equal("color [green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF008000U, c.to_argb());
assert::are_equal(known_color::green, c.to_known_color());
}
void test_method_(create_from_know_color_green_yellow) {
color c = color::from_known_color(known_color::green_yellow);
assert::are_equal(color::from_known_color(known_color::green_yellow), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xAD, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x2F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("green_yellow", c.name());
assert::are_equal("color [green_yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFADFF2FU, c.to_argb());
assert::are_equal(known_color::green_yellow, c.to_known_color());
}
void test_method_(create_from_know_color_honeydew) {
color c = color::from_known_color(known_color::honeydew);
assert::are_equal(color::from_known_color(known_color::honeydew), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xF0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("honeydew", c.name());
assert::are_equal("color [honeydew]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0FFF0U, c.to_argb());
assert::are_equal(known_color::honeydew, c.to_known_color());
}
void test_method_(create_from_know_color_hot_pink) {
color c = color::from_known_color(known_color::hot_pink);
assert::are_equal(color::from_known_color(known_color::hot_pink), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0xB4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("hot_pink", c.name());
assert::are_equal("color [hot_pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF69B4U, c.to_argb());
assert::are_equal(known_color::hot_pink, c.to_known_color());
}
void test_method_(create_from_know_color_indian_red) {
color c = color::from_known_color(known_color::indian_red);
assert::are_equal(color::from_known_color(known_color::indian_red), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xCD, c.r());
assert::are_equal(0x5C, c.g());
assert::are_equal(0x5C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("indian_red", c.name());
assert::are_equal("color [indian_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFCD5C5CU, c.to_argb());
assert::are_equal(known_color::indian_red, c.to_known_color());
}
void test_method_(create_from_know_color_indigo) {
color c = color::from_known_color(known_color::indigo);
assert::are_equal(color::from_known_color(known_color::indigo), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x4B, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x82, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("indigo", c.name());
assert::are_equal("color [indigo]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF4B0082U, c.to_argb());
assert::are_equal(known_color::indigo, c.to_known_color());
}
void test_method_(create_from_know_color_ivory) {
color c = color::from_known_color(known_color::ivory);
assert::are_equal(color::from_known_color(known_color::ivory), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xF0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("ivory", c.name());
assert::are_equal("color [ivory]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFFF0U, c.to_argb());
assert::are_equal(known_color::ivory, c.to_known_color());
}
void test_method_(create_from_know_color_khaki) {
color c = color::from_known_color(known_color::khaki);
assert::are_equal(color::from_known_color(known_color::khaki), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xE6, c.g());
assert::are_equal(0x8C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("khaki", c.name());
assert::are_equal("color [khaki]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0E68CU, c.to_argb());
assert::are_equal(known_color::khaki, c.to_known_color());
}
void test_method_(create_from_know_color_lavender) {
color c = color::from_known_color(known_color::lavender);
assert::are_equal(color::from_known_color(known_color::lavender), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xE6, c.r());
assert::are_equal(0xE6, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lavender", c.name());
assert::are_equal("color [lavender]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFE6E6FAU, c.to_argb());
assert::are_equal(known_color::lavender, c.to_known_color());
}
void test_method_(create_from_know_color_lavender_blush) {
color c = color::from_known_color(known_color::lavender_blush);
assert::are_equal(color::from_known_color(known_color::lavender_blush), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xF0, c.g());
assert::are_equal(0xF5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lavender_blush", c.name());
assert::are_equal("color [lavender_blush]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFF0F5U, c.to_argb());
assert::are_equal(known_color::lavender_blush, c.to_known_color());
}
void test_method_(create_from_know_color_lawn_green) {
color c = color::from_known_color(known_color::lawn_green);
assert::are_equal(color::from_known_color(known_color::lawn_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7C, c.r());
assert::are_equal(0xFC, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lawn_green", c.name());
assert::are_equal("color [lawn_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7CFC00U, c.to_argb());
assert::are_equal(known_color::lawn_green, c.to_known_color());
}
void test_method_(create_from_know_color_lemon_chiffon) {
color c = color::from_known_color(known_color::lemon_chiffon);
assert::are_equal(color::from_known_color(known_color::lemon_chiffon), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lemon_chiffon", c.name());
assert::are_equal("color [lemon_chiffon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFACDU, c.to_argb());
assert::are_equal(known_color::lemon_chiffon, c.to_known_color());
}
void test_method_(create_from_know_color_light_blue) {
color c = color::from_known_color(known_color::light_blue);
assert::are_equal(color::from_known_color(known_color::light_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xAD, c.r());
assert::are_equal(0xD8, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_blue", c.name());
assert::are_equal("color [light_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFADD8E6U, c.to_argb());
assert::are_equal(known_color::light_blue, c.to_known_color());
}
void test_method_(create_from_know_color_light_coral) {
color c = color::from_known_color(known_color::light_coral);
assert::are_equal(color::from_known_color(known_color::light_coral), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_coral", c.name());
assert::are_equal("color [light_coral]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF08080U, c.to_argb());
assert::are_equal(known_color::light_coral, c.to_known_color());
}
void test_method_(create_from_know_color_light_cyan) {
color c = color::from_known_color(known_color::light_cyan);
assert::are_equal(color::from_known_color(known_color::light_cyan), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xE0, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_cyan", c.name());
assert::are_equal("color [light_cyan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFE0FFFFU, c.to_argb());
assert::are_equal(known_color::light_cyan, c.to_known_color());
}
void test_method_(create_from_know_color_light_goldenrod_yellow) {
color c = color::from_known_color(known_color::light_goldenrod_yellow);
assert::are_equal(color::from_known_color(known_color::light_goldenrod_yellow), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xD2, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_goldenrod_yellow", c.name());
assert::are_equal("color [light_goldenrod_yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFAFAD2U, c.to_argb());
assert::are_equal(known_color::light_goldenrod_yellow, c.to_known_color());
}
void test_method_(create_from_know_color_light_gray) {
color c = color::from_known_color(known_color::light_gray);
assert::are_equal(color::from_known_color(known_color::light_gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD3, c.r());
assert::are_equal(0xD3, c.g());
assert::are_equal(0xD3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_gray", c.name());
assert::are_equal("color [light_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD3D3D3U, c.to_argb());
assert::are_equal(known_color::light_gray, c.to_known_color());
}
void test_method_(create_from_know_color_light_green) {
color c = color::from_known_color(known_color::light_green);
assert::are_equal(color::from_known_color(known_color::light_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x90, c.r());
assert::are_equal(0xEE, c.g());
assert::are_equal(0x90, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_green", c.name());
assert::are_equal("color [light_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF90EE90U, c.to_argb());
assert::are_equal(known_color::light_green, c.to_known_color());
}
void test_method_(create_from_know_color_light_pink) {
color c = color::from_known_color(known_color::light_pink);
assert::are_equal(color::from_known_color(known_color::light_pink), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xB6, c.g());
assert::are_equal(0xC1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_pink", c.name());
assert::are_equal("color [light_pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFB6C1U, c.to_argb());
assert::are_equal(known_color::light_pink, c.to_known_color());
}
void test_method_(create_from_know_color_light_salmon) {
color c = color::from_known_color(known_color::light_salmon);
assert::are_equal(color::from_known_color(known_color::light_salmon), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xA0, c.g());
assert::are_equal(0x7A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_salmon", c.name());
assert::are_equal("color [light_salmon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFA07AU, c.to_argb());
assert::are_equal(known_color::light_salmon, c.to_known_color());
}
void test_method_(create_from_know_color_light_sea_green) {
color c = color::from_known_color(known_color::light_sea_green);
assert::are_equal(color::from_known_color(known_color::light_sea_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x20, c.r());
assert::are_equal(0xB2, c.g());
assert::are_equal(0xAA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_sea_green", c.name());
assert::are_equal("color [light_sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF20B2AAU, c.to_argb());
assert::are_equal(known_color::light_sea_green, c.to_known_color());
}
void test_method_(create_from_know_color_light_sky_blue) {
color c = color::from_known_color(known_color::light_sky_blue);
assert::are_equal(color::from_known_color(known_color::light_sky_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x87, c.r());
assert::are_equal(0xCE, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_sky_blue", c.name());
assert::are_equal("color [light_sky_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF87CEFAU, c.to_argb());
assert::are_equal(known_color::light_sky_blue, c.to_known_color());
}
void test_method_(create_from_know_color_light_slate_gray) {
color c = color::from_known_color(known_color::light_slate_gray);
assert::are_equal(color::from_known_color(known_color::light_slate_gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x77, c.r());
assert::are_equal(0x88, c.g());
assert::are_equal(0x99, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_slate_gray", c.name());
assert::are_equal("color [light_slate_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF778899U, c.to_argb());
assert::are_equal(known_color::light_slate_gray, c.to_known_color());
}
void test_method_(create_from_know_color_light_steel_blue) {
color c = color::from_known_color(known_color::light_steel_blue);
assert::are_equal(color::from_known_color(known_color::light_steel_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB0, c.r());
assert::are_equal(0xC4, c.g());
assert::are_equal(0xDE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_steel_blue", c.name());
assert::are_equal("color [light_steel_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB0C4DEU, c.to_argb());
assert::are_equal(known_color::light_steel_blue, c.to_known_color());
}
void test_method_(create_from_know_color_light_yellow) {
color c = color::from_known_color(known_color::light_yellow);
assert::are_equal(color::from_known_color(known_color::light_yellow), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xE0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_yellow", c.name());
assert::are_equal("color [light_yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFFE0U, c.to_argb());
assert::are_equal(known_color::light_yellow, c.to_known_color());
}
void test_method_(create_from_know_color_lime) {
color c = color::from_known_color(known_color::lime);
assert::are_equal(color::from_known_color(known_color::lime), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lime", c.name());
assert::are_equal("color [lime]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FF00U, c.to_argb());
assert::are_equal(known_color::lime, c.to_known_color());
}
void test_method_(create_from_know_color_lime_green) {
color c = color::from_known_color(known_color::lime_green);
assert::are_equal(color::from_known_color(known_color::lime_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x32, c.r());
assert::are_equal(0xCD, c.g());
assert::are_equal(0x32, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lime_green", c.name());
assert::are_equal("color [lime_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF32CD32U, c.to_argb());
assert::are_equal(known_color::lime_green, c.to_known_color());
}
void test_method_(create_from_know_color_linen) {
color c = color::from_known_color(known_color::linen);
assert::are_equal(color::from_known_color(known_color::linen), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0xF0, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("linen", c.name());
assert::are_equal("color [linen]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFAF0E6U, c.to_argb());
assert::are_equal(known_color::linen, c.to_known_color());
}
void test_method_(create_from_know_color_magenta) {
color c = color::from_known_color(known_color::magenta);
assert::are_equal(color::from_known_color(known_color::magenta), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("magenta", c.name());
assert::are_equal("color [magenta]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF00FFU, c.to_argb());
assert::are_equal(known_color::magenta, c.to_known_color());
}
void test_method_(create_from_know_color_maroon) {
color c = color::from_known_color(known_color::maroon);
assert::are_equal(color::from_known_color(known_color::maroon), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("maroon", c.name());
assert::are_equal("color [maroon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF800000U, c.to_argb());
assert::are_equal(known_color::maroon, c.to_known_color());
}
void test_method_(create_from_know_color_medium_aquamarine) {
color c = color::from_known_color(known_color::medium_aquamarine);
assert::are_equal(color::from_known_color(known_color::medium_aquamarine), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x66, c.r());
assert::are_equal(0xCD, c.g());
assert::are_equal(0xAA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_aquamarine", c.name());
assert::are_equal("color [medium_aquamarine]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF66CDAAU, c.to_argb());
assert::are_equal(known_color::medium_aquamarine, c.to_known_color());
}
void test_method_(create_from_know_color_medium_blue) {
color c = color::from_known_color(known_color::medium_blue);
assert::are_equal(color::from_known_color(known_color::medium_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_blue", c.name());
assert::are_equal("color [medium_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF0000CDU, c.to_argb());
assert::are_equal(known_color::medium_blue, c.to_known_color());
}
void test_method_(create_from_know_color_medium_orchid) {
color c = color::from_known_color(known_color::medium_orchid);
assert::are_equal(color::from_known_color(known_color::medium_orchid), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xBA, c.r());
assert::are_equal(0x55, c.g());
assert::are_equal(0xD3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_orchid", c.name());
assert::are_equal("color [medium_orchid]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFBA55D3U, c.to_argb());
assert::are_equal(known_color::medium_orchid, c.to_known_color());
}
void test_method_(create_from_know_color_medium_purple) {
color c = color::from_known_color(known_color::medium_purple);
assert::are_equal(color::from_known_color(known_color::medium_purple), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x93, c.r());
assert::are_equal(0x70, c.g());
assert::are_equal(0xDB, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_purple", c.name());
assert::are_equal("color [medium_purple]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF9370DBU, c.to_argb());
assert::are_equal(known_color::medium_purple, c.to_known_color());
}
void test_method_(create_from_know_color_medium_sea_green) {
color c = color::from_known_color(known_color::medium_sea_green);
assert::are_equal(color::from_known_color(known_color::medium_sea_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x3C, c.r());
assert::are_equal(0xB3, c.g());
assert::are_equal(0x71, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_sea_green", c.name());
assert::are_equal("color [medium_sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF3CB371U, c.to_argb());
assert::are_equal(known_color::medium_sea_green, c.to_known_color());
}
void test_method_(create_from_know_color_medium_slate_blue) {
color c = color::from_known_color(known_color::medium_slate_blue);
assert::are_equal(color::from_known_color(known_color::medium_slate_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7B, c.r());
assert::are_equal(0x68, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_slate_blue", c.name());
assert::are_equal("color [medium_slate_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7B68EEU, c.to_argb());
assert::are_equal(known_color::medium_slate_blue, c.to_known_color());
}
void test_method_(create_from_know_color_medium_spring_green) {
color c = color::from_known_color(known_color::medium_spring_green);
assert::are_equal(color::from_known_color(known_color::medium_spring_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0x9A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_spring_green", c.name());
assert::are_equal("color [medium_spring_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FA9AU, c.to_argb());
assert::are_equal(known_color::medium_spring_green, c.to_known_color());
}
void test_method_(create_from_know_color_medium_turquoise) {
color c = color::from_known_color(known_color::medium_turquoise);
assert::are_equal(color::from_known_color(known_color::medium_turquoise), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x48, c.r());
assert::are_equal(0xD1, c.g());
assert::are_equal(0xCC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_turquoise", c.name());
assert::are_equal("color [medium_turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF48D1CCU, c.to_argb());
assert::are_equal(known_color::medium_turquoise, c.to_known_color());
}
void test_method_(create_from_know_color_medium_violet_red) {
color c = color::from_known_color(known_color::medium_violet_red);
assert::are_equal(color::from_known_color(known_color::medium_violet_red), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xC7, c.r());
assert::are_equal(0x15, c.g());
assert::are_equal(0x85, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_violet_red", c.name());
assert::are_equal("color [medium_violet_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFC71585U, c.to_argb());
assert::are_equal(known_color::medium_violet_red, c.to_known_color());
}
void test_method_(create_from_know_color_midnight_blue) {
color c = color::from_known_color(known_color::midnight_blue);
assert::are_equal(color::from_known_color(known_color::midnight_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x19, c.r());
assert::are_equal(0x19, c.g());
assert::are_equal(0x70, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("midnight_blue", c.name());
assert::are_equal("color [midnight_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF191970U, c.to_argb());
assert::are_equal(known_color::midnight_blue, c.to_known_color());
}
void test_method_(create_from_know_color_mint_cream) {
color c = color::from_known_color(known_color::mint_cream);
assert::are_equal(color::from_known_color(known_color::mint_cream), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("mint_cream", c.name());
assert::are_equal("color [mint_cream]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5FFFAU, c.to_argb());
assert::are_equal(known_color::mint_cream, c.to_known_color());
}
void test_method_(create_from_know_color_misty_rose) {
color c = color::from_known_color(known_color::misty_rose);
assert::are_equal(color::from_known_color(known_color::misty_rose), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xE4, c.g());
assert::are_equal(0xE1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("misty_rose", c.name());
assert::are_equal("color [misty_rose]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFE4E1U, c.to_argb());
assert::are_equal(known_color::misty_rose, c.to_known_color());
}
void test_method_(create_from_know_color_moccasin) {
color c = color::from_known_color(known_color::moccasin);
assert::are_equal(color::from_known_color(known_color::moccasin), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xE4, c.g());
assert::are_equal(0xB5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("moccasin", c.name());
assert::are_equal("color [moccasin]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFE4B5U, c.to_argb());
assert::are_equal(known_color::moccasin, c.to_known_color());
}
void test_method_(create_from_know_color_navajo_white) {
color c = color::from_known_color(known_color::navajo_white);
assert::are_equal(color::from_known_color(known_color::navajo_white), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xDE, c.g());
assert::are_equal(0xAD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("navajo_white", c.name());
assert::are_equal("color [navajo_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFDEADU, c.to_argb());
assert::are_equal(known_color::navajo_white, c.to_known_color());
}
void test_method_(create_from_know_color_navy) {
color c = color::from_known_color(known_color::navy);
assert::are_equal(color::from_known_color(known_color::navy), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("navy", c.name());
assert::are_equal("color [navy]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF000080U, c.to_argb());
assert::are_equal(known_color::navy, c.to_known_color());
}
void test_method_(create_from_know_color_old_lace) {
color c = color::from_known_color(known_color::old_lace);
assert::are_equal(color::from_known_color(known_color::old_lace), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFD, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("old_lace", c.name());
assert::are_equal("color [old_lace]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFDF5E6U, c.to_argb());
assert::are_equal(known_color::old_lace, c.to_known_color());
}
void test_method_(create_from_know_color_olive) {
color c = color::from_known_color(known_color::olive);
assert::are_equal(color::from_known_color(known_color::olive), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("olive", c.name());
assert::are_equal("color [olive]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF808000U, c.to_argb());
assert::are_equal(known_color::olive, c.to_known_color());
}
void test_method_(create_from_know_color_olive_drab) {
color c = color::from_known_color(known_color::olive_drab);
assert::are_equal(color::from_known_color(known_color::olive_drab), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x6B, c.r());
assert::are_equal(0x8E, c.g());
assert::are_equal(0x23, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("olive_drab", c.name());
assert::are_equal("color [olive_drab]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF6B8E23U, c.to_argb());
assert::are_equal(known_color::olive_drab, c.to_known_color());
}
void test_method_(create_from_know_color_orange) {
color c = color::from_known_color(known_color::orange);
assert::are_equal(color::from_known_color(known_color::orange), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xA5, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("orange", c.name());
assert::are_equal("color [orange]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFA500U, c.to_argb());
assert::are_equal(known_color::orange, c.to_known_color());
}
void test_method_(create_from_know_color_orange_red) {
color c = color::from_known_color(known_color::orange_red);
assert::are_equal(color::from_known_color(known_color::orange_red), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x45, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("orange_red", c.name());
assert::are_equal("color [orange_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF4500U, c.to_argb());
assert::are_equal(known_color::orange_red, c.to_known_color());
}
void test_method_(create_from_know_color_orchid) {
color c = color::from_known_color(known_color::orchid);
assert::are_equal(color::from_known_color(known_color::orchid), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDA, c.r());
assert::are_equal(0x70, c.g());
assert::are_equal(0xD6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("orchid", c.name());
assert::are_equal("color [orchid]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDA70D6U, c.to_argb());
assert::are_equal(known_color::orchid, c.to_known_color());
}
void test_method_(create_from_know_color_pale_goldenrod) {
color c = color::from_known_color(known_color::pale_goldenrod);
assert::are_equal(color::from_known_color(known_color::pale_goldenrod), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xEE, c.r());
assert::are_equal(0xE8, c.g());
assert::are_equal(0xAA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_goldenrod", c.name());
assert::are_equal("color [pale_goldenrod]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFEEE8AAU, c.to_argb());
assert::are_equal(known_color::pale_goldenrod, c.to_known_color());
}
void test_method_(create_from_know_color_pale_green) {
color c = color::from_known_color(known_color::pale_green);
assert::are_equal(color::from_known_color(known_color::pale_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x98, c.r());
assert::are_equal(0xFB, c.g());
assert::are_equal(0x98, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_green", c.name());
assert::are_equal("color [pale_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF98FB98U, c.to_argb());
assert::are_equal(known_color::pale_green, c.to_known_color());
}
void test_method_(create_from_know_color_pale_turquoise) {
color c = color::from_known_color(known_color::pale_turquoise);
assert::are_equal(color::from_known_color(known_color::pale_turquoise), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xAF, c.r());
assert::are_equal(0xEE, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_turquoise", c.name());
assert::are_equal("color [pale_turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFAFEEEEU, c.to_argb());
assert::are_equal(known_color::pale_turquoise, c.to_known_color());
}
void test_method_(create_from_know_color_pale_violet_red) {
color c = color::from_known_color(known_color::pale_violet_red);
assert::are_equal(color::from_known_color(known_color::pale_violet_red), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDB, c.r());
assert::are_equal(0x70, c.g());
assert::are_equal(0x93, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_violet_red", c.name());
assert::are_equal("color [pale_violet_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDB7093U, c.to_argb());
assert::are_equal(known_color::pale_violet_red, c.to_known_color());
}
void test_method_(create_from_know_color_papaya_whip) {
color c = color::from_known_color(known_color::papaya_whip);
assert::are_equal(color::from_known_color(known_color::papaya_whip), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xEF, c.g());
assert::are_equal(0xD5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("papaya_whip", c.name());
assert::are_equal("color [papaya_whip]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFEFD5U, c.to_argb());
assert::are_equal(known_color::papaya_whip, c.to_known_color());
}
void test_method_(create_from_know_color_peach_puff) {
color c = color::from_known_color(known_color::peach_puff);
assert::are_equal(color::from_known_color(known_color::peach_puff), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xDA, c.g());
assert::are_equal(0xB9, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("peach_puff", c.name());
assert::are_equal("color [peach_puff]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFDAB9U, c.to_argb());
assert::are_equal(known_color::peach_puff, c.to_known_color());
}
void test_method_(create_from_know_color_peru) {
color c = color::from_known_color(known_color::peru);
assert::are_equal(color::from_known_color(known_color::peru), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xCD, c.r());
assert::are_equal(0x85, c.g());
assert::are_equal(0x3F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("peru", c.name());
assert::are_equal("color [peru]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFCD853FU, c.to_argb());
assert::are_equal(known_color::peru, c.to_known_color());
}
void test_method_(create_from_know_color_pink) {
color c = color::from_known_color(known_color::pink);
assert::are_equal(color::from_known_color(known_color::pink), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xC0, c.g());
assert::are_equal(0xCB, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pink", c.name());
assert::are_equal("color [pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFC0CBU, c.to_argb());
assert::are_equal(known_color::pink, c.to_known_color());
}
void test_method_(create_from_know_color_plum) {
color c = color::from_known_color(known_color::plum);
assert::are_equal(color::from_known_color(known_color::plum), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDD, c.r());
assert::are_equal(0xA0, c.g());
assert::are_equal(0xDD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("plum", c.name());
assert::are_equal("color [plum]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDDA0DDU, c.to_argb());
assert::are_equal(known_color::plum, c.to_known_color());
}
void test_method_(create_from_know_color_powder_blue) {
color c = color::from_known_color(known_color::powder_blue);
assert::are_equal(color::from_known_color(known_color::powder_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB0, c.r());
assert::are_equal(0xE0, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("powder_blue", c.name());
assert::are_equal("color [powder_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB0E0E6U, c.to_argb());
assert::are_equal(known_color::powder_blue, c.to_known_color());
}
void test_method_(create_from_know_color_purple) {
color c = color::from_known_color(known_color::purple);
assert::are_equal(color::from_known_color(known_color::purple), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("purple", c.name());
assert::are_equal("color [purple]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF800080U, c.to_argb());
assert::are_equal(known_color::purple, c.to_known_color());
}
void test_method_(create_from_know_color_rebecca_purple) {
color c = color::from_known_color(known_color::rebecca_purple);
assert::are_equal(color::from_known_color(known_color::rebecca_purple), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x66, c.r());
assert::are_equal(0x33, c.g());
assert::are_equal(0x99, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("rebecca_purple", c.name());
assert::are_equal("color [rebecca_purple]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF663399U, c.to_argb());
assert::are_equal(known_color::rebecca_purple, c.to_known_color());
}
void test_method_(create_from_know_color_red) {
color c = color::from_known_color(known_color::red);
assert::are_equal(color::from_known_color(known_color::red), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("red", c.name());
assert::are_equal("color [red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF0000U, c.to_argb());
assert::are_equal(known_color::red, c.to_known_color());
}
void test_method_(create_from_know_color_rosy_brown) {
color c = color::from_known_color(known_color::rosy_brown);
assert::are_equal(color::from_known_color(known_color::rosy_brown), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xBC, c.r());
assert::are_equal(0x8F, c.g());
assert::are_equal(0x8F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("rosy_brown", c.name());
assert::are_equal("color [rosy_brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFBC8F8FU, c.to_argb());
assert::are_equal(known_color::rosy_brown, c.to_known_color());
}
void test_method_(create_from_know_color_royal_blue) {
color c = color::from_known_color(known_color::royal_blue);
assert::are_equal(color::from_known_color(known_color::royal_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x41, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0xE1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("royal_blue", c.name());
assert::are_equal("color [royal_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF4169E1U, c.to_argb());
assert::are_equal(known_color::royal_blue, c.to_known_color());
}
void test_method_(create_from_know_color_saddle_brown) {
color c = color::from_known_color(known_color::saddle_brown);
assert::are_equal(color::from_known_color(known_color::saddle_brown), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8B, c.r());
assert::are_equal(0x45, c.g());
assert::are_equal(0x13, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("saddle_brown", c.name());
assert::are_equal("color [saddle_brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8B4513U, c.to_argb());
assert::are_equal(known_color::saddle_brown, c.to_known_color());
}
void test_method_(create_from_know_color_salmon) {
color c = color::from_known_color(known_color::salmon);
assert::are_equal(color::from_known_color(known_color::salmon), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x72, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("salmon", c.name());
assert::are_equal("color [salmon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFA8072U, c.to_argb());
assert::are_equal(known_color::salmon, c.to_known_color());
}
void test_method_(create_from_know_color_sandy_brown) {
color c = color::from_known_color(known_color::sandy_brown);
assert::are_equal(color::from_known_color(known_color::sandy_brown), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF4, c.r());
assert::are_equal(0xA4, c.g());
assert::are_equal(0x60, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sandy_brown", c.name());
assert::are_equal("color [sandy_brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF4A460U, c.to_argb());
assert::are_equal(known_color::sandy_brown, c.to_known_color());
}
void test_method_(create_from_know_color_sea_green) {
color c = color::from_known_color(known_color::sea_green);
assert::are_equal(color::from_known_color(known_color::sea_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x2E, c.r());
assert::are_equal(0x8B, c.g());
assert::are_equal(0x57, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sea_green", c.name());
assert::are_equal("color [sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF2E8B57U, c.to_argb());
assert::are_equal(known_color::sea_green, c.to_known_color());
}
void test_method_(create_from_know_color_sea_shell) {
color c = color::from_known_color(known_color::sea_shell);
assert::are_equal(color::from_known_color(known_color::sea_shell), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sea_shell", c.name());
assert::are_equal("color [sea_shell]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFF5EEU, c.to_argb());
assert::are_equal(known_color::sea_shell, c.to_known_color());
}
void test_method_(create_from_know_color_sienna) {
color c = color::from_known_color(known_color::sienna);
assert::are_equal(color::from_known_color(known_color::sienna), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xA0, c.r());
assert::are_equal(0x52, c.g());
assert::are_equal(0x2D, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sienna", c.name());
assert::are_equal("color [sienna]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFA0522DU, c.to_argb());
assert::are_equal(known_color::sienna, c.to_known_color());
}
void test_method_(create_from_know_color_silver) {
color c = color::from_known_color(known_color::silver);
assert::are_equal(color::from_known_color(known_color::silver), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xC0, c.r());
assert::are_equal(0xC0, c.g());
assert::are_equal(0xC0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("silver", c.name());
assert::are_equal("color [silver]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFC0C0C0U, c.to_argb());
assert::are_equal(known_color::silver, c.to_known_color());
}
void test_method_(create_from_know_color_sky_blue) {
color c = color::from_known_color(known_color::sky_blue);
assert::are_equal(color::from_known_color(known_color::sky_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x87, c.r());
assert::are_equal(0xCE, c.g());
assert::are_equal(0xEB, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sky_blue", c.name());
assert::are_equal("color [sky_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF87CEEBU, c.to_argb());
assert::are_equal(known_color::sky_blue, c.to_known_color());
}
void test_method_(create_from_know_color_slate_blue) {
color c = color::from_known_color(known_color::slate_blue);
assert::are_equal(color::from_known_color(known_color::slate_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x6A, c.r());
assert::are_equal(0x5A, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("slate_blue", c.name());
assert::are_equal("color [slate_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF6A5ACDU, c.to_argb());
assert::are_equal(known_color::slate_blue, c.to_known_color());
}
void test_method_(create_from_know_color_slate_gray) {
color c = color::from_known_color(known_color::slate_gray);
assert::are_equal(color::from_known_color(known_color::slate_gray), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x70, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x90, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("slate_gray", c.name());
assert::are_equal("color [slate_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF708090U, c.to_argb());
assert::are_equal(known_color::slate_gray, c.to_known_color());
}
void test_method_(create_from_know_color_snow) {
color c = color::from_known_color(known_color::snow);
assert::are_equal(color::from_known_color(known_color::snow), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("snow", c.name());
assert::are_equal("color [snow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFAFAU, c.to_argb());
assert::are_equal(known_color::snow, c.to_known_color());
}
void test_method_(create_from_know_color_spring_green) {
color c = color::from_known_color(known_color::spring_green);
assert::are_equal(color::from_known_color(known_color::spring_green), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x7F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("spring_green", c.name());
assert::are_equal("color [spring_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FF7FU, c.to_argb());
assert::are_equal(known_color::spring_green, c.to_known_color());
}
void test_method_(create_from_know_color_steel_blue) {
color c = color::from_known_color(known_color::steel_blue);
assert::are_equal(color::from_known_color(known_color::steel_blue), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x46, c.r());
assert::are_equal(0x82, c.g());
assert::are_equal(0xB4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("steel_blue", c.name());
assert::are_equal("color [steel_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF4682B4U, c.to_argb());
assert::are_equal(known_color::steel_blue, c.to_known_color());
}
void test_method_(create_from_know_color_tan) {
color c = color::from_known_color(known_color::tan);
assert::are_equal(color::from_known_color(known_color::tan), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD2, c.r());
assert::are_equal(0xB4, c.g());
assert::are_equal(0x8C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("tan", c.name());
assert::are_equal("color [tan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD2B48CU, c.to_argb());
assert::are_equal(known_color::tan, c.to_known_color());
}
void test_method_(create_from_know_color_teal) {
color c = color::from_known_color(known_color::teal);
assert::are_equal(color::from_known_color(known_color::teal), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("teal", c.name());
assert::are_equal("color [teal]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF008080U, c.to_argb());
assert::are_equal(known_color::teal, c.to_known_color());
}
void test_method_(create_from_know_color_thistle) {
color c = color::from_known_color(known_color::thistle);
assert::are_equal(color::from_known_color(known_color::thistle), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD8, c.r());
assert::are_equal(0xBF, c.g());
assert::are_equal(0xD8, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("thistle", c.name());
assert::are_equal("color [thistle]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD8BFD8U, c.to_argb());
assert::are_equal(known_color::thistle, c.to_known_color());
}
void test_method_(create_from_know_color_tomato) {
color c = color::from_known_color(known_color::tomato);
assert::are_equal(color::from_known_color(known_color::tomato), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x63, c.g());
assert::are_equal(0x47, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("tomato", c.name());
assert::are_equal("color [tomato]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF6347U, c.to_argb());
assert::are_equal(known_color::tomato, c.to_known_color());
}
void test_method_(create_from_know_color_turquoise) {
color c = color::from_known_color(known_color::turquoise);
assert::are_equal(color::from_known_color(known_color::turquoise), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x40, c.r());
assert::are_equal(0xE0, c.g());
assert::are_equal(0xD0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("turquoise", c.name());
assert::are_equal("color [turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF40E0D0U, c.to_argb());
assert::are_equal(known_color::turquoise, c.to_known_color());
}
void test_method_(create_from_know_color_violet) {
color c = color::from_known_color(known_color::violet);
assert::are_equal(color::from_known_color(known_color::violet), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xEE, c.r());
assert::are_equal(0x82, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("violet", c.name());
assert::are_equal("color [violet]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFEE82EEU, c.to_argb());
assert::are_equal(known_color::violet, c.to_known_color());
}
void test_method_(create_from_know_color_wheat) {
color c = color::from_known_color(known_color::wheat);
assert::are_equal(color::from_known_color(known_color::wheat), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xDE, c.g());
assert::are_equal(0xB3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("wheat", c.name());
assert::are_equal("color [wheat]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5DEB3U, c.to_argb());
assert::are_equal(known_color::wheat, c.to_known_color());
}
void test_method_(create_from_know_color_white) {
color c = color::from_known_color(known_color::white);
assert::are_equal(color::from_known_color(known_color::white), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("white", c.name());
assert::are_equal("color [white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFFFFU, c.to_argb());
assert::are_equal(known_color::white, c.to_known_color());
}
void test_method_(create_from_know_color_white_smoke) {
color c = color::from_known_color(known_color::white_smoke);
assert::are_equal(color::from_known_color(known_color::white_smoke), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xF5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("white_smoke", c.name());
assert::are_equal("color [white_smoke]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5F5F5U, c.to_argb());
assert::are_equal(known_color::white_smoke, c.to_known_color());
}
void test_method_(create_from_know_color_yellow) {
color c = color::from_known_color(known_color::yellow);
assert::are_equal(color::from_known_color(known_color::yellow), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("yellow", c.name());
assert::are_equal("color [yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFF00U, c.to_argb());
assert::are_equal(known_color::yellow, c.to_known_color());
}
void test_method_(create_from_name_transparent) {
color c = color::from_name("transparent");
assert::are_equal(color::from_name("transparent"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0x00, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("transparent", c.name());
assert::are_equal("color [transparent]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0x00FFFFFFU, c.to_argb());
assert::are_equal(known_color::transparent, c.to_known_color());
}
void test_method_(create_from_name_alice_blue) {
color c = color::from_name("alice_blue");
assert::are_equal(color::from_name("alice_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xF8, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("alice_blue", c.name());
assert::are_equal("color [alice_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0F8FFU, c.to_argb());
assert::are_equal(known_color::alice_blue, c.to_known_color());
}
void test_method_(create_from_name_antique_white) {
color c = color::from_name("antique_white");
assert::are_equal(color::from_name("antique_white"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0xEB, c.g());
assert::are_equal(0xD7, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("antique_white", c.name());
assert::are_equal("color [antique_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFAEBD7U, c.to_argb());
assert::are_equal(known_color::antique_white, c.to_known_color());
}
void test_method_(create_from_name_aqua) {
color c = color::from_name("aqua");
assert::are_equal(color::from_name("aqua"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("aqua", c.name());
assert::are_equal("color [aqua]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FFFFU, c.to_argb());
assert::are_equal(known_color::aqua, c.to_known_color());
}
void test_method_(create_from_name_aquamarine) {
color c = color::from_name("aquamarine");
assert::are_equal(color::from_name("aquamarine"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7F, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xD4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("aquamarine", c.name());
assert::are_equal("color [aquamarine]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7FFFD4U, c.to_argb());
assert::are_equal(known_color::aquamarine, c.to_known_color());
}
void test_method_(create_from_name_azure) {
color c = color::from_name("azure");
assert::are_equal(color::from_name("azure"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("azure", c.name());
assert::are_equal("color [azure]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0FFFFU, c.to_argb());
assert::are_equal(known_color::azure, c.to_known_color());
}
void test_method_(create_from_name_beige) {
color c = color::from_name("beige");
assert::are_equal(color::from_name("beige"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xDC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("beige", c.name());
assert::are_equal("color [beige]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5F5DCU, c.to_argb());
assert::are_equal(known_color::beige, c.to_known_color());
}
void test_method_(create_from_name_bisque) {
color c = color::from_name("bisque");
assert::are_equal(color::from_name("bisque"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xE4, c.g());
assert::are_equal(0xC4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("bisque", c.name());
assert::are_equal("color [bisque]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFE4C4U, c.to_argb());
assert::are_equal(known_color::bisque, c.to_known_color());
}
void test_method_(create_from_name_black) {
color c = color::from_name("black");
assert::are_equal(color::from_name("black"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("black", c.name());
assert::are_equal("color [black]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF000000U, c.to_argb());
assert::are_equal(known_color::black, c.to_known_color());
}
void test_method_(create_from_name_blanched_almond) {
color c = color::from_name("blanched_almond");
assert::are_equal(color::from_name("blanched_almond"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xEB, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("blanched_almond", c.name());
assert::are_equal("color [blanched_almond]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFEBCDU, c.to_argb());
assert::are_equal(known_color::blanched_almond, c.to_known_color());
}
void test_method_(create_from_name_blue) {
color c = color::from_name("blue");
assert::are_equal(color::from_name("blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("blue", c.name());
assert::are_equal("color [blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF0000FFU, c.to_argb());
assert::are_equal(known_color::blue, c.to_known_color());
}
void test_method_(create_from_name_blue_violet) {
color c = color::from_name("blue_violet");
assert::are_equal(color::from_name("blue_violet"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8A, c.r());
assert::are_equal(0x2B, c.g());
assert::are_equal(0xE2, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("blue_violet", c.name());
assert::are_equal("color [blue_violet]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8A2BE2U, c.to_argb());
assert::are_equal(known_color::blue_violet, c.to_known_color());
}
void test_method_(create_from_name_brown) {
color c = color::from_name("brown");
assert::are_equal(color::from_name("brown"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xA5, c.r());
assert::are_equal(0x2A, c.g());
assert::are_equal(0x2A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("brown", c.name());
assert::are_equal("color [brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFA52A2AU, c.to_argb());
assert::are_equal(known_color::brown, c.to_known_color());
}
void test_method_(create_from_name_burly_wood) {
color c = color::from_name("burly_wood");
assert::are_equal(color::from_name("burly_wood"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDE, c.r());
assert::are_equal(0xB8, c.g());
assert::are_equal(0x87, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("burly_wood", c.name());
assert::are_equal("color [burly_wood]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDEB887U, c.to_argb());
assert::are_equal(known_color::burly_wood, c.to_known_color());
}
void test_method_(create_from_name_cadet_blue) {
color c = color::from_name("cadet_blue");
assert::are_equal(color::from_name("cadet_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x5F, c.r());
assert::are_equal(0x9E, c.g());
assert::are_equal(0xA0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cadet_blue", c.name());
assert::are_equal("color [cadet_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF5F9EA0U, c.to_argb());
assert::are_equal(known_color::cadet_blue, c.to_known_color());
}
void test_method_(create_from_name_chartreuse) {
color c = color::from_name("chartreuse");
assert::are_equal(color::from_name("chartreuse"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7F, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("chartreuse", c.name());
assert::are_equal("color [chartreuse]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7FFF00U, c.to_argb());
assert::are_equal(known_color::chartreuse, c.to_known_color());
}
void test_method_(create_from_name_chocolate) {
color c = color::from_name("chocolate");
assert::are_equal(color::from_name("chocolate"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD2, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0x1E, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("chocolate", c.name());
assert::are_equal("color [chocolate]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD2691EU, c.to_argb());
assert::are_equal(known_color::chocolate, c.to_known_color());
}
void test_method_(create_from_name_coral) {
color c = color::from_name("coral");
assert::are_equal(color::from_name("coral"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x7F, c.g());
assert::are_equal(0x50, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("coral", c.name());
assert::are_equal("color [coral]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF7F50U, c.to_argb());
assert::are_equal(known_color::coral, c.to_known_color());
}
void test_method_(create_from_name_cornflower_blue) {
color c = color::from_name("cornflower_blue");
assert::are_equal(color::from_name("cornflower_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x64, c.r());
assert::are_equal(0x95, c.g());
assert::are_equal(0xED, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cornflower_blue", c.name());
assert::are_equal("color [cornflower_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF6495EDU, c.to_argb());
assert::are_equal(known_color::cornflower_blue, c.to_known_color());
}
void test_method_(create_from_name_cornsilk) {
color c = color::from_name("cornsilk");
assert::are_equal(color::from_name("cornsilk"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xF8, c.g());
assert::are_equal(0xDC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cornsilk", c.name());
assert::are_equal("color [cornsilk]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFF8DCU, c.to_argb());
assert::are_equal(known_color::cornsilk, c.to_known_color());
}
void test_method_(create_from_name_crimson) {
color c = color::from_name("crimson");
assert::are_equal(color::from_name("crimson"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDC, c.r());
assert::are_equal(0x14, c.g());
assert::are_equal(0x3C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("crimson", c.name());
assert::are_equal("color [crimson]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDC143CU, c.to_argb());
assert::are_equal(known_color::crimson, c.to_known_color());
}
void test_method_(create_from_name_cyan) {
color c = color::from_name("cyan");
assert::are_equal(color::from_name("cyan"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("cyan", c.name());
assert::are_equal("color [cyan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FFFFU, c.to_argb());
assert::are_equal(known_color::cyan, c.to_known_color());
}
void test_method_(create_from_name_dark_blue) {
color c = color::from_name("dark_blue");
assert::are_equal(color::from_name("dark_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_blue", c.name());
assert::are_equal("color [dark_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00008BU, c.to_argb());
assert::are_equal(known_color::dark_blue, c.to_known_color());
}
void test_method_(create_from_name_dark_cyan) {
color c = color::from_name("dark_cyan");
assert::are_equal(color::from_name("dark_cyan"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x8B, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_cyan", c.name());
assert::are_equal("color [dark_cyan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF008B8BU, c.to_argb());
assert::are_equal(known_color::dark_cyan, c.to_known_color());
}
void test_method_(create_from_name_dark_goldenrod) {
color c = color::from_name("dark_goldenrod");
assert::are_equal(color::from_name("dark_goldenrod"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB8, c.r());
assert::are_equal(0x86, c.g());
assert::are_equal(0x0B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_goldenrod", c.name());
assert::are_equal("color [dark_goldenrod]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB8860BU, c.to_argb());
assert::are_equal(known_color::dark_goldenrod, c.to_known_color());
}
void test_method_(create_from_name_dark_gray) {
color c = color::from_name("dark_gray");
assert::are_equal(color::from_name("dark_gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xA9, c.r());
assert::are_equal(0xA9, c.g());
assert::are_equal(0xA9, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_gray", c.name());
assert::are_equal("color [dark_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFA9A9A9U, c.to_argb());
assert::are_equal(known_color::dark_gray, c.to_known_color());
}
void test_method_(create_from_name_dark_green) {
color c = color::from_name("dark_green");
assert::are_equal(color::from_name("dark_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x64, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_green", c.name());
assert::are_equal("color [dark_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF006400U, c.to_argb());
assert::are_equal(known_color::dark_green, c.to_known_color());
}
void test_method_(create_from_name_dark_khaki) {
color c = color::from_name("dark_khaki");
assert::are_equal(color::from_name("dark_khaki"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xBD, c.r());
assert::are_equal(0xB7, c.g());
assert::are_equal(0x6B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_khaki", c.name());
assert::are_equal("color [dark_khaki]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFBDB76BU, c.to_argb());
assert::are_equal(known_color::dark_khaki, c.to_known_color());
}
void test_method_(create_from_name_dark_magenta) {
color c = color::from_name("dark_magenta");
assert::are_equal(color::from_name("dark_magenta"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8B, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_magenta", c.name());
assert::are_equal("color [dark_magenta]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8B008BU, c.to_argb());
assert::are_equal(known_color::dark_magenta, c.to_known_color());
}
void test_method_(create_from_name_dark_olive_green) {
color c = color::from_name("dark_olive_green");
assert::are_equal(color::from_name("dark_olive_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x55, c.r());
assert::are_equal(0x6B, c.g());
assert::are_equal(0x2F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_olive_green", c.name());
assert::are_equal("color [dark_olive_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF556B2FU, c.to_argb());
assert::are_equal(known_color::dark_olive_green, c.to_known_color());
}
void test_method_(create_from_name_dark_orange) {
color c = color::from_name("dark_orange");
assert::are_equal(color::from_name("dark_orange"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x8C, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_orange", c.name());
assert::are_equal("color [dark_orange]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF8C00U, c.to_argb());
assert::are_equal(known_color::dark_orange, c.to_known_color());
}
void test_method_(create_from_name_dark_orchid) {
color c = color::from_name("dark_orchid");
assert::are_equal(color::from_name("dark_orchid"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x99, c.r());
assert::are_equal(0x32, c.g());
assert::are_equal(0xCC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_orchid", c.name());
assert::are_equal("color [dark_orchid]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF9932CCU, c.to_argb());
assert::are_equal(known_color::dark_orchid, c.to_known_color());
}
void test_method_(create_from_name_dark_red) {
color c = color::from_name("dark_red");
assert::are_equal(color::from_name("dark_red"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8B, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_red", c.name());
assert::are_equal("color [dark_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8B0000U, c.to_argb());
assert::are_equal(known_color::dark_red, c.to_known_color());
}
void test_method_(create_from_name_dark_salmon) {
color c = color::from_name("dark_salmon");
assert::are_equal(color::from_name("dark_salmon"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xE9, c.r());
assert::are_equal(0x96, c.g());
assert::are_equal(0x7A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_salmon", c.name());
assert::are_equal("color [dark_salmon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFE9967AU, c.to_argb());
assert::are_equal(known_color::dark_salmon, c.to_known_color());
}
void test_method_(create_from_name_dark_sea_green) {
color c = color::from_name("dark_sea_green");
assert::are_equal(color::from_name("dark_sea_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8F, c.r());
assert::are_equal(0xBC, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_sea_green", c.name());
assert::are_equal("color [dark_sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8FBC8BU, c.to_argb());
assert::are_equal(known_color::dark_sea_green, c.to_known_color());
}
void test_method_(create_from_name_dark_slate_blue) {
color c = color::from_name("dark_slate_blue");
assert::are_equal(color::from_name("dark_slate_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x48, c.r());
assert::are_equal(0x3D, c.g());
assert::are_equal(0x8B, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_slate_blue", c.name());
assert::are_equal("color [dark_slate_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF483D8BU, c.to_argb());
assert::are_equal(known_color::dark_slate_blue, c.to_known_color());
}
void test_method_(create_from_name_dark_slate_gray) {
color c = color::from_name("dark_slate_gray");
assert::are_equal(color::from_name("dark_slate_gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x2F, c.r());
assert::are_equal(0x4F, c.g());
assert::are_equal(0x4F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_slate_gray", c.name());
assert::are_equal("color [dark_slate_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF2F4F4FU, c.to_argb());
assert::are_equal(known_color::dark_slate_gray, c.to_known_color());
}
void test_method_(create_from_name_dark_turquoise) {
color c = color::from_name("dark_turquoise");
assert::are_equal(color::from_name("dark_turquoise"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xCE, c.g());
assert::are_equal(0xD1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_turquoise", c.name());
assert::are_equal("color [dark_turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00CED1U, c.to_argb());
assert::are_equal(known_color::dark_turquoise, c.to_known_color());
}
void test_method_(create_from_name_dark_violet) {
color c = color::from_name("dark_violet");
assert::are_equal(color::from_name("dark_violet"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x94, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xD3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dark_violet", c.name());
assert::are_equal("color [dark_violet]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF9400D3U, c.to_argb());
assert::are_equal(known_color::dark_violet, c.to_known_color());
}
void test_method_(create_from_name_deep_pink) {
color c = color::from_name("deep_pink");
assert::are_equal(color::from_name("deep_pink"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x14, c.g());
assert::are_equal(0x93, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("deep_pink", c.name());
assert::are_equal("color [deep_pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF1493U, c.to_argb());
assert::are_equal(known_color::deep_pink, c.to_known_color());
}
void test_method_(create_from_name_deep_sky_blue) {
color c = color::from_name("deep_sky_blue");
assert::are_equal(color::from_name("deep_sky_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xBF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("deep_sky_blue", c.name());
assert::are_equal("color [deep_sky_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00BFFFU, c.to_argb());
assert::are_equal(known_color::deep_sky_blue, c.to_known_color());
}
void test_method_(create_from_name_dim_gray) {
color c = color::from_name("dim_gray");
assert::are_equal(color::from_name("dim_gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x69, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0x69, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dim_gray", c.name());
assert::are_equal("color [dim_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF696969U, c.to_argb());
assert::are_equal(known_color::dim_gray, c.to_known_color());
}
void test_method_(create_from_name_dodger_blue) {
color c = color::from_name("dodger_blue");
assert::are_equal(color::from_name("dodger_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x1E, c.r());
assert::are_equal(0x90, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("dodger_blue", c.name());
assert::are_equal("color [dodger_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF1E90FFU, c.to_argb());
assert::are_equal(known_color::dodger_blue, c.to_known_color());
}
void test_method_(create_from_name_firebrick) {
color c = color::from_name("firebrick");
assert::are_equal(color::from_name("firebrick"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB2, c.r());
assert::are_equal(0x22, c.g());
assert::are_equal(0x22, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("firebrick", c.name());
assert::are_equal("color [firebrick]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB22222U, c.to_argb());
assert::are_equal(known_color::firebrick, c.to_known_color());
}
void test_method_(create_from_name_floral_white) {
color c = color::from_name("floral_white");
assert::are_equal(color::from_name("floral_white"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xF0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("floral_white", c.name());
assert::are_equal("color [floral_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFAF0U, c.to_argb());
assert::are_equal(known_color::floral_white, c.to_known_color());
}
void test_method_(create_from_name_forest_green) {
color c = color::from_name("forest_green");
assert::are_equal(color::from_name("forest_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x22, c.r());
assert::are_equal(0x8B, c.g());
assert::are_equal(0x22, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("forest_green", c.name());
assert::are_equal("color [forest_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF228B22U, c.to_argb());
assert::are_equal(known_color::forest_green, c.to_known_color());
}
void test_method_(create_from_name_fuchsia) {
color c = color::from_name("fuchsia");
assert::are_equal(color::from_name("fuchsia"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("fuchsia", c.name());
assert::are_equal("color [fuchsia]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF00FFU, c.to_argb());
assert::are_equal(known_color::fuchsia, c.to_known_color());
}
void test_method_(create_from_name_gainsboro) {
color c = color::from_name("gainsboro");
assert::are_equal(color::from_name("gainsboro"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDC, c.r());
assert::are_equal(0xDC, c.g());
assert::are_equal(0xDC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("gainsboro", c.name());
assert::are_equal("color [gainsboro]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDCDCDCU, c.to_argb());
assert::are_equal(known_color::gainsboro, c.to_known_color());
}
void test_method_(create_from_name_ghost_white) {
color c = color::from_name("ghost_white");
assert::are_equal(color::from_name("ghost_white"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF8, c.r());
assert::are_equal(0xF8, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("ghost_white", c.name());
assert::are_equal("color [ghost_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF8F8FFU, c.to_argb());
assert::are_equal(known_color::ghost_white, c.to_known_color());
}
void test_method_(create_from_name_gold) {
color c = color::from_name("gold");
assert::are_equal(color::from_name("gold"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xD7, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("gold", c.name());
assert::are_equal("color [gold]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFD700U, c.to_argb());
assert::are_equal(known_color::gold, c.to_known_color());
}
void test_method_(create_from_name_goldenrod) {
color c = color::from_name("goldenrod");
assert::are_equal(color::from_name("goldenrod"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDA, c.r());
assert::are_equal(0xA5, c.g());
assert::are_equal(0x20, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("goldenrod", c.name());
assert::are_equal("color [goldenrod]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDAA520U, c.to_argb());
assert::are_equal(known_color::goldenrod, c.to_known_color());
}
void test_method_(create_from_name_gray) {
color c = color::from_name("gray");
assert::are_equal(color::from_name("gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("gray", c.name());
assert::are_equal("color [gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF808080U, c.to_argb());
assert::are_equal(known_color::gray, c.to_known_color());
}
void test_method_(create_from_name_green) {
color c = color::from_name("green");
assert::are_equal(color::from_name("green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("green", c.name());
assert::are_equal("color [green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF008000U, c.to_argb());
assert::are_equal(known_color::green, c.to_known_color());
}
void test_method_(create_from_name_green_yellow) {
color c = color::from_name("green_yellow");
assert::are_equal(color::from_name("green_yellow"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xAD, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x2F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("green_yellow", c.name());
assert::are_equal("color [green_yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFADFF2FU, c.to_argb());
assert::are_equal(known_color::green_yellow, c.to_known_color());
}
void test_method_(create_from_name_honeydew) {
color c = color::from_name("honeydew");
assert::are_equal(color::from_name("honeydew"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xF0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("honeydew", c.name());
assert::are_equal("color [honeydew]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0FFF0U, c.to_argb());
assert::are_equal(known_color::honeydew, c.to_known_color());
}
void test_method_(create_from_name_hot_pink) {
color c = color::from_name("hot_pink");
assert::are_equal(color::from_name("hot_pink"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0xB4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("hot_pink", c.name());
assert::are_equal("color [hot_pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF69B4U, c.to_argb());
assert::are_equal(known_color::hot_pink, c.to_known_color());
}
void test_method_(create_from_name_indian_red) {
color c = color::from_name("indian_red");
assert::are_equal(color::from_name("indian_red"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xCD, c.r());
assert::are_equal(0x5C, c.g());
assert::are_equal(0x5C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("indian_red", c.name());
assert::are_equal("color [indian_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFCD5C5CU, c.to_argb());
assert::are_equal(known_color::indian_red, c.to_known_color());
}
void test_method_(create_from_name_indigo) {
color c = color::from_name("indigo");
assert::are_equal(color::from_name("indigo"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x4B, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x82, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("indigo", c.name());
assert::are_equal("color [indigo]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF4B0082U, c.to_argb());
assert::are_equal(known_color::indigo, c.to_known_color());
}
void test_method_(create_from_name_ivory) {
color c = color::from_name("ivory");
assert::are_equal(color::from_name("ivory"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xF0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("ivory", c.name());
assert::are_equal("color [ivory]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFFF0U, c.to_argb());
assert::are_equal(known_color::ivory, c.to_known_color());
}
void test_method_(create_from_name_khaki) {
color c = color::from_name("khaki");
assert::are_equal(color::from_name("khaki"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0xE6, c.g());
assert::are_equal(0x8C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("khaki", c.name());
assert::are_equal("color [khaki]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF0E68CU, c.to_argb());
assert::are_equal(known_color::khaki, c.to_known_color());
}
void test_method_(create_from_name_lavender) {
color c = color::from_name("lavender");
assert::are_equal(color::from_name("lavender"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xE6, c.r());
assert::are_equal(0xE6, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lavender", c.name());
assert::are_equal("color [lavender]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFE6E6FAU, c.to_argb());
assert::are_equal(known_color::lavender, c.to_known_color());
}
void test_method_(create_from_name_lavender_blush) {
color c = color::from_name("lavender_blush");
assert::are_equal(color::from_name("lavender_blush"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xF0, c.g());
assert::are_equal(0xF5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lavender_blush", c.name());
assert::are_equal("color [lavender_blush]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFF0F5U, c.to_argb());
assert::are_equal(known_color::lavender_blush, c.to_known_color());
}
void test_method_(create_from_name_lawn_green) {
color c = color::from_name("lawn_green");
assert::are_equal(color::from_name("lawn_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7C, c.r());
assert::are_equal(0xFC, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lawn_green", c.name());
assert::are_equal("color [lawn_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7CFC00U, c.to_argb());
assert::are_equal(known_color::lawn_green, c.to_known_color());
}
void test_method_(create_from_name_lemon_chiffon) {
color c = color::from_name("lemon_chiffon");
assert::are_equal(color::from_name("lemon_chiffon"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lemon_chiffon", c.name());
assert::are_equal("color [lemon_chiffon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFACDU, c.to_argb());
assert::are_equal(known_color::lemon_chiffon, c.to_known_color());
}
void test_method_(create_from_name_light_blue) {
color c = color::from_name("light_blue");
assert::are_equal(color::from_name("light_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xAD, c.r());
assert::are_equal(0xD8, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_blue", c.name());
assert::are_equal("color [light_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFADD8E6U, c.to_argb());
assert::are_equal(known_color::light_blue, c.to_known_color());
}
void test_method_(create_from_name_light_coral) {
color c = color::from_name("light_coral");
assert::are_equal(color::from_name("light_coral"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF0, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_coral", c.name());
assert::are_equal("color [light_coral]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF08080U, c.to_argb());
assert::are_equal(known_color::light_coral, c.to_known_color());
}
void test_method_(create_from_name_light_cyan) {
color c = color::from_name("light_cyan");
assert::are_equal(color::from_name("light_cyan"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xE0, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_cyan", c.name());
assert::are_equal("color [light_cyan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFE0FFFFU, c.to_argb());
assert::are_equal(known_color::light_cyan, c.to_known_color());
}
void test_method_(create_from_name_light_goldenrod_yellow) {
color c = color::from_name("light_goldenrod_yellow");
assert::are_equal(color::from_name("light_goldenrod_yellow"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xD2, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_goldenrod_yellow", c.name());
assert::are_equal("color [light_goldenrod_yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFAFAD2U, c.to_argb());
assert::are_equal(known_color::light_goldenrod_yellow, c.to_known_color());
}
void test_method_(create_from_name_light_gray) {
color c = color::from_name("light_gray");
assert::are_equal(color::from_name("light_gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD3, c.r());
assert::are_equal(0xD3, c.g());
assert::are_equal(0xD3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_gray", c.name());
assert::are_equal("color [light_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD3D3D3U, c.to_argb());
assert::are_equal(known_color::light_gray, c.to_known_color());
}
void test_method_(create_from_name_light_green) {
color c = color::from_name("light_green");
assert::are_equal(color::from_name("light_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x90, c.r());
assert::are_equal(0xEE, c.g());
assert::are_equal(0x90, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_green", c.name());
assert::are_equal("color [light_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF90EE90U, c.to_argb());
assert::are_equal(known_color::light_green, c.to_known_color());
}
void test_method_(create_from_name_light_pink) {
color c = color::from_name("light_pink");
assert::are_equal(color::from_name("light_pink"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xB6, c.g());
assert::are_equal(0xC1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_pink", c.name());
assert::are_equal("color [light_pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFB6C1U, c.to_argb());
assert::are_equal(known_color::light_pink, c.to_known_color());
}
void test_method_(create_from_name_light_salmon) {
color c = color::from_name("light_salmon");
assert::are_equal(color::from_name("light_salmon"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xA0, c.g());
assert::are_equal(0x7A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_salmon", c.name());
assert::are_equal("color [light_salmon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFA07AU, c.to_argb());
assert::are_equal(known_color::light_salmon, c.to_known_color());
}
void test_method_(create_from_name_light_sea_green) {
color c = color::from_name("light_sea_green");
assert::are_equal(color::from_name("light_sea_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x20, c.r());
assert::are_equal(0xB2, c.g());
assert::are_equal(0xAA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_sea_green", c.name());
assert::are_equal("color [light_sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF20B2AAU, c.to_argb());
assert::are_equal(known_color::light_sea_green, c.to_known_color());
}
void test_method_(create_from_name_light_sky_blue) {
color c = color::from_name("light_sky_blue");
assert::are_equal(color::from_name("light_sky_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x87, c.r());
assert::are_equal(0xCE, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_sky_blue", c.name());
assert::are_equal("color [light_sky_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF87CEFAU, c.to_argb());
assert::are_equal(known_color::light_sky_blue, c.to_known_color());
}
void test_method_(create_from_name_light_slate_gray) {
color c = color::from_name("light_slate_gray");
assert::are_equal(color::from_name("light_slate_gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x77, c.r());
assert::are_equal(0x88, c.g());
assert::are_equal(0x99, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_slate_gray", c.name());
assert::are_equal("color [light_slate_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF778899U, c.to_argb());
assert::are_equal(known_color::light_slate_gray, c.to_known_color());
}
void test_method_(create_from_name_light_steel_blue) {
color c = color::from_name("light_steel_blue");
assert::are_equal(color::from_name("light_steel_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB0, c.r());
assert::are_equal(0xC4, c.g());
assert::are_equal(0xDE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_steel_blue", c.name());
assert::are_equal("color [light_steel_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB0C4DEU, c.to_argb());
assert::are_equal(known_color::light_steel_blue, c.to_known_color());
}
void test_method_(create_from_name_light_yellow) {
color c = color::from_name("light_yellow");
assert::are_equal(color::from_name("light_yellow"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xE0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("light_yellow", c.name());
assert::are_equal("color [light_yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFFE0U, c.to_argb());
assert::are_equal(known_color::light_yellow, c.to_known_color());
}
void test_method_(create_from_name_lime) {
color c = color::from_name("lime");
assert::are_equal(color::from_name("lime"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lime", c.name());
assert::are_equal("color [lime]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FF00U, c.to_argb());
assert::are_equal(known_color::lime, c.to_known_color());
}
void test_method_(create_from_name_lime_green) {
color c = color::from_name("lime_green");
assert::are_equal(color::from_name("lime_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x32, c.r());
assert::are_equal(0xCD, c.g());
assert::are_equal(0x32, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("lime_green", c.name());
assert::are_equal("color [lime_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF32CD32U, c.to_argb());
assert::are_equal(known_color::lime_green, c.to_known_color());
}
void test_method_(create_from_name_linen) {
color c = color::from_name("linen");
assert::are_equal(color::from_name("linen"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0xF0, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("linen", c.name());
assert::are_equal("color [linen]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFAF0E6U, c.to_argb());
assert::are_equal(known_color::linen, c.to_known_color());
}
void test_method_(create_from_name_magenta) {
color c = color::from_name("magenta");
assert::are_equal(color::from_name("magenta"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("magenta", c.name());
assert::are_equal("color [magenta]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF00FFU, c.to_argb());
assert::are_equal(known_color::magenta, c.to_known_color());
}
void test_method_(create_from_name_maroon) {
color c = color::from_name("maroon");
assert::are_equal(color::from_name("maroon"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("maroon", c.name());
assert::are_equal("color [maroon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF800000U, c.to_argb());
assert::are_equal(known_color::maroon, c.to_known_color());
}
void test_method_(create_from_name_medium_aquamarine) {
color c = color::from_name("medium_aquamarine");
assert::are_equal(color::from_name("medium_aquamarine"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x66, c.r());
assert::are_equal(0xCD, c.g());
assert::are_equal(0xAA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_aquamarine", c.name());
assert::are_equal("color [medium_aquamarine]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF66CDAAU, c.to_argb());
assert::are_equal(known_color::medium_aquamarine, c.to_known_color());
}
void test_method_(create_from_name_medium_blue) {
color c = color::from_name("medium_blue");
assert::are_equal(color::from_name("medium_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_blue", c.name());
assert::are_equal("color [medium_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF0000CDU, c.to_argb());
assert::are_equal(known_color::medium_blue, c.to_known_color());
}
void test_method_(create_from_name_medium_orchid) {
color c = color::from_name("medium_orchid");
assert::are_equal(color::from_name("medium_orchid"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xBA, c.r());
assert::are_equal(0x55, c.g());
assert::are_equal(0xD3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_orchid", c.name());
assert::are_equal("color [medium_orchid]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFBA55D3U, c.to_argb());
assert::are_equal(known_color::medium_orchid, c.to_known_color());
}
void test_method_(create_from_name_medium_purple) {
color c = color::from_name("medium_purple");
assert::are_equal(color::from_name("medium_purple"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x93, c.r());
assert::are_equal(0x70, c.g());
assert::are_equal(0xDB, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_purple", c.name());
assert::are_equal("color [medium_purple]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF9370DBU, c.to_argb());
assert::are_equal(known_color::medium_purple, c.to_known_color());
}
void test_method_(create_from_name_medium_sea_green) {
color c = color::from_name("medium_sea_green");
assert::are_equal(color::from_name("medium_sea_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x3C, c.r());
assert::are_equal(0xB3, c.g());
assert::are_equal(0x71, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_sea_green", c.name());
assert::are_equal("color [medium_sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF3CB371U, c.to_argb());
assert::are_equal(known_color::medium_sea_green, c.to_known_color());
}
void test_method_(create_from_name_medium_slate_blue) {
color c = color::from_name("medium_slate_blue");
assert::are_equal(color::from_name("medium_slate_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x7B, c.r());
assert::are_equal(0x68, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_slate_blue", c.name());
assert::are_equal("color [medium_slate_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF7B68EEU, c.to_argb());
assert::are_equal(known_color::medium_slate_blue, c.to_known_color());
}
void test_method_(create_from_name_medium_spring_green) {
color c = color::from_name("medium_spring_green");
assert::are_equal(color::from_name("medium_spring_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0x9A, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_spring_green", c.name());
assert::are_equal("color [medium_spring_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FA9AU, c.to_argb());
assert::are_equal(known_color::medium_spring_green, c.to_known_color());
}
void test_method_(create_from_name_medium_turquoise) {
color c = color::from_name("medium_turquoise");
assert::are_equal(color::from_name("medium_turquoise"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x48, c.r());
assert::are_equal(0xD1, c.g());
assert::are_equal(0xCC, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_turquoise", c.name());
assert::are_equal("color [medium_turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF48D1CCU, c.to_argb());
assert::are_equal(known_color::medium_turquoise, c.to_known_color());
}
void test_method_(create_from_name_medium_violet_red) {
color c = color::from_name("medium_violet_red");
assert::are_equal(color::from_name("medium_violet_red"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xC7, c.r());
assert::are_equal(0x15, c.g());
assert::are_equal(0x85, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("medium_violet_red", c.name());
assert::are_equal("color [medium_violet_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFC71585U, c.to_argb());
assert::are_equal(known_color::medium_violet_red, c.to_known_color());
}
void test_method_(create_from_name_midnight_blue) {
color c = color::from_name("midnight_blue");
assert::are_equal(color::from_name("midnight_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x19, c.r());
assert::are_equal(0x19, c.g());
assert::are_equal(0x70, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("midnight_blue", c.name());
assert::are_equal("color [midnight_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF191970U, c.to_argb());
assert::are_equal(known_color::midnight_blue, c.to_known_color());
}
void test_method_(create_from_name_mint_cream) {
color c = color::from_name("mint_cream");
assert::are_equal(color::from_name("mint_cream"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("mint_cream", c.name());
assert::are_equal("color [mint_cream]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5FFFAU, c.to_argb());
assert::are_equal(known_color::mint_cream, c.to_known_color());
}
void test_method_(create_from_name_misty_rose) {
color c = color::from_name("misty_rose");
assert::are_equal(color::from_name("misty_rose"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xE4, c.g());
assert::are_equal(0xE1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("misty_rose", c.name());
assert::are_equal("color [misty_rose]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFE4E1U, c.to_argb());
assert::are_equal(known_color::misty_rose, c.to_known_color());
}
void test_method_(create_from_name_moccasin) {
color c = color::from_name("moccasin");
assert::are_equal(color::from_name("moccasin"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xE4, c.g());
assert::are_equal(0xB5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("moccasin", c.name());
assert::are_equal("color [moccasin]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFE4B5U, c.to_argb());
assert::are_equal(known_color::moccasin, c.to_known_color());
}
void test_method_(create_from_name_navajo_white) {
color c = color::from_name("navajo_white");
assert::are_equal(color::from_name("navajo_white"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xDE, c.g());
assert::are_equal(0xAD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("navajo_white", c.name());
assert::are_equal("color [navajo_white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFDEADU, c.to_argb());
assert::are_equal(known_color::navajo_white, c.to_known_color());
}
void test_method_(create_from_name_navy) {
color c = color::from_name("navy");
assert::are_equal(color::from_name("navy"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("navy", c.name());
assert::are_equal("color [navy]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF000080U, c.to_argb());
assert::are_equal(known_color::navy, c.to_known_color());
}
void test_method_(create_from_name_old_lace) {
color c = color::from_name("old_lace");
assert::are_equal(color::from_name("old_lace"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFD, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("old_lace", c.name());
assert::are_equal("color [old_lace]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFDF5E6U, c.to_argb());
assert::are_equal(known_color::old_lace, c.to_known_color());
}
void test_method_(create_from_name_olive) {
color c = color::from_name("olive");
assert::are_equal(color::from_name("olive"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("olive", c.name());
assert::are_equal("color [olive]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF808000U, c.to_argb());
assert::are_equal(known_color::olive, c.to_known_color());
}
void test_method_(create_from_name_olive_drab) {
color c = color::from_name("olive_drab");
assert::are_equal(color::from_name("olive_drab"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x6B, c.r());
assert::are_equal(0x8E, c.g());
assert::are_equal(0x23, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("olive_drab", c.name());
assert::are_equal("color [olive_drab]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF6B8E23U, c.to_argb());
assert::are_equal(known_color::olive_drab, c.to_known_color());
}
void test_method_(create_from_name_orange) {
color c = color::from_name("orange");
assert::are_equal(color::from_name("orange"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xA5, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("orange", c.name());
assert::are_equal("color [orange]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFA500U, c.to_argb());
assert::are_equal(known_color::orange, c.to_known_color());
}
void test_method_(create_from_name_orange_red) {
color c = color::from_name("orange_red");
assert::are_equal(color::from_name("orange_red"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x45, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("orange_red", c.name());
assert::are_equal("color [orange_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF4500U, c.to_argb());
assert::are_equal(known_color::orange_red, c.to_known_color());
}
void test_method_(create_from_name_orchid) {
color c = color::from_name("orchid");
assert::are_equal(color::from_name("orchid"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDA, c.r());
assert::are_equal(0x70, c.g());
assert::are_equal(0xD6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("orchid", c.name());
assert::are_equal("color [orchid]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDA70D6U, c.to_argb());
assert::are_equal(known_color::orchid, c.to_known_color());
}
void test_method_(create_from_name_pale_goldenrod) {
color c = color::from_name("pale_goldenrod");
assert::are_equal(color::from_name("pale_goldenrod"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xEE, c.r());
assert::are_equal(0xE8, c.g());
assert::are_equal(0xAA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_goldenrod", c.name());
assert::are_equal("color [pale_goldenrod]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFEEE8AAU, c.to_argb());
assert::are_equal(known_color::pale_goldenrod, c.to_known_color());
}
void test_method_(create_from_name_pale_green) {
color c = color::from_name("pale_green");
assert::are_equal(color::from_name("pale_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x98, c.r());
assert::are_equal(0xFB, c.g());
assert::are_equal(0x98, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_green", c.name());
assert::are_equal("color [pale_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF98FB98U, c.to_argb());
assert::are_equal(known_color::pale_green, c.to_known_color());
}
void test_method_(create_from_name_pale_turquoise) {
color c = color::from_name("pale_turquoise");
assert::are_equal(color::from_name("pale_turquoise"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xAF, c.r());
assert::are_equal(0xEE, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_turquoise", c.name());
assert::are_equal("color [pale_turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFAFEEEEU, c.to_argb());
assert::are_equal(known_color::pale_turquoise, c.to_known_color());
}
void test_method_(create_from_name_pale_violet_red) {
color c = color::from_name("pale_violet_red");
assert::are_equal(color::from_name("pale_violet_red"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDB, c.r());
assert::are_equal(0x70, c.g());
assert::are_equal(0x93, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pale_violet_red", c.name());
assert::are_equal("color [pale_violet_red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDB7093U, c.to_argb());
assert::are_equal(known_color::pale_violet_red, c.to_known_color());
}
void test_method_(create_from_name_papaya_whip) {
color c = color::from_name("papaya_whip");
assert::are_equal(color::from_name("papaya_whip"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xEF, c.g());
assert::are_equal(0xD5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("papaya_whip", c.name());
assert::are_equal("color [papaya_whip]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFEFD5U, c.to_argb());
assert::are_equal(known_color::papaya_whip, c.to_known_color());
}
void test_method_(create_from_name_peach_puff) {
color c = color::from_name("peach_puff");
assert::are_equal(color::from_name("peach_puff"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xDA, c.g());
assert::are_equal(0xB9, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("peach_puff", c.name());
assert::are_equal("color [peach_puff]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFDAB9U, c.to_argb());
assert::are_equal(known_color::peach_puff, c.to_known_color());
}
void test_method_(create_from_name_peru) {
color c = color::from_name("peru");
assert::are_equal(color::from_name("peru"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xCD, c.r());
assert::are_equal(0x85, c.g());
assert::are_equal(0x3F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("peru", c.name());
assert::are_equal("color [peru]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFCD853FU, c.to_argb());
assert::are_equal(known_color::peru, c.to_known_color());
}
void test_method_(create_from_name_pink) {
color c = color::from_name("pink");
assert::are_equal(color::from_name("pink"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xC0, c.g());
assert::are_equal(0xCB, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("pink", c.name());
assert::are_equal("color [pink]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFC0CBU, c.to_argb());
assert::are_equal(known_color::pink, c.to_known_color());
}
void test_method_(create_from_name_plum) {
color c = color::from_name("plum");
assert::are_equal(color::from_name("plum"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xDD, c.r());
assert::are_equal(0xA0, c.g());
assert::are_equal(0xDD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("plum", c.name());
assert::are_equal("color [plum]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFDDA0DDU, c.to_argb());
assert::are_equal(known_color::plum, c.to_known_color());
}
void test_method_(create_from_name_powder_blue) {
color c = color::from_name("powder_blue");
assert::are_equal(color::from_name("powder_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xB0, c.r());
assert::are_equal(0xE0, c.g());
assert::are_equal(0xE6, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("powder_blue", c.name());
assert::are_equal("color [powder_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFB0E0E6U, c.to_argb());
assert::are_equal(known_color::powder_blue, c.to_known_color());
}
void test_method_(create_from_name_purple) {
color c = color::from_name("purple");
assert::are_equal(color::from_name("purple"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x80, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("purple", c.name());
assert::are_equal("color [purple]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF800080U, c.to_argb());
assert::are_equal(known_color::purple, c.to_known_color());
}
void test_method_(create_from_name_rebecca_purple) {
color c = color::from_name("rebecca_purple");
assert::are_equal(color::from_name("rebecca_purple"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x66, c.r());
assert::are_equal(0x33, c.g());
assert::are_equal(0x99, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("rebecca_purple", c.name());
assert::are_equal("color [rebecca_purple]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF663399U, c.to_argb());
assert::are_equal(known_color::rebecca_purple, c.to_known_color());
}
void test_method_(create_from_name_red) {
color c = color::from_name("red");
assert::are_equal(color::from_name("red"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x00, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("red", c.name());
assert::are_equal("color [red]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF0000U, c.to_argb());
assert::are_equal(known_color::red, c.to_known_color());
}
void test_method_(create_from_name_rosy_brown) {
color c = color::from_name("rosy_brown");
assert::are_equal(color::from_name("rosy_brown"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xBC, c.r());
assert::are_equal(0x8F, c.g());
assert::are_equal(0x8F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("rosy_brown", c.name());
assert::are_equal("color [rosy_brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFBC8F8FU, c.to_argb());
assert::are_equal(known_color::rosy_brown, c.to_known_color());
}
void test_method_(create_from_name_royal_blue) {
color c = color::from_name("royal_blue");
assert::are_equal(color::from_name("royal_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x41, c.r());
assert::are_equal(0x69, c.g());
assert::are_equal(0xE1, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("royal_blue", c.name());
assert::are_equal("color [royal_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF4169E1U, c.to_argb());
assert::are_equal(known_color::royal_blue, c.to_known_color());
}
void test_method_(create_from_name_saddle_brown) {
color c = color::from_name("saddle_brown");
assert::are_equal(color::from_name("saddle_brown"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x8B, c.r());
assert::are_equal(0x45, c.g());
assert::are_equal(0x13, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("saddle_brown", c.name());
assert::are_equal("color [saddle_brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF8B4513U, c.to_argb());
assert::are_equal(known_color::saddle_brown, c.to_known_color());
}
void test_method_(create_from_name_salmon) {
color c = color::from_name("salmon");
assert::are_equal(color::from_name("salmon"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFA, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x72, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("salmon", c.name());
assert::are_equal("color [salmon]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFA8072U, c.to_argb());
assert::are_equal(known_color::salmon, c.to_known_color());
}
void test_method_(create_from_name_sandy_brown) {
color c = color::from_name("sandy_brown");
assert::are_equal(color::from_name("sandy_brown"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF4, c.r());
assert::are_equal(0xA4, c.g());
assert::are_equal(0x60, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sandy_brown", c.name());
assert::are_equal("color [sandy_brown]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF4A460U, c.to_argb());
assert::are_equal(known_color::sandy_brown, c.to_known_color());
}
void test_method_(create_from_name_sea_green) {
color c = color::from_name("sea_green");
assert::are_equal(color::from_name("sea_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x2E, c.r());
assert::are_equal(0x8B, c.g());
assert::are_equal(0x57, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sea_green", c.name());
assert::are_equal("color [sea_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF2E8B57U, c.to_argb());
assert::are_equal(known_color::sea_green, c.to_known_color());
}
void test_method_(create_from_name_sea_shell) {
color c = color::from_name("sea_shell");
assert::are_equal(color::from_name("sea_shell"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sea_shell", c.name());
assert::are_equal("color [sea_shell]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFF5EEU, c.to_argb());
assert::are_equal(known_color::sea_shell, c.to_known_color());
}
void test_method_(create_from_name_sienna) {
color c = color::from_name("sienna");
assert::are_equal(color::from_name("sienna"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xA0, c.r());
assert::are_equal(0x52, c.g());
assert::are_equal(0x2D, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sienna", c.name());
assert::are_equal("color [sienna]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFA0522DU, c.to_argb());
assert::are_equal(known_color::sienna, c.to_known_color());
}
void test_method_(create_from_name_silver) {
color c = color::from_name("silver");
assert::are_equal(color::from_name("silver"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xC0, c.r());
assert::are_equal(0xC0, c.g());
assert::are_equal(0xC0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("silver", c.name());
assert::are_equal("color [silver]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFC0C0C0U, c.to_argb());
assert::are_equal(known_color::silver, c.to_known_color());
}
void test_method_(create_from_name_sky_blue) {
color c = color::from_name("sky_blue");
assert::are_equal(color::from_name("sky_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x87, c.r());
assert::are_equal(0xCE, c.g());
assert::are_equal(0xEB, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("sky_blue", c.name());
assert::are_equal("color [sky_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF87CEEBU, c.to_argb());
assert::are_equal(known_color::sky_blue, c.to_known_color());
}
void test_method_(create_from_name_slate_blue) {
color c = color::from_name("slate_blue");
assert::are_equal(color::from_name("slate_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x6A, c.r());
assert::are_equal(0x5A, c.g());
assert::are_equal(0xCD, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("slate_blue", c.name());
assert::are_equal("color [slate_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF6A5ACDU, c.to_argb());
assert::are_equal(known_color::slate_blue, c.to_known_color());
}
void test_method_(create_from_name_slate_gray) {
color c = color::from_name("slate_gray");
assert::are_equal(color::from_name("slate_gray"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x70, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x90, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("slate_gray", c.name());
assert::are_equal("color [slate_gray]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF708090U, c.to_argb());
assert::are_equal(known_color::slate_gray, c.to_known_color());
}
void test_method_(create_from_name_snow) {
color c = color::from_name("snow");
assert::are_equal(color::from_name("snow"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFA, c.g());
assert::are_equal(0xFA, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("snow", c.name());
assert::are_equal("color [snow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFAFAU, c.to_argb());
assert::are_equal(known_color::snow, c.to_known_color());
}
void test_method_(create_from_name_spring_green) {
color c = color::from_name("spring_green");
assert::are_equal(color::from_name("spring_green"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x7F, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("spring_green", c.name());
assert::are_equal("color [spring_green]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF00FF7FU, c.to_argb());
assert::are_equal(known_color::spring_green, c.to_known_color());
}
void test_method_(create_from_name_steel_blue) {
color c = color::from_name("steel_blue");
assert::are_equal(color::from_name("steel_blue"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x46, c.r());
assert::are_equal(0x82, c.g());
assert::are_equal(0xB4, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("steel_blue", c.name());
assert::are_equal("color [steel_blue]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF4682B4U, c.to_argb());
assert::are_equal(known_color::steel_blue, c.to_known_color());
}
void test_method_(create_from_name_tan) {
color c = color::from_name("tan");
assert::are_equal(color::from_name("tan"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD2, c.r());
assert::are_equal(0xB4, c.g());
assert::are_equal(0x8C, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("tan", c.name());
assert::are_equal("color [tan]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD2B48CU, c.to_argb());
assert::are_equal(known_color::tan, c.to_known_color());
}
void test_method_(create_from_name_teal) {
color c = color::from_name("teal");
assert::are_equal(color::from_name("teal"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x00, c.r());
assert::are_equal(0x80, c.g());
assert::are_equal(0x80, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("teal", c.name());
assert::are_equal("color [teal]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF008080U, c.to_argb());
assert::are_equal(known_color::teal, c.to_known_color());
}
void test_method_(create_from_name_thistle) {
color c = color::from_name("thistle");
assert::are_equal(color::from_name("thistle"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xD8, c.r());
assert::are_equal(0xBF, c.g());
assert::are_equal(0xD8, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("thistle", c.name());
assert::are_equal("color [thistle]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFD8BFD8U, c.to_argb());
assert::are_equal(known_color::thistle, c.to_known_color());
}
void test_method_(create_from_name_tomato) {
color c = color::from_name("tomato");
assert::are_equal(color::from_name("tomato"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0x63, c.g());
assert::are_equal(0x47, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("tomato", c.name());
assert::are_equal("color [tomato]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFF6347U, c.to_argb());
assert::are_equal(known_color::tomato, c.to_known_color());
}
void test_method_(create_from_name_turquoise) {
color c = color::from_name("turquoise");
assert::are_equal(color::from_name("turquoise"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0x40, c.r());
assert::are_equal(0xE0, c.g());
assert::are_equal(0xD0, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("turquoise", c.name());
assert::are_equal("color [turquoise]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFF40E0D0U, c.to_argb());
assert::are_equal(known_color::turquoise, c.to_known_color());
}
void test_method_(create_from_name_violet) {
color c = color::from_name("violet");
assert::are_equal(color::from_name("violet"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xEE, c.r());
assert::are_equal(0x82, c.g());
assert::are_equal(0xEE, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("violet", c.name());
assert::are_equal("color [violet]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFEE82EEU, c.to_argb());
assert::are_equal(known_color::violet, c.to_known_color());
}
void test_method_(create_from_name_wheat) {
color c = color::from_name("wheat");
assert::are_equal(color::from_name("wheat"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xDE, c.g());
assert::are_equal(0xB3, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("wheat", c.name());
assert::are_equal("color [wheat]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5DEB3U, c.to_argb());
assert::are_equal(known_color::wheat, c.to_known_color());
}
void test_method_(create_from_name_white) {
color c = color::from_name("white");
assert::are_equal(color::from_name("white"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0xFF, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("white", c.name());
assert::are_equal("color [white]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFFFFU, c.to_argb());
assert::are_equal(known_color::white, c.to_known_color());
}
void test_method_(create_from_name_white_smoke) {
color c = color::from_name("white_smoke");
assert::are_equal(color::from_name("white_smoke"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xF5, c.r());
assert::are_equal(0xF5, c.g());
assert::are_equal(0xF5, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("white_smoke", c.name());
assert::are_equal("color [white_smoke]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFF5F5F5U, c.to_argb());
assert::are_equal(known_color::white_smoke, c.to_known_color());
}
void test_method_(create_from_name_yellow) {
color c = color::from_name("yellow");
assert::are_equal(color::from_name("yellow"), c);
assert::are_not_equal(color(), c);
assert::are_not_equal(color::empty, c);
assert::are_equal(0xFF, c.a());
assert::are_equal(0xFF, c.r());
assert::are_equal(0xFF, c.g());
assert::are_equal(0x00, c.b());
assert::are_equal(0, c.handle());
assert::are_equal("yellow", c.name());
assert::are_equal("color [yellow]", c.to_string());
assert::is_false(c.is_empty());
assert::is_true(c.is_known_color());
assert::is_false(c.is_system_color());
assert::is_true(c.is_named_color());
assert::are_equal(0xFFFFFF00U, c.to_argb());
assert::are_equal(known_color::yellow, c.to_known_color());
}
};
}
| 263,248 | 98,273 |
#include <JSFML/JNI/org_jsfml_graphics_Image.h>
#include <JSFML/Intercom/Intercom.hpp>
#include <JSFML/Intercom/NativeObject.hpp>
#include <SFML/Graphics/Image.hpp>
/*
* Class: org_jsfml_graphics_Image
* Method: nativeCreate
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_org_jsfml_graphics_Image_nativeCreate (JNIEnv *env, jobject obj) {
return (jlong)new sf::Image();
}
/*
* Class: org_jsfml_graphics_Image
* Method: nativeDelete
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_jsfml_graphics_Image_nativeDelete (JNIEnv *env, jobject obj) {
delete THIS(sf::Image);
}
/*
* Class: org_jsfml_graphics_Image
* Method: nativeLoadFromMemory
* Signature: ([B)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jsfml_graphics_Image_nativeLoadFromMemory (JNIEnv *env, jobject obj, jbyteArray arr) {
std::size_t n = (std::size_t)env->GetArrayLength(arr);
jbyte* mem = env->GetByteArrayElements(arr, 0);
jboolean result = THIS(sf::Image)->loadFromMemory(mem, n);
env->ReleaseByteArrayElements(arr, mem, JNI_ABORT);
return result;
}
/*
* Class: org_jsfml_graphics_Image
* Method: nativeSaveToFile
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_org_jsfml_graphics_Image_nativeSaveToFile (JNIEnv *env, jobject obj, jstring fileName) {
const char *utf8 = env->GetStringUTFChars(fileName, NULL);
jboolean result = THIS(sf::Image)->saveToFile(std::string(utf8));
env->ReleaseStringUTFChars(fileName, utf8);
return result;
}
/*
* Class: org_jsfml_graphics_Image
* Method: nativeGetSize
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_org_jsfml_graphics_Image_nativeGetSize
(JNIEnv *env, jobject obj) {
return JSFML::Intercom::encodeVector2u(THIS(sf::Image)->getSize());
}
/*
* Class: org_jsfml_graphics_Image
* Method: nativeSync
* Signature: (IILjava/nio/Buffer;)V
*/
JNIEXPORT void JNICALL Java_org_jsfml_graphics_Image_nativeSync
(JNIEnv *env, jobject obj, jint width, jint height, jobject buffer) {
sf::Uint8 *dst = (sf::Uint8*)env->GetDirectBufferAddress(buffer);
const sf::Uint8 *src = THIS(sf::Image)->getPixelsPtr();
int x = width * height * 4;
while(x) {
*dst++ = *src++;
x--;
}
}
/*
* Class: org_jsfml_graphics_Image
* Method: nativeCommit
* Signature: (IILjava/nio/Buffer;)V
*/
JNIEXPORT void JNICALL Java_org_jsfml_graphics_Image_nativeCommit
(JNIEnv *env, jobject obj, jint width, jint height, jobject buffer) {
if(width == 0 || height == 0) {
THIS(sf::Image)->create(0, 0);
} else {
const sf::Uint8 *pixels = (const sf::Uint8*)env->GetDirectBufferAddress(buffer);
THIS(sf::Image)->create(width, height, pixels);
}
}
| 2,762 | 1,032 |
#include "ofApp.h"
void ofApp::setup()
{
ofBackground(80);
ofSetCircleResolution(64);
// flowers = { Flower(), Flower(), Flower() };
}
void ofApp::update()
{
for (std::size_t i = 0; i < flowers.size(); i++)
{
flowers[i].update();
}
}
void ofApp::draw()
{
for (std::size_t i = 0; i < flowers.size(); i++)
{
flowers[i].draw();
}
}
void ofApp::mousePressed(int x, int y, int button)
{
Flower aFlower;
aFlower.x = x;
aFlower.y = y;
flowers.push_back(aFlower);
}
| 553 | 228 |
/* Copyright (c) 2018-2019 The Khronos Group Inc.
* Copyright (c) 2018-2019 Valve Corporation
* Copyright (c) 2018-2019 LunarG, Inc.
* Copyright (C) 2018-2019 Google 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.
*
*/
// Allow use of STL min and max functions in Windows
#define NOMINMAX
#include "chassis.h"
#include "core_validation.h"
// This define indicates to build the VMA routines themselves
#define VMA_IMPLEMENTATION
// This define indicates that we will supply Vulkan function pointers at initialization
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#include "gpu_validation.h"
#include "shader_validation.h"
#include "spirv-tools/libspirv.h"
#include "spirv-tools/optimizer.hpp"
#include "spirv-tools/instrument.hpp"
#include <SPIRV/spirv.hpp>
#include <algorithm>
#include <regex>
// This is the number of bindings in the debug descriptor set.
static const uint32_t kNumBindingsInSet = 2;
// Implementation for Descriptor Set Manager class
GpuDescriptorSetManager::GpuDescriptorSetManager(CoreChecks *dev_data) { dev_data_ = dev_data; }
GpuDescriptorSetManager::~GpuDescriptorSetManager() {
for (auto &pool : desc_pool_map_) {
DispatchDestroyDescriptorPool(dev_data_->device, pool.first, NULL);
}
desc_pool_map_.clear();
}
VkResult GpuDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool,
std::vector<VkDescriptorSet> *desc_sets) {
const uint32_t default_pool_size = kItemsPerChunk;
VkResult result = VK_SUCCESS;
VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
if (0 == count) {
return result;
}
desc_sets->clear();
desc_sets->resize(count);
for (auto &pool : desc_pool_map_) {
if (pool.second.used + count < pool.second.size) {
pool_to_use = pool.first;
break;
}
}
if (VK_NULL_HANDLE == pool_to_use) {
uint32_t pool_count = default_pool_size;
if (count > default_pool_size) {
pool_count = count;
}
const VkDescriptorPoolSize size_counts = {
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
pool_count * kNumBindingsInSet,
};
VkDescriptorPoolCreateInfo desc_pool_info = {};
desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
desc_pool_info.pNext = NULL;
desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
desc_pool_info.maxSets = pool_count;
desc_pool_info.poolSizeCount = 1;
desc_pool_info.pPoolSizes = &size_counts;
result = DispatchCreateDescriptorPool(dev_data_->device, &desc_pool_info, NULL, &pool_to_use);
assert(result == VK_SUCCESS);
if (result != VK_SUCCESS) {
return result;
}
desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
desc_pool_map_[pool_to_use].used = 0;
}
std::vector<VkDescriptorSetLayout> desc_layouts(count, dev_data_->gpu_validation_state->debug_desc_layout);
VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
desc_layouts.data()};
result = DispatchAllocateDescriptorSets(dev_data_->device, &alloc_info, desc_sets->data());
assert(result == VK_SUCCESS);
if (result != VK_SUCCESS) {
return result;
}
*pool = pool_to_use;
desc_pool_map_[pool_to_use].used += count;
return result;
}
void GpuDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
auto iter = desc_pool_map_.find(desc_pool);
if (iter != desc_pool_map_.end()) {
VkResult result = DispatchFreeDescriptorSets(dev_data_->device, desc_pool, 1, &desc_set);
assert(result == VK_SUCCESS);
if (result != VK_SUCCESS) {
return;
}
desc_pool_map_[desc_pool].used--;
if (0 == desc_pool_map_[desc_pool].used) {
DispatchDestroyDescriptorPool(dev_data_->device, desc_pool, NULL);
desc_pool_map_.erase(desc_pool);
}
}
return;
}
// Trampolines to make VMA call Dispatch for Vulkan calls
static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
VkPhysicalDeviceProperties *pProperties) {
DispatchGetPhysicalDeviceProperties(physicalDevice, pProperties);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice,
VkPhysicalDeviceMemoryProperties *pMemoryProperties) {
DispatchGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
return DispatchAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks *pAllocator) {
DispatchFreeMemory(device, memory, pAllocator);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkMapMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size,
VkMemoryMapFlags flags, void **ppData) {
return DispatchMapMemory(device, memory, offset, size, flags, ppData);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkUnmapMemory(VkDevice device, VkDeviceMemory memory) { DispatchUnmapMemory(device, memory); }
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkFlushMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
const VkMappedMemoryRange *pMemoryRanges) {
return DispatchFlushMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkInvalidateMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
const VkMappedMemoryRange *pMemoryRanges) {
return DispatchInvalidateMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
VkDeviceSize memoryOffset) {
return DispatchBindBufferMemory(device, buffer, memory, memoryOffset);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
VkDeviceSize memoryOffset) {
return DispatchBindImageMemory(device, image, memory, memoryOffset);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer,
VkMemoryRequirements *pMemoryRequirements) {
DispatchGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkGetImageMemoryRequirements(VkDevice device, VkImage image,
VkMemoryRequirements *pMemoryRequirements) {
DispatchGetImageMemoryRequirements(device, image, pMemoryRequirements);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
return DispatchCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
return DispatchDestroyBuffer(device, buffer, pAllocator);
}
static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
return DispatchCreateImage(device, pCreateInfo, pAllocator, pImage);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
DispatchDestroyImage(device, image, pAllocator);
}
static VKAPI_ATTR void VKAPI_CALL gpuVkCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
uint32_t regionCount, const VkBufferCopy *pRegions) {
DispatchCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
}
VkResult CoreChecks::GpuInitializeVma() {
VmaVulkanFunctions functions;
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.device = device;
ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(allocatorInfo.device), layer_data_map);
ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeCoreValidation);
CoreChecks *core_checks = static_cast<CoreChecks *>(validation_data);
allocatorInfo.physicalDevice = core_checks->physical_device;
functions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)gpuVkGetPhysicalDeviceProperties;
functions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)gpuVkGetPhysicalDeviceMemoryProperties;
functions.vkAllocateMemory = (PFN_vkAllocateMemory)gpuVkAllocateMemory;
functions.vkFreeMemory = (PFN_vkFreeMemory)gpuVkFreeMemory;
functions.vkMapMemory = (PFN_vkMapMemory)gpuVkMapMemory;
functions.vkUnmapMemory = (PFN_vkUnmapMemory)gpuVkUnmapMemory;
functions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)gpuVkFlushMappedMemoryRanges;
functions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)gpuVkInvalidateMappedMemoryRanges;
functions.vkBindBufferMemory = (PFN_vkBindBufferMemory)gpuVkBindBufferMemory;
functions.vkBindImageMemory = (PFN_vkBindImageMemory)gpuVkBindImageMemory;
functions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)gpuVkGetBufferMemoryRequirements;
functions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)gpuVkGetImageMemoryRequirements;
functions.vkCreateBuffer = (PFN_vkCreateBuffer)gpuVkCreateBuffer;
functions.vkDestroyBuffer = (PFN_vkDestroyBuffer)gpuVkDestroyBuffer;
functions.vkCreateImage = (PFN_vkCreateImage)gpuVkCreateImage;
functions.vkDestroyImage = (PFN_vkDestroyImage)gpuVkDestroyImage;
functions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)gpuVkCmdCopyBuffer;
allocatorInfo.pVulkanFunctions = &functions;
return vmaCreateAllocator(&allocatorInfo, &gpu_validation_state->vmaAllocator);
}
// Convenience function for reporting problems with setting up GPU Validation.
void CoreChecks::ReportSetupProblem(VkDebugReportObjectTypeEXT object_type, uint64_t object_handle,
const char *const specific_message) {
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, object_type, object_handle, "UNASSIGNED-GPU-Assisted Validation Error. ",
"Detail: (%s)", specific_message);
}
// Turn on necessary device features.
void CoreChecks::GpuPreCallRecordCreateDevice(VkPhysicalDevice gpu, std::unique_ptr<safe_VkDeviceCreateInfo> &create_info,
VkPhysicalDeviceFeatures *supported_features) {
if (supported_features->fragmentStoresAndAtomics || supported_features->vertexPipelineStoresAndAtomics) {
VkPhysicalDeviceFeatures new_features = {};
if (create_info->pEnabledFeatures) {
new_features = *create_info->pEnabledFeatures;
}
new_features.fragmentStoresAndAtomics = supported_features->fragmentStoresAndAtomics;
new_features.vertexPipelineStoresAndAtomics = supported_features->vertexPipelineStoresAndAtomics;
delete create_info->pEnabledFeatures;
create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
}
}
// Perform initializations that can be done at Create Device time.
void CoreChecks::GpuPostCallRecordCreateDevice(const CHECK_ENABLED *enables) {
// Set instance-level enables in device-enable data structure if using legacy settings
enabled.gpu_validation = enables->gpu_validation;
enabled.gpu_validation_reserve_binding_slot = enables->gpu_validation_reserve_binding_slot;
gpu_validation_state = std::unique_ptr<GpuValidationState>(new GpuValidationState);
gpu_validation_state->reserve_binding_slot = enables->gpu_validation_reserve_binding_slot;
if (phys_dev_props.apiVersion < VK_API_VERSION_1_1) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"GPU-Assisted validation requires Vulkan 1.1 or later. GPU-Assisted Validation disabled.");
gpu_validation_state->aborted = true;
return;
}
// Some devices have extremely high limits here, so set a reasonable max because we have to pad
// the pipeline layout with dummy descriptor set layouts.
gpu_validation_state->adjusted_max_desc_sets = phys_dev_props.limits.maxBoundDescriptorSets;
gpu_validation_state->adjusted_max_desc_sets = std::min(33U, gpu_validation_state->adjusted_max_desc_sets);
// We can't do anything if there is only one.
// Device probably not a legit Vulkan device, since there should be at least 4. Protect ourselves.
if (gpu_validation_state->adjusted_max_desc_sets == 1) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Device can bind only a single descriptor set. GPU-Assisted Validation disabled.");
gpu_validation_state->aborted = true;
return;
}
gpu_validation_state->desc_set_bind_index = gpu_validation_state->adjusted_max_desc_sets - 1;
log_msg(report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"UNASSIGNED-GPU-Assisted Validation. ", "Shaders using descriptor set at index %d. ",
gpu_validation_state->desc_set_bind_index);
gpu_validation_state->output_buffer_size = sizeof(uint32_t) * (spvtools::kInstMaxOutCnt + 1);
VkResult result = GpuInitializeVma();
assert(result == VK_SUCCESS);
std::unique_ptr<GpuDescriptorSetManager> desc_set_manager(new GpuDescriptorSetManager(this));
// The descriptor indexing checks require only the first "output" binding.
const VkDescriptorSetLayoutBinding debug_desc_layout_bindings[kNumBindingsInSet] = {
{
0, // output
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
1,
VK_SHADER_STAGE_ALL_GRAPHICS,
NULL,
},
{
1, // input
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
1,
VK_SHADER_STAGE_ALL_GRAPHICS,
NULL,
},
};
const VkDescriptorSetLayoutCreateInfo debug_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0,
kNumBindingsInSet, debug_desc_layout_bindings};
const VkDescriptorSetLayoutCreateInfo dummy_desc_layout_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 0,
NULL};
result = DispatchCreateDescriptorSetLayout(device, &debug_desc_layout_info, NULL, &gpu_validation_state->debug_desc_layout);
// This is a layout used to "pad" a pipeline layout to fill in any gaps to the selected bind index.
VkResult result2 =
DispatchCreateDescriptorSetLayout(device, &dummy_desc_layout_info, NULL, &gpu_validation_state->dummy_desc_layout);
assert((result == VK_SUCCESS) && (result2 == VK_SUCCESS));
if ((result != VK_SUCCESS) || (result2 != VK_SUCCESS)) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to create descriptor set layout. GPU-Assisted Validation disabled.");
if (result == VK_SUCCESS) {
DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->debug_desc_layout, NULL);
}
if (result2 == VK_SUCCESS) {
DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->dummy_desc_layout, NULL);
}
gpu_validation_state->debug_desc_layout = VK_NULL_HANDLE;
gpu_validation_state->dummy_desc_layout = VK_NULL_HANDLE;
gpu_validation_state->aborted = true;
return;
}
gpu_validation_state->desc_set_manager = std::move(desc_set_manager);
}
// Clean up device-related resources
void CoreChecks::GpuPreCallRecordDestroyDevice() {
if (gpu_validation_state->barrier_command_buffer) {
DispatchFreeCommandBuffers(device, gpu_validation_state->barrier_command_pool, 1,
&gpu_validation_state->barrier_command_buffer);
gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
}
if (gpu_validation_state->barrier_command_pool) {
DispatchDestroyCommandPool(device, gpu_validation_state->barrier_command_pool, NULL);
gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
}
if (gpu_validation_state->debug_desc_layout) {
DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->debug_desc_layout, NULL);
gpu_validation_state->debug_desc_layout = VK_NULL_HANDLE;
}
if (gpu_validation_state->dummy_desc_layout) {
DispatchDestroyDescriptorSetLayout(device, gpu_validation_state->dummy_desc_layout, NULL);
gpu_validation_state->dummy_desc_layout = VK_NULL_HANDLE;
}
gpu_validation_state->desc_set_manager.reset();
if (gpu_validation_state->vmaAllocator) {
vmaDestroyAllocator(gpu_validation_state->vmaAllocator);
}
}
// Modify the pipeline layout to include our debug descriptor set and any needed padding with the dummy descriptor set.
bool CoreChecks::GpuPreCallCreatePipelineLayout(const VkPipelineLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout,
std::vector<VkDescriptorSetLayout> *new_layouts,
VkPipelineLayoutCreateInfo *modified_create_info) {
if (gpu_validation_state->aborted) {
return false;
}
if (modified_create_info->setLayoutCount >= gpu_validation_state->adjusted_max_desc_sets) {
std::ostringstream strm;
strm << "Pipeline Layout conflict with validation's descriptor set at slot " << gpu_validation_state->desc_set_bind_index
<< ". "
<< "Application has too many descriptor sets in the pipeline layout to continue with gpu validation. "
<< "Validation is not modifying the pipeline layout. "
<< "Instrumented shaders are replaced with non-instrumented shaders.";
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), strm.str().c_str());
} else {
// Modify the pipeline layout by:
// 1. Copying the caller's descriptor set desc_layouts
// 2. Fill in dummy descriptor layouts up to the max binding
// 3. Fill in with the debug descriptor layout at the max binding slot
new_layouts->reserve(gpu_validation_state->adjusted_max_desc_sets);
new_layouts->insert(new_layouts->end(), &pCreateInfo->pSetLayouts[0],
&pCreateInfo->pSetLayouts[pCreateInfo->setLayoutCount]);
for (uint32_t i = pCreateInfo->setLayoutCount; i < gpu_validation_state->adjusted_max_desc_sets - 1; ++i) {
new_layouts->push_back(gpu_validation_state->dummy_desc_layout);
}
new_layouts->push_back(gpu_validation_state->debug_desc_layout);
modified_create_info->pSetLayouts = new_layouts->data();
modified_create_info->setLayoutCount = gpu_validation_state->adjusted_max_desc_sets;
}
return true;
}
// Clean up GPU validation after the CreatePipelineLayout call is made
void CoreChecks::GpuPostCallCreatePipelineLayout(VkResult result) {
// Clean up GPU validation
if (result != VK_SUCCESS) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to create pipeline layout. Device could become unstable.");
gpu_validation_state->aborted = true;
}
}
// Free the device memory and descriptor set associated with a command buffer.
void CoreChecks::GpuResetCommandBuffer(const VkCommandBuffer commandBuffer) {
if (gpu_validation_state->aborted) {
return;
}
auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(commandBuffer);
for (auto buffer_info : gpu_buffer_list) {
vmaDestroyBuffer(gpu_validation_state->vmaAllocator, buffer_info.output_mem_block.buffer,
buffer_info.output_mem_block.allocation);
if (buffer_info.input_mem_block.buffer) {
vmaDestroyBuffer(gpu_validation_state->vmaAllocator, buffer_info.input_mem_block.buffer,
buffer_info.input_mem_block.allocation);
}
if (buffer_info.desc_set != VK_NULL_HANDLE) {
gpu_validation_state->desc_set_manager->PutBackDescriptorSet(buffer_info.desc_pool, buffer_info.desc_set);
}
}
gpu_validation_state->command_buffer_map.erase(commandBuffer);
}
// Just gives a warning about a possible deadlock.
void CoreChecks::GpuPreCallValidateCmdWaitEvents(VkPipelineStageFlags sourceStageMask) {
if (sourceStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"CmdWaitEvents recorded with VK_PIPELINE_STAGE_HOST_BIT set. "
"GPU_Assisted validation waits on queue completion. "
"This wait could block the host's signaling of this event, resulting in deadlock.");
}
}
std::vector<safe_VkGraphicsPipelineCreateInfo> CoreChecks::GpuPreCallRecordCreateGraphicsPipelines(
VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
std::vector<safe_VkGraphicsPipelineCreateInfo> new_pipeline_create_infos;
GpuPreCallRecordPipelineCreations(count, pCreateInfos, nullptr, pAllocator, pPipelines, pipe_state, &new_pipeline_create_infos,
nullptr, VK_PIPELINE_BIND_POINT_GRAPHICS);
return new_pipeline_create_infos;
}
std::vector<safe_VkComputePipelineCreateInfo> CoreChecks::GpuPreCallRecordCreateComputePipelines(
VkPipelineCache pipelineCache, uint32_t count, const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) {
std::vector<safe_VkComputePipelineCreateInfo> new_pipeline_create_infos;
GpuPreCallRecordPipelineCreations(count, nullptr, pCreateInfos, pAllocator, pPipelines, pipe_state, nullptr,
&new_pipeline_create_infos, VK_PIPELINE_BIND_POINT_COMPUTE);
return new_pipeline_create_infos;
}
// Examine the pipelines to see if they use the debug descriptor set binding index.
// If any do, create new non-instrumented shader modules and use them to replace the instrumented
// shaders in the pipeline. Return the (possibly) modified create infos to the caller.
void CoreChecks::GpuPreCallRecordPipelineCreations(
uint32_t count, const VkGraphicsPipelineCreateInfo *pGraphicsCreateInfos,
const VkComputePipelineCreateInfo *pComputeCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
std::vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state,
std::vector<safe_VkGraphicsPipelineCreateInfo> *new_graphics_pipeline_create_infos,
std::vector<safe_VkComputePipelineCreateInfo> *new_compute_pipeline_create_infos, const VkPipelineBindPoint bind_point) {
if (bind_point != VK_PIPELINE_BIND_POINT_GRAPHICS && bind_point != VK_PIPELINE_BIND_POINT_COMPUTE) {
return;
}
bool graphics_pipeline = (bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS);
// Walk through all the pipelines, make a copy of each and flag each pipeline that contains a shader that uses the debug
// descriptor set index.
for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
auto stageCount = graphics_pipeline ? pGraphicsCreateInfos[pipeline].stageCount : 1;
bool replace_shaders = false;
if (graphics_pipeline)
new_graphics_pipeline_create_infos->push_back(pipe_state[pipeline]->graphicsPipelineCI);
else
new_compute_pipeline_create_infos->push_back(pipe_state[pipeline]->computePipelineCI);
if (pipe_state[pipeline]->active_slots.find(gpu_validation_state->desc_set_bind_index) !=
pipe_state[pipeline]->active_slots.end()) {
replace_shaders = true;
}
// If the app requests all available sets, the pipeline layout was not modified at pipeline layout creation and the already
// instrumented shaders need to be replaced with uninstrumented shaders
if (pipe_state[pipeline]->pipeline_layout.set_layouts.size() >= gpu_validation_state->adjusted_max_desc_sets) {
replace_shaders = true;
}
if (replace_shaders) {
for (uint32_t stage = 0; stage < stageCount; ++stage) {
const SHADER_MODULE_STATE *shader;
if (graphics_pipeline)
shader = GetShaderModuleState(pGraphicsCreateInfos[pipeline].pStages[stage].module);
else
shader = GetShaderModuleState(pComputeCreateInfos[pipeline].stage.module);
VkShaderModuleCreateInfo create_info = {};
VkShaderModule shader_module;
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.pCode = shader->words.data();
create_info.codeSize = shader->words.size() * sizeof(uint32_t);
VkResult result = DispatchCreateShaderModule(device, &create_info, pAllocator, &shader_module);
if (result == VK_SUCCESS) {
if (graphics_pipeline)
new_graphics_pipeline_create_infos[pipeline].data()->pStages[stage].module = shader_module;
else
new_compute_pipeline_create_infos[pipeline].data()->stage.module = shader_module;
} else {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
(graphics_pipeline) ? HandleToUint64(pGraphicsCreateInfos[pipeline].pStages[stage].module)
: HandleToUint64(pComputeCreateInfos[pipeline].stage.module),
"Unable to replace instrumented shader with non-instrumented one. "
"Device could become unstable.");
}
}
}
}
}
void CoreChecks::GpuPostCallRecordCreateGraphicsPipelines(const uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
GpuPostCallRecordPipelineCreations(count, pCreateInfos, nullptr, pAllocator, pPipelines, VK_PIPELINE_BIND_POINT_GRAPHICS);
}
void CoreChecks::GpuPostCallRecordCreateComputePipelines(const uint32_t count, const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) {
GpuPostCallRecordPipelineCreations(count, nullptr, pCreateInfos, pAllocator, pPipelines, VK_PIPELINE_BIND_POINT_GRAPHICS);
}
// For every pipeline:
// - For every shader in a pipeline:
// - If the shader had to be replaced in PreCallRecord (because the pipeline is using the debug desc set index):
// - Destroy it since it has been bound into the pipeline by now. This is our only chance to delete it.
// - Track the shader in the shader_map
// - Save the shader binary if it contains debug code
void CoreChecks::GpuPostCallRecordPipelineCreations(const uint32_t count, const VkGraphicsPipelineCreateInfo *pGraphicsCreateInfos,
const VkComputePipelineCreateInfo *pComputeCreateInfos,
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines,
const VkPipelineBindPoint bind_point) {
if (bind_point != VK_PIPELINE_BIND_POINT_GRAPHICS && bind_point != VK_PIPELINE_BIND_POINT_COMPUTE) {
return;
}
for (uint32_t pipeline = 0; pipeline < count; ++pipeline) {
auto pipeline_state = GetPipelineState(pPipelines[pipeline]);
if (nullptr == pipeline_state) continue;
for (uint32_t stage = 0; stage < pipeline_state->graphicsPipelineCI.stageCount; ++stage) {
if (pipeline_state->active_slots.find(gpu_validation_state->desc_set_bind_index) !=
pipeline_state->active_slots.end()) {
if (bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS)
DispatchDestroyShaderModule(device, pGraphicsCreateInfos->pStages[stage].module, pAllocator);
else
DispatchDestroyShaderModule(device, pComputeCreateInfos->stage.module, pAllocator);
}
auto shader_state = GetShaderModuleState(pipeline_state->graphicsPipelineCI.pStages[stage].module);
std::vector<unsigned int> code;
// Save the shader binary if debug info is present.
// The core_validation ShaderModule tracker saves the binary too, but discards it when the ShaderModule
// is destroyed. Applications may destroy ShaderModules after they are placed in a pipeline and before
// the pipeline is used, so we have to keep another copy.
if (shader_state && shader_state->has_valid_spirv) { // really checking for presense of SPIR-V code.
for (auto insn : *shader_state) {
if (insn.opcode() == spv::OpLine) {
code = shader_state->words;
break;
}
}
}
gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].pipeline = pipeline_state->pipeline;
// Be careful to use the originally bound (instrumented) shader here, even if PreCallRecord had to back it
// out with a non-instrumented shader. The non-instrumented shader (found in pCreateInfo) was destroyed above.
gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].shader_module =
pipeline_state->graphicsPipelineCI.pStages[stage].module;
gpu_validation_state->shader_map[shader_state->gpu_validation_shader_id].pgm = std::move(code);
}
}
}
// Remove all the shader trackers associated with this destroyed pipeline.
void CoreChecks::GpuPreCallRecordDestroyPipeline(const VkPipeline pipeline) {
for (auto it = gpu_validation_state->shader_map.begin(); it != gpu_validation_state->shader_map.end();) {
if (it->second.pipeline == pipeline) {
it = gpu_validation_state->shader_map.erase(it);
} else {
++it;
}
}
}
// Call the SPIR-V Optimizer to run the instrumentation pass on the shader.
bool CoreChecks::GpuInstrumentShader(const VkShaderModuleCreateInfo *pCreateInfo, std::vector<unsigned int> &new_pgm,
uint32_t *unique_shader_id) {
if (gpu_validation_state->aborted) return false;
if (pCreateInfo->pCode[0] != spv::MagicNumber) return false;
// Load original shader SPIR-V
uint32_t num_words = static_cast<uint32_t>(pCreateInfo->codeSize / 4);
new_pgm.clear();
new_pgm.reserve(num_words);
new_pgm.insert(new_pgm.end(), &pCreateInfo->pCode[0], &pCreateInfo->pCode[num_words]);
// Call the optimizer to instrument the shader.
// Use the unique_shader_module_id as a shader ID so we can look up its handle later in the shader_map.
// If descriptor indexing is enabled, enable length checks and updated descriptor checks
const bool descriptor_indexing = device_extensions.vk_ext_descriptor_indexing;
using namespace spvtools;
spv_target_env target_env = SPV_ENV_VULKAN_1_1;
Optimizer optimizer(target_env);
optimizer.RegisterPass(CreateInstBindlessCheckPass(gpu_validation_state->desc_set_bind_index,
gpu_validation_state->unique_shader_module_id, descriptor_indexing,
descriptor_indexing));
optimizer.RegisterPass(CreateAggressiveDCEPass());
bool pass = optimizer.Run(new_pgm.data(), new_pgm.size(), &new_pgm);
if (!pass) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, VK_NULL_HANDLE,
"Failure to instrument shader. Proceeding with non-instrumented shader.");
}
*unique_shader_id = gpu_validation_state->unique_shader_module_id++;
return pass;
}
// Create the instrumented shader data to provide to the driver.
bool CoreChecks::GpuPreCallCreateShaderModule(const VkShaderModuleCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator,
VkShaderModule *pShaderModule, uint32_t *unique_shader_id,
VkShaderModuleCreateInfo *instrumented_create_info,
std::vector<unsigned int> *instrumented_pgm) {
bool pass = GpuInstrumentShader(pCreateInfo, *instrumented_pgm, unique_shader_id);
if (pass) {
instrumented_create_info->pCode = instrumented_pgm->data();
instrumented_create_info->codeSize = instrumented_pgm->size() * sizeof(unsigned int);
}
return pass;
}
// Generate the stage-specific part of the message.
static void GenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
using namespace spvtools;
std::ostringstream strm;
switch (debug_record[kInstCommonOutStageIdx]) {
case 0: {
strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
<< " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
} break;
case 1: {
strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
} break;
case 2: {
strm << "Stage = Tessellation Eval. Invocation ID = " << debug_record[kInstTessOutInvocationId] << ". ";
} break;
case 3: {
strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
<< " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
} break;
case 4: {
strm << "Stage = Fragment. Fragment coord (x,y) = ("
<< *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
<< *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
} break;
case 5: {
strm << "Stage = Compute. Global invocation ID = " << debug_record[kInstCompOutGlobalInvocationId] << ". ";
} break;
default: {
strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
assert(false);
} break;
}
msg = strm.str();
}
// Generate the part of the message describing the violation.
static void GenerateValidationMessage(const uint32_t *debug_record, std::string &msg, std::string &vuid_msg) {
using namespace spvtools;
std::ostringstream strm;
switch (debug_record[kInstValidationOutError]) {
case 0: {
strm << "Index of " << debug_record[kInstBindlessOutDescIndex] << " used to index descriptor array of length "
<< debug_record[kInstBindlessOutDescBound] << ". ";
vuid_msg = "UNASSIGNED-Descriptor index out of bounds";
} break;
case 1: {
strm << "Descriptor index " << debug_record[kInstBindlessOutDescIndex] << " is uninitialized. ";
vuid_msg = "UNASSIGNED-Descriptor uninitialized";
} break;
default: {
strm << "Internal Error (unexpected error type = " << debug_record[kInstValidationOutError] << "). ";
vuid_msg = "UNASSIGNED-Internal Error";
assert(false);
} break;
}
msg = strm.str();
}
static std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
auto object_label = report_data->DebugReportGetUtilsObjectName(object);
if (object_label != "") {
object_label = "(" + object_label + ")";
}
return object_label;
}
// Generate message from the common portion of the debug report record.
static void GenerateCommonMessage(const debug_report_data *report_data, const CMD_BUFFER_STATE *cb_node,
const uint32_t *debug_record, const VkShaderModule shader_module_handle,
const VkPipeline pipeline_handle, const uint32_t draw_index, std::string &msg) {
using namespace spvtools;
std::ostringstream strm;
if (shader_module_handle == VK_NULL_HANDLE) {
strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
<< LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
<< HandleToUint64(cb_node->commandBuffer) << "). ";
assert(true);
} else {
strm << std::hex << std::showbase << "Command buffer "
<< LookupDebugUtilsName(report_data, HandleToUint64(cb_node->commandBuffer)) << "("
<< HandleToUint64(cb_node->commandBuffer) << "). "
<< "Draw Index " << draw_index << ". "
<< "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
<< HandleToUint64(pipeline_handle) << "). "
<< "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
<< HandleToUint64(shader_module_handle) << "). ";
}
strm << std::dec << std::noshowbase;
strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
msg = strm.str();
}
// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
// Split the single string into a vector of strings, one for each line, for easier processing.
static void ReadOpSource(const SHADER_MODULE_STATE &shader, const uint32_t reported_file_id,
std::vector<std::string> &opsource_lines) {
for (auto insn : shader) {
if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
std::istringstream in_stream;
std::string cur_line;
in_stream.str((char *)&insn.word(4));
while (std::getline(in_stream, cur_line)) {
opsource_lines.push_back(cur_line);
}
while ((++insn).opcode() == spv::OpSourceContinued) {
in_stream.str((char *)&insn.word(1));
while (std::getline(in_stream, cur_line)) {
opsource_lines.push_back(cur_line);
}
}
break;
}
}
}
// The task here is to search the OpSource content to find the #line directive with the
// line number that is closest to, but still prior to the reported error line number and
// still within the reported filename.
// From this known position in the OpSource content we can add the difference between
// the #line line number and the reported error line number to determine the location
// in the OpSource content of the reported error line.
//
// Considerations:
// - Look only at #line directives that specify the reported_filename since
// the reported error line number refers to its location in the reported filename.
// - If a #line directive does not have a filename, the file is the reported filename, or
// the filename found in a prior #line directive. (This is C-preprocessor behavior)
// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
// original order and the #line directives are used to keep the numbering correct. This
// is why we need to examine the entire contents of the source, instead of leaving early
// when finding a #line line number larger than the reported error line number.
//
// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if defined(__GNUC__) && GCC_VERSION < 40900
static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
// # line <linenumber> "<filename>" or
// #line <linenumber> "<filename>"
std::vector<std::string> tokens;
std::stringstream stream(string);
std::string temp;
uint32_t line_index = 0;
while (stream >> temp) tokens.push_back(temp);
auto size = tokens.size();
if (size > 1) {
if (tokens[0] == "#" && tokens[1] == "line") {
line_index = 2;
} else if (tokens[0] == "#line") {
line_index = 1;
}
}
if (0 == line_index) return false;
*linenumber = std::stoul(tokens[line_index]);
uint32_t filename_index = line_index + 1;
// Remove enclosing double quotes around filename
if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
return true;
}
#else
static bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
static const std::regex line_regex( // matches #line directives
"^" // beginning of line
"\\s*" // optional whitespace
"#" // required text
"\\s*" // optional whitespace
"line" // required text
"\\s+" // required whitespace
"([0-9]+)" // required first capture - line number
"(\\s+)?" // optional second capture - whitespace
"(\".+\")?" // optional third capture - quoted filename with at least one char inside
".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
std::smatch captures;
bool found_line = std::regex_match(string, captures, line_regex);
if (!found_line) return false;
// filename is optional and considered found only if the whitespace and the filename are captured
if (captures[2].matched && captures[3].matched) {
// Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
filename = captures[3].str().substr(1, captures[3].str().size() - 2);
}
*linenumber = std::stoul(captures[1]);
return true;
}
#endif // GCC_VERSION
// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
static void GenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, std::string &filename_msg,
std::string &source_msg) {
using namespace spvtools;
std::ostringstream filename_stream;
std::ostringstream source_stream;
SHADER_MODULE_STATE shader;
shader.words = pgm;
// Find the OpLine just before the failing instruction indicated by the debug info.
// SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
uint32_t instruction_index = 0;
uint32_t reported_file_id = 0;
uint32_t reported_line_number = 0;
uint32_t reported_column_number = 0;
if (shader.words.size() > 0) {
for (auto insn : shader) {
if (insn.opcode() == spv::OpLine) {
reported_file_id = insn.word(1);
reported_line_number = insn.word(2);
reported_column_number = insn.word(3);
}
if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
break;
}
instruction_index++;
}
}
// Create message with file information obtained from the OpString pointed to by the discovered OpLine.
std::string reported_filename;
if (reported_file_id == 0) {
filename_stream
<< "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
} else {
bool found_opstring = false;
for (auto insn : shader) {
if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
found_opstring = true;
reported_filename = (char *)&insn.word(2);
if (reported_filename.empty()) {
filename_stream << "Shader validation error occurred at line " << reported_line_number;
} else {
filename_stream << "Shader validation error occurred in file: " << reported_filename << " at line "
<< reported_line_number;
}
if (reported_column_number > 0) {
filename_stream << ", column " << reported_column_number;
}
filename_stream << ".";
break;
}
}
if (!found_opstring) {
filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
}
}
filename_msg = filename_stream.str();
// Create message to display source code line containing error.
if ((reported_file_id != 0)) {
// Read the source code and split it up into separate lines.
std::vector<std::string> opsource_lines;
ReadOpSource(shader, reported_file_id, opsource_lines);
// Find the line in the OpSource content that corresponds to the reported error file and line.
if (!opsource_lines.empty()) {
uint32_t saved_line_number = 0;
std::string current_filename = reported_filename; // current "preprocessor" filename state.
std::vector<std::string>::size_type saved_opsource_offset = 0;
bool found_best_line = false;
for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
uint32_t parsed_line_number;
std::string parsed_filename;
bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
if (!found_line) continue;
bool found_filename = parsed_filename.size() > 0;
if (found_filename) {
current_filename = parsed_filename;
}
if ((!found_filename) || (current_filename == reported_filename)) {
// Update the candidate best line directive, if the current one is prior and closer to the reported line
if (reported_line_number >= parsed_line_number) {
if (!found_best_line ||
(reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
saved_line_number = parsed_line_number;
saved_opsource_offset = std::distance(opsource_lines.begin(), it);
found_best_line = true;
}
}
}
}
if (found_best_line) {
assert(reported_line_number >= saved_line_number);
std::vector<std::string>::size_type opsource_index =
(reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
if (opsource_index < opsource_lines.size()) {
source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
} else {
source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
<< opsource_lines.size() << " lines.";
}
} else {
source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
}
} else {
source_stream << "Unable to find SPIR-V OpSource.";
}
}
source_msg = source_stream.str();
}
// Pull together all the information from the debug record to build the error message strings,
// and then assemble them into a single message string.
// Retrieve the shader program referenced by the unique shader ID provided in the debug record.
// We had to keep a copy of the shader program with the same lifecycle as the pipeline to make
// sure it is available when the pipeline is submitted. (The ShaderModule tracking object also
// keeps a copy, but it can be destroyed after the pipeline is created and before it is submitted.)
//
void CoreChecks::AnalyzeAndReportError(CMD_BUFFER_STATE *cb_node, VkQueue queue, uint32_t draw_index,
uint32_t *const debug_output_buffer) {
using namespace spvtools;
const uint32_t total_words = debug_output_buffer[0];
// A zero here means that the shader instrumentation didn't write anything.
// If you have nothing to say, don't say it here.
if (0 == total_words) {
return;
}
// The first word in the debug output buffer is the number of words that would have
// been written by the shader instrumentation, if there was enough room in the buffer we provided.
// The number of words actually written by the shaders is determined by the size of the buffer
// we provide via the descriptor. So, we process only the number of words that can fit in the
// buffer.
// Each "report" written by the shader instrumentation is considered a "record". This function
// is hard-coded to process only one record because it expects the buffer to be large enough to
// hold only one record. If there is a desire to process more than one record, this function needs
// to be modified to loop over records and the buffer size increased.
std::string validation_message;
std::string stage_message;
std::string common_message;
std::string filename_message;
std::string source_message;
std::string vuid_msg;
VkShaderModule shader_module_handle = VK_NULL_HANDLE;
VkPipeline pipeline_handle = VK_NULL_HANDLE;
std::vector<unsigned int> pgm;
// The first record starts at this offset after the total_words.
const uint32_t *debug_record = &debug_output_buffer[kDebugOutputDataOffset];
// Lookup the VkShaderModule handle and SPIR-V code used to create the shader, using the unique shader ID value returned
// by the instrumented shader.
auto it = gpu_validation_state->shader_map.find(debug_record[kInstCommonOutShaderId]);
if (it != gpu_validation_state->shader_map.end()) {
shader_module_handle = it->second.shader_module;
pipeline_handle = it->second.pipeline;
pgm = it->second.pgm;
}
GenerateValidationMessage(debug_record, validation_message, vuid_msg);
GenerateStageMessage(debug_record, stage_message);
GenerateCommonMessage(report_data, cb_node, debug_record, shader_module_handle, pipeline_handle, draw_index, common_message);
GenerateSourceMessages(pgm, debug_record, filename_message, source_message);
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue),
vuid_msg.c_str(), "%s %s %s %s%s", validation_message.c_str(), common_message.c_str(), stage_message.c_str(),
filename_message.c_str(), source_message.c_str());
// The debug record at word kInstCommonOutSize is the number of words in the record
// written by the shader. Clear the entire record plus the total_words word at the start.
const uint32_t words_to_clear = 1 + std::min(debug_record[kInstCommonOutSize], (uint32_t)kInstMaxOutCnt);
memset(debug_output_buffer, 0, sizeof(uint32_t) * words_to_clear);
}
// For the given command buffer, map its debug data buffers and read their contents for analysis.
void CoreChecks::ProcessInstrumentationBuffer(VkQueue queue, CMD_BUFFER_STATE *cb_node) {
auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(cb_node->commandBuffer);
if (cb_node && cb_node->hasDrawCmd && gpu_buffer_list.size() > 0) {
VkResult result;
char *pData;
uint32_t draw_index = 0;
for (auto &buffer_info : gpu_buffer_list) {
result = vmaMapMemory(gpu_validation_state->vmaAllocator, buffer_info.output_mem_block.allocation, (void **)&pData);
// Analyze debug output buffer
if (result == VK_SUCCESS) {
AnalyzeAndReportError(cb_node, queue, draw_index, (uint32_t *)pData);
vmaUnmapMemory(gpu_validation_state->vmaAllocator, buffer_info.output_mem_block.allocation);
}
draw_index++;
}
}
}
// For the given command buffer, map its debug data buffers and update the status of any update after bind descriptors
void CoreChecks::UpdateInstrumentationBuffer(CMD_BUFFER_STATE *cb_node) {
auto gpu_buffer_list = gpu_validation_state->GetGpuBufferInfo(cb_node->commandBuffer);
uint32_t *pData;
for (auto &buffer_info : gpu_buffer_list) {
if (buffer_info.input_mem_block.update_at_submit.size() > 0) {
VkResult result =
vmaMapMemory(gpu_validation_state->vmaAllocator, buffer_info.input_mem_block.allocation, (void **)&pData);
if (result == VK_SUCCESS) {
for (auto update : buffer_info.input_mem_block.update_at_submit) {
if (update.second->updated) pData[update.first] = 1;
}
vmaUnmapMemory(gpu_validation_state->vmaAllocator, buffer_info.input_mem_block.allocation);
}
}
}
}
// Submit a memory barrier on graphics queues.
// Lazy-create and record the needed command buffer.
void CoreChecks::SubmitBarrier(VkQueue queue) {
uint32_t queue_family_index = 0;
auto it = queueMap.find(queue);
if (it != queueMap.end()) {
queue_family_index = it->second.queueFamilyIndex;
}
// Pay attention only to queues that support graphics.
// This ensures that the command buffer pool is created so that it can be used on a graphics queue.
VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[queue_family_index].queueFlags;
if (!(queue_flags & VK_QUEUE_GRAPHICS_BIT)) {
return;
}
// Lazy-allocate and record the command buffer.
if (gpu_validation_state->barrier_command_buffer == VK_NULL_HANDLE) {
VkResult result;
VkCommandPoolCreateInfo pool_create_info = {};
pool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_create_info.queueFamilyIndex = queue_family_index;
result = DispatchCreateCommandPool(device, &pool_create_info, nullptr, &gpu_validation_state->barrier_command_pool);
if (result != VK_SUCCESS) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to create command pool for barrier CB.");
gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
return;
}
VkCommandBufferAllocateInfo command_buffer_alloc_info = {};
command_buffer_alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffer_alloc_info.commandPool = gpu_validation_state->barrier_command_pool;
command_buffer_alloc_info.commandBufferCount = 1;
command_buffer_alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
result = DispatchAllocateCommandBuffers(device, &command_buffer_alloc_info, &gpu_validation_state->barrier_command_buffer);
if (result != VK_SUCCESS) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to create barrier command buffer.");
DispatchDestroyCommandPool(device, gpu_validation_state->barrier_command_pool, nullptr);
gpu_validation_state->barrier_command_pool = VK_NULL_HANDLE;
gpu_validation_state->barrier_command_buffer = VK_NULL_HANDLE;
return;
}
// Hook up command buffer dispatch
*((const void **)gpu_validation_state->barrier_command_buffer) = *(void **)(device);
// Record a global memory barrier to force availability of device memory operations to the host domain.
VkCommandBufferBeginInfo command_buffer_begin_info = {};
command_buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
result = DispatchBeginCommandBuffer(gpu_validation_state->barrier_command_buffer, &command_buffer_begin_info);
if (result == VK_SUCCESS) {
VkMemoryBarrier memory_barrier = {};
memory_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
memory_barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
memory_barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
DispatchCmdPipelineBarrier(gpu_validation_state->barrier_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &memory_barrier, 0, nullptr, 0, nullptr);
DispatchEndCommandBuffer(gpu_validation_state->barrier_command_buffer);
}
}
if (gpu_validation_state->barrier_command_buffer) {
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &gpu_validation_state->barrier_command_buffer;
DispatchQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
}
}
void CoreChecks::GpuPreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
const VkSubmitInfo *submit = &pSubmits[submit_idx];
for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
auto cb_node = GetCBState(submit->pCommandBuffers[i]);
UpdateInstrumentationBuffer(cb_node);
for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
UpdateInstrumentationBuffer(secondaryCmdBuffer);
}
}
}
}
// Issue a memory barrier to make GPU-written data available to host.
// Wait for the queue to complete execution.
// Check the debug buffers for all the command buffers that were submitted.
void CoreChecks::GpuPostCallQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) {
if (gpu_validation_state->aborted) return;
SubmitBarrier(queue);
DispatchQueueWaitIdle(queue);
for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) {
const VkSubmitInfo *submit = &pSubmits[submit_idx];
for (uint32_t i = 0; i < submit->commandBufferCount; i++) {
auto cb_node = GetCBState(submit->pCommandBuffers[i]);
ProcessInstrumentationBuffer(queue, cb_node);
for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) {
ProcessInstrumentationBuffer(queue, secondaryCmdBuffer);
}
}
}
}
void CoreChecks::GpuAllocateValidationResources(const VkCommandBuffer cmd_buffer, const VkPipelineBindPoint bind_point) {
// Does GPUAV support VK_PIPELINE_BIND_POINT_RAY_TRACING_NV?
if (bind_point != VK_PIPELINE_BIND_POINT_GRAPHICS && bind_point != VK_PIPELINE_BIND_POINT_COMPUTE) {
return;
}
VkResult result;
if (!(enabled.gpu_validation)) return;
if (gpu_validation_state->aborted) return;
std::vector<VkDescriptorSet> desc_sets;
VkDescriptorPool desc_pool = VK_NULL_HANDLE;
result = gpu_validation_state->desc_set_manager->GetDescriptorSets(1, &desc_pool, &desc_sets);
assert(result == VK_SUCCESS);
if (result != VK_SUCCESS) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to allocate descriptor sets. Device could become unstable.");
gpu_validation_state->aborted = true;
return;
}
VkDescriptorBufferInfo output_desc_buffer_info = {};
output_desc_buffer_info.range = gpu_validation_state->output_buffer_size;
auto cb_node = GetCBState(cmd_buffer);
if (!cb_node) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "Unrecognized command buffer");
gpu_validation_state->aborted = true;
return;
}
// Allocate memory for the output block that the gpu will use to return any error information
GpuDeviceMemoryBlock output_block = {};
VkBufferCreateInfo bufferInfo = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
bufferInfo.size = gpu_validation_state->output_buffer_size;
bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = VMA_MEMORY_USAGE_GPU_TO_CPU;
result = vmaCreateBuffer(gpu_validation_state->vmaAllocator, &bufferInfo, &allocInfo, &output_block.buffer,
&output_block.allocation, nullptr);
if (result != VK_SUCCESS) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to allocate device memory. Device could become unstable.");
gpu_validation_state->aborted = true;
return;
}
// Clear the output block to zeros so that only error information from the gpu will be present
uint32_t *pData;
result = vmaMapMemory(gpu_validation_state->vmaAllocator, output_block.allocation, (void **)&pData);
if (result == VK_SUCCESS) {
memset(pData, 0, gpu_validation_state->output_buffer_size);
vmaUnmapMemory(gpu_validation_state->vmaAllocator, output_block.allocation);
}
GpuDeviceMemoryBlock input_block = {};
VkWriteDescriptorSet desc_writes[2] = {};
uint32_t desc_count = 1;
auto const &state = cb_node->lastBound[bind_point];
uint32_t number_of_sets = (uint32_t)state.boundDescriptorSets.size();
// Figure out how much memory we need for the input block based on how many sets and bindings there are
// and how big each of the bindings is
if (number_of_sets > 0 && device_extensions.vk_ext_descriptor_indexing) {
uint32_t descriptor_count = 0; // Number of descriptors, including all array elements
uint32_t binding_count = 0; // Number of bindings based on the max binding number used
for (auto desc : state.boundDescriptorSets) {
auto bindings = desc->GetLayout()->GetSortedBindingSet();
if (bindings.size() > 0) {
binding_count += desc->GetLayout()->GetMaxBinding() + 1;
for (auto binding : bindings) {
if (binding == desc->GetLayout()->GetMaxBinding() && desc->IsVariableDescriptorCount(binding)) {
descriptor_count += desc->GetVariableDescriptorCount();
} else {
descriptor_count += desc->GetDescriptorCountFromBinding(binding);
}
}
}
}
// Note that the size of the input buffer is dependent on the maximum binding number, which
// can be very large. This is because for (set = s, binding = b, index = i), the validation
// code is going to dereference Input[ i + Input[ b + Input[ s + Input[ Input[0] ] ] ] ] to
// see if descriptors have been written. In gpu_validation.md, we note this and advise
// using densely packed bindings as a best practice when using gpu-av with descriptor indexing
uint32_t words_needed = 1 + (number_of_sets * 2) + (binding_count * 2) + descriptor_count;
allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
bufferInfo.size = words_needed * 4;
result = vmaCreateBuffer(gpu_validation_state->vmaAllocator, &bufferInfo, &allocInfo, &input_block.buffer,
&input_block.allocation, nullptr);
if (result != VK_SUCCESS) {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device),
"Unable to allocate device memory. Device could become unstable.");
gpu_validation_state->aborted = true;
return;
}
// Populate input buffer first with the sizes of every descriptor in every set, then with whether
// each element of each descriptor has been written or not. See gpu_validation.md for a more thourough
// outline of the input buffer format
result = vmaMapMemory(gpu_validation_state->vmaAllocator, input_block.allocation, (void **)&pData);
// Pointer to a sets array that points into the sizes array
uint32_t *sets_to_sizes = pData + 1;
// Pointer to the sizes array that contains the array size of the descriptor at each binding
uint32_t *sizes = sets_to_sizes + number_of_sets;
// Pointer to another sets array that points into the bindings array that points into the written array
uint32_t *sets_to_bindings = sizes + binding_count;
// Pointer to the bindings array that points at the start of the writes in the writes array for each binding
uint32_t *bindings_to_written = sets_to_bindings + number_of_sets;
// Index of the next entry in the written array to be updated
uint32_t written_index = 1 + (number_of_sets * 2) + (binding_count * 2);
uint32_t bindCounter = number_of_sets + 1;
// Index of the start of the sets_to_bindings array
pData[0] = number_of_sets + binding_count + 1;
for (auto desc : state.boundDescriptorSets) {
auto layout = desc->GetLayout();
auto bindings = layout->GetSortedBindingSet();
if (bindings.size() > 0) {
// For each set, fill in index of its bindings sizes in the sizes array
*sets_to_sizes++ = bindCounter;
// For each set, fill in the index of its bindings in the bindings_to_written array
*sets_to_bindings++ = bindCounter + number_of_sets + binding_count;
for (auto binding : bindings) {
// For each binding, fill in its size in the sizes array
if (binding == layout->GetMaxBinding() && desc->IsVariableDescriptorCount(binding)) {
sizes[binding] = desc->GetVariableDescriptorCount();
} else {
sizes[binding] = desc->GetDescriptorCountFromBinding(binding);
}
// Fill in the starting index for this binding in the written array in the bindings_to_written array
bindings_to_written[binding] = written_index;
auto index_range = desc->GetGlobalIndexRangeFromBinding(binding, true);
// For each array element in the binding, update the written array with whether it has been written
for (uint32_t i = index_range.start; i < index_range.end; ++i) {
auto *descriptor = desc->GetDescriptorFromGlobalIndex(i);
if (descriptor->updated) {
pData[written_index] = 1;
} else if (desc->IsUpdateAfterBind(binding)) {
// If it hasn't been written now and it's update after bind, put it in a list to check at QueueSubmit
input_block.update_at_submit[written_index] = descriptor;
}
written_index++;
}
}
auto last = desc->GetLayout()->GetMaxBinding();
bindings_to_written += last + 1;
bindCounter += last + 1;
sizes += last + 1;
} else {
*sets_to_sizes++ = 0;
*sets_to_bindings++ = 0;
}
}
vmaUnmapMemory(gpu_validation_state->vmaAllocator, input_block.allocation);
VkDescriptorBufferInfo input_desc_buffer_info = {};
input_desc_buffer_info.range = (words_needed * 4);
input_desc_buffer_info.buffer = input_block.buffer;
input_desc_buffer_info.offset = 0;
desc_writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
desc_writes[1].dstBinding = 1;
desc_writes[1].descriptorCount = 1;
desc_writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
desc_writes[1].pBufferInfo = &input_desc_buffer_info;
desc_writes[1].dstSet = desc_sets[0];
desc_count = 2;
}
// Write the descriptor
output_desc_buffer_info.buffer = output_block.buffer;
output_desc_buffer_info.offset = 0;
desc_writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
desc_writes[0].descriptorCount = 1;
desc_writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
desc_writes[0].pBufferInfo = &output_desc_buffer_info;
desc_writes[0].dstSet = desc_sets[0];
DispatchUpdateDescriptorSets(device, desc_count, desc_writes, 0, NULL);
auto iter = cb_node->lastBound.find(bind_point); // find() allows read-only access to cb_state
if (iter != cb_node->lastBound.end()) {
auto pipeline_state = iter->second.pipeline_state;
if (pipeline_state && (pipeline_state->pipeline_layout.set_layouts.size() <= gpu_validation_state->desc_set_bind_index)) {
DispatchCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_state->pipeline_layout.layout,
gpu_validation_state->desc_set_bind_index, 1, desc_sets.data(), 0, nullptr);
}
// Record buffer and memory info in CB state tracking
gpu_validation_state->GetGpuBufferInfo(cmd_buffer).emplace_back(output_block, input_block, desc_sets[0], desc_pool);
} else {
ReportSetupProblem(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "Unable to find pipeline state");
vmaDestroyBuffer(gpu_validation_state->vmaAllocator, input_block.buffer, input_block.allocation);
vmaDestroyBuffer(gpu_validation_state->vmaAllocator, output_block.buffer, output_block.allocation);
gpu_validation_state->aborted = true;
return;
}
}
| 72,816 | 21,829 |
#include <cstdint>
#include "common.h"
namespace {
const Signal sigs_161[] = {
{
.name = "TimeStatus",
.b1 = 0,
.b2 = 28,
.bo = 36,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 28,
.b2 = 2,
.bo = 34,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_309[] = {
{
.name = "CtLghtDet",
.b1 = 7,
.b2 = 1,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "HiBmRecmnd",
.b1 = 6,
.b2 = 1,
.bo = 57,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_774[] = {
{
.name = "RollingCounter",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "AlwaysF0",
.b1 = 8,
.b2 = 8,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "Always20",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ASCMSterringStatusChecksum",
.b1 = 48,
.b2 = 16,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_776[] = {
{
.name = "AlwaysOne",
.b1 = 4,
.b2 = 1,
.bo = 59,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "VehicleSpeed",
.b1 = 8,
.b2 = 12,
.bo = 44,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "VehicleAcceleration",
.b1 = 20,
.b2 = 12,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "AccSpeedChecksum",
.b1 = 45,
.b2 = 11,
.bo = 8,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "NearRangeMode",
.b1 = 44,
.b2 = 1,
.bo = 19,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FarRangeMode",
.b1 = 43,
.b2 = 1,
.bo = 20,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 41,
.b2 = 2,
.bo = 21,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_784[] = {
{
.name = "Always42",
.b1 = 0,
.b2 = 8,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "Always4",
.b1 = 8,
.b2 = 8,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_848[] = {
{
.name = "LnSnsRLnPosValid",
.b1 = 7,
.b2 = 1,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsTngtOfHdngLnRtV",
.b1 = 6,
.b2 = 1,
.bo = 57,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LaneSnsLLnPosValid",
.b1 = 5,
.b2 = 1,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LaneSenseSystemOKV",
.b1 = 4,
.b2 = 1,
.bo = 59,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LaneSenseSystemOK",
.b1 = 3,
.b2 = 1,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LaneSenseTimeStampV",
.b1 = 2,
.b2 = 1,
.bo = 61,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LaneSenseRollingCount",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSenseDistToLLnEdge",
.b1 = 9,
.b2 = 7,
.bo = 48,
.is_signed = false,
.factor = 0.05,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsDistToRLnEdge",
.b1 = 17,
.b2 = 7,
.bo = 40,
.is_signed = false,
.factor = 0.05,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsTngtOfHdngLnRt",
.b1 = 24,
.b2 = 8,
.bo = 32,
.is_signed = true,
.factor = 0.002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LaneSenseTimeStamp",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnEnvIllum",
.b1 = 34,
.b2 = 3,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLnChngStatus",
.b1 = 32,
.b2 = 2,
.bo = 30,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsBurstChecksum",
.b1 = 48,
.b2 = 16,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_849[] = {
{
.name = "LnSnsLnCrvtrRghtV",
.b1 = 7,
.b2 = 1,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsBurstID",
.b1 = 5,
.b2 = 2,
.bo = 57,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLatVRelToLftMrkg",
.b1 = 8,
.b2 = 8,
.bo = 48,
.is_signed = true,
.factor = 0.02,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLatVRelToRgtMrkg",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = true,
.factor = 0.02,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsCrvtGrdntRt",
.b1 = 24,
.b2 = 16,
.bo = 24,
.is_signed = true,
.factor = 5.96e-08,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLnCrvtrRght",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = true,
.factor = 9.53e-07,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLtAnchrLn",
.b1 = 63,
.b2 = 1,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsRtAnchrLn",
.b1 = 62,
.b2 = 1,
.bo = 1,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsRtLnMrkgTypChgDst",
.b1 = 58,
.b2 = 4,
.bo = 2,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLnMrkgWdthRt",
.b1 = 57,
.b2 = 1,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsCrvtGrdntRtV",
.b1 = 56,
.b2 = 1,
.bo = 7,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_850[] = {
{
.name = "LnPrvwDstncRght",
.b1 = 5,
.b2 = 3,
.bo = 56,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnPrvwDstncLft",
.b1 = 2,
.b2 = 3,
.bo = 59,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsBurstID1",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnQltyCnfdncLvlLft",
.b1 = 9,
.b2 = 7,
.bo = 48,
.is_signed = false,
.factor = 0.7874016,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLnCrvtrLftV",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnQltyCnfdncLvlRght",
.b1 = 17,
.b2 = 7,
.bo = 40,
.is_signed = false,
.factor = 0.7874016,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsTngtOfHdngLnLftV",
.b1 = 16,
.b2 = 1,
.bo = 47,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsTngtOfHdngLnLft",
.b1 = 24,
.b2 = 8,
.bo = 32,
.is_signed = true,
.factor = 0.002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLnCrvtrLft",
.b1 = 32,
.b2 = 16,
.bo = 16,
.is_signed = true,
.factor = 9.53e-07,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkrTypRght",
.b1 = 53,
.b2 = 3,
.bo = 8,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkrTypLft",
.b1 = 50,
.b2 = 3,
.bo = 11,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkrElvtdRght",
.b1 = 49,
.b2 = 1,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkrElvtdLft",
.b1 = 48,
.b2 = 1,
.bo = 15,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsTtlNmLnMrkgDetLt",
.b1 = 61,
.b2 = 3,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLtLnMrkgTypChgDst",
.b1 = 57,
.b2 = 4,
.bo = 3,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLtLnMrkgWdth",
.b1 = 56,
.b2 = 1,
.bo = 7,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_851[] = {
{
.name = "LnSnsBurstID2",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsTtlNmLnMrkgDetRt",
.b1 = 3,
.b2 = 3,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsCrvtGrdntLft",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 5.96e-08,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsRtLinCrsTm",
.b1 = 30,
.b2 = 5,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsLtLinCrsTm",
.b1 = 25,
.b2 = 5,
.bo = 34,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsCrvtGrdntLftV",
.b1 = 24,
.b2 = 1,
.bo = 39,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsNumPrlLnsDetRt",
.b1 = 38,
.b2 = 3,
.bo = 23,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnSnsNumPrlLnsDetLt",
.b1 = 35,
.b2 = 3,
.bo = 26,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnMrkgTypChgDst",
.b1 = 47,
.b2 = 4,
.bo = 13,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnMrkgWdth",
.b1 = 46,
.b2 = 1,
.bo = 17,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnPrvwDst",
.b1 = 42,
.b2 = 4,
.bo = 18,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnMarkrElvtd",
.b1 = 41,
.b2 = 1,
.bo = 22,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnPrvwDst",
.b1 = 53,
.b2 = 4,
.bo = 7,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnMarkrElvtd",
.b1 = 52,
.b2 = 1,
.bo = 11,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3AnchrLnLin",
.b1 = 51,
.b2 = 1,
.bo = 12,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4AnchrLnLin",
.b1 = 62,
.b2 = 1,
.bo = 1,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnMrkgTypChgDst",
.b1 = 58,
.b2 = 4,
.bo = 2,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnMrkgWdth",
.b1 = 57,
.b2 = 1,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_852[] = {
{
.name = "LnSnsBrstID3",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnMrkrTyp",
.b1 = 3,
.b2 = 3,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnCrvtGradV",
.b1 = 2,
.b2 = 1,
.bo = 61,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnCrvtV",
.b1 = 1,
.b2 = 1,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnHdngTngtV",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnDst",
.b1 = 8,
.b2 = 8,
.bo = 48,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnHdngTngt",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = true,
.factor = 0.002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnCrvt",
.b1 = 24,
.b2 = 16,
.bo = 24,
.is_signed = true,
.factor = 9.53e-07,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnCrvtGrad",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = true,
.factor = 5.96e-08,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnSnsLnDstV",
.b1 = 63,
.b2 = 1,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg3LnQltyConfLvl",
.b1 = 56,
.b2 = 7,
.bo = 1,
.is_signed = false,
.factor = 0.7874016,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_853[] = {
{
.name = "LnSnsBrstID4",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnMrkrTyp",
.b1 = 3,
.b2 = 3,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnCrvtGradV",
.b1 = 2,
.b2 = 1,
.bo = 61,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnCrvtV",
.b1 = 1,
.b2 = 1,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnHdngTngtV",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnDst",
.b1 = 8,
.b2 = 8,
.bo = 48,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnHdngTngt",
.b1 = 16,
.b2 = 8,
.bo = 40,
.is_signed = true,
.factor = 0.002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnCrvt",
.b1 = 24,
.b2 = 16,
.bo = 24,
.is_signed = true,
.factor = 9.53e-07,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnCrvtGrad",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = true,
.factor = 5.96e-08,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnSnsLnDstV",
.b1 = 63,
.b2 = 1,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LnMrkg4LnQltyConfLvl",
.b1 = 56,
.b2 = 7,
.bo = 1,
.is_signed = false,
.factor = 0.7874016,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_854[] = {
{
.name = "LnSnsBrstID5",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRdTypDet",
.b1 = 14,
.b2 = 2,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnCnstrctAreaDst",
.b1 = 10,
.b2 = 4,
.bo = 50,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnCnstrctZnDet",
.b1 = 8,
.b2 = 2,
.bo = 54,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnEgoVehLnPos",
.b1 = 22,
.b2 = 2,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTunnlDst",
.b1 = 18,
.b2 = 4,
.bo = 42,
.is_signed = false,
.factor = 10,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTunnlDetd",
.b1 = 16,
.b2 = 2,
.bo = 46,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1056[] = {
{
.name = "FVisionRollingCnt",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVISModeCmdFdbk",
.b1 = 3,
.b2 = 3,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnIniDiagSuccCmpt",
.b1 = 2,
.b2 = 1,
.bo = 61,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnFld",
.b1 = 1,
.b2 = 1,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnUnvlbl",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionTimeStamp",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionNumValidTrgts",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnSrvAlgnInPrcs",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVsnSnsrBlckd",
.b1 = 31,
.b2 = 1,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ClstInPathVehObjID",
.b1 = 25,
.b2 = 6,
.bo = 33,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionTimeStampV",
.b1 = 24,
.b2 = 1,
.bo = 39,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "VISBurstChecksum",
.b1 = 32,
.b2 = 16,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1057[] = {
{
.name = "FVisBurstIDTrk1",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk1",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk1Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr1Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk1",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk1Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk1",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk1",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk1",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk1",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk1",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk1",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1058[] = {
{
.name = "FVisBurstIDTrk2",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk2",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk2Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr2Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk2",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk2Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk2",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk2",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk2",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk2",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk2",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk2",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1059[] = {
{
.name = "FVisBurstIDTrk3",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk3",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk3Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr3Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk3",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk3Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk3",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk3",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk3",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk3",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk3",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk3",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1060[] = {
{
.name = "FVisBurstIDTrk4",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk4",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk4Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr4Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk4",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk4Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk4",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk4",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk4",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk4",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk4",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk4",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1061[] = {
{
.name = "FVisBurstIDTrk5",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk5",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk5Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr5Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk5",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk5Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk5",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk5",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk5",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk5",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk5",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk5",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1062[] = {
{
.name = "FVisBurstIDTrk6",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk6",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk6Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr6Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk6",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk6Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk6",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk6",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk6",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk6",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk6",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk6",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1063[] = {
{
.name = "FwVsnCinCoutPotT1Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo1",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk1",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr1",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk1",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk1",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk1",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk1",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1064[] = {
{
.name = "FwVsnCinCoutPotT2Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo2",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk2",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr2",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk2",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk2",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk2",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk2",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1065[] = {
{
.name = "FwVsnCinCoutPotT3Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo3",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk3",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr3",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk3",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk3",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk3",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk3",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1066[] = {
{
.name = "FwVsnCinCoutPotT4Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo4",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk4",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr4",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk4",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk4",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk4",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk4",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1067[] = {
{
.name = "FwVsnCinCoutPotT5Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo5",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk5",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr5",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk5",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk5",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk5",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk5",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1068[] = {
{
.name = "FwVsnCinCoutPotT6Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo6",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk6",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr6",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk6",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk6",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk6",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk6",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1088[] = {
{
.name = "FrtVsnRollCnt2",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrntVsnInPthVehAlrtNwFlg",
.b1 = 5,
.b2 = 1,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnTmStmp2",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnVldTgtNum2",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrntVsnClostPedNotftnFlg",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrntVsnClostPedObjID",
.b1 = 26,
.b2 = 6,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrntVsnClostPedAlrtNwFlg",
.b1 = 25,
.b2 = 1,
.bo = 38,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnTmStmp2V",
.b1 = 24,
.b2 = 1,
.bo = 39,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrntVsnInPthVehBrkNwSt",
.b1 = 36,
.b2 = 4,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrntVsnClostPedBrkNwSt",
.b1 = 32,
.b2 = 4,
.bo = 28,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstChksum2",
.b1 = 48,
.b2 = 16,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1089[] = {
{
.name = "FVisBurstIDTrk7",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk7",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk7Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr7Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk7",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk7Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk7",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk7",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk7",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk7",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk7",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk7",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1090[] = {
{
.name = "FVisBurstIDTrk8",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk8",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk8Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr8Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk8",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk8Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk8",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk8",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk8",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk8",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk8",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk8",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1091[] = {
{
.name = "FVisBurstIDTrk9",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk9",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk9Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr9Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk9",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk9Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk9",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk9",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk9",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk9",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk9",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk9",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1092[] = {
{
.name = "FVisBurstIDTrk10",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk10",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk10Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr10Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk10",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk10Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk10",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk10",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk10",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk10",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk10",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk10",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1093[] = {
{
.name = "FVisBurstIDTrk11",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk11",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk11Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr11Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk11",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk11Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk11",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk11",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk11",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk11",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk11",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk11",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1094[] = {
{
.name = "FVisBurstIDTrk12",
.b1 = 6,
.b2 = 2,
.bo = 56,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionObjectIDTrk12",
.b1 = 0,
.b2 = 6,
.bo = 58,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnAzmthTrk12Rev",
.b1 = 13,
.b2 = 10,
.bo = 41,
.is_signed = true,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjTypTr12Rev",
.b1 = 9,
.b2 = 4,
.bo = 51,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "ObjDirTrk12",
.b1 = 8,
.b2 = 1,
.bo = 55,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnRngTrk12Rev",
.b1 = 23,
.b2 = 12,
.bo = 29,
.is_signed = false,
.factor = 0.1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionAzRateTrk12",
.b1 = 37,
.b2 = 11,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionConfTrk12",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnVertPosTrk12",
.b1 = 50,
.b2 = 6,
.bo = 8,
.is_signed = false,
.factor = 0.25,
.offset = -2.0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionRelLaneTrk12",
.b1 = 48,
.b2 = 2,
.bo = 14,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionWidthTrk12",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FVisionMeasStatTrk12",
.b1 = 56,
.b2 = 2,
.bo = 6,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1095[] = {
{
.name = "FwVsnCinCoutPotT7Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo7",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk7",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr7",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk7",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk7",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk7",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk7",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1096[] = {
{
.name = "FwVsnCinCoutPotT8Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo8",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk8",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr8",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk8",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk8",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk8",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk8",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1097[] = {
{
.name = "FwVsnCinCoutPotT9Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo9",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk9",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr9",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk9",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk9",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk9",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk9",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1098[] = {
{
.name = "FwVsnCinCoutPotT10Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo10",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk10",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr10",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk10",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk10",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk10",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk10",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1099[] = {
{
.name = "FwVsnCinCoutPotT11Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo11",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk11",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr11",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk11",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk11",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk11",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk11",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1100[] = {
{
.name = "FwVsnCinCoutPotT12Rev",
.b1 = 2,
.b2 = 2,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrtVsnBrstIDAddInfo12",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjSclChgTrk12",
.b1 = 8,
.b2 = 16,
.bo = 40,
.is_signed = true,
.factor = 0.0002,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnTrnSigStatTr12",
.b1 = 30,
.b2 = 3,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLatOfstTrk12",
.b1 = 35,
.b2 = 10,
.bo = 19,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnBrkLtStatTrk12",
.b1 = 33,
.b2 = 2,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnLongVlctyTrk12",
.b1 = 45,
.b2 = 12,
.bo = 7,
.is_signed = true,
.factor = 0.0625,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FwdVsnObjAgeTrk12",
.b1 = 57,
.b2 = 7,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1120[] = {
{
.name = "FLRRTimeStamp",
.b1 = 5,
.b2 = 11,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRRoadTypeInfo",
.b1 = 2,
.b2 = 3,
.bo = 59,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRRollingCount",
.b1 = 0,
.b2 = 2,
.bo = 62,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRNumValidTargets",
.b1 = 19,
.b2 = 5,
.bo = 40,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRModeCmdFdbk",
.b1 = 16,
.b2 = 3,
.bo = 45,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRSnstvFltPrsntInt",
.b1 = 31,
.b2 = 1,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRHWFltPrsntInt",
.b1 = 30,
.b2 = 1,
.bo = 33,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRAntTngFltPrsnt",
.b1 = 29,
.b2 = 1,
.bo = 34,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRTunlDtctd",
.b1 = 28,
.b2 = 1,
.bo = 35,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRCANRxErr",
.b1 = 27,
.b2 = 1,
.bo = 36,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRCANSgnlSpvFld",
.b1 = 26,
.b2 = 1,
.bo = 37,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRDiagSpare",
.b1 = 25,
.b2 = 1,
.bo = 38,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRTimeStampV",
.b1 = 24,
.b2 = 1,
.bo = 39,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRMsalgnPtchUp",
.b1 = 39,
.b2 = 1,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRMsalgnPtchDn",
.b1 = 38,
.b2 = 1,
.bo = 25,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRYawRtPlsblityFlt",
.b1 = 37,
.b2 = 1,
.bo = 26,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRLonVelPlsblityFlt",
.b1 = 36,
.b2 = 1,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRExtIntrfrnc",
.b1 = 35,
.b2 = 1,
.bo = 28,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRPlntAlgnInProc",
.b1 = 34,
.b2 = 1,
.bo = 29,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRSvcAlgnInPrcs",
.b1 = 33,
.b2 = 1,
.bo = 30,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRAlgnFltPrsnt",
.b1 = 32,
.b2 = 1,
.bo = 31,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRInitDiagCmplt",
.b1 = 47,
.b2 = 1,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRAmbTmpOutRngHi",
.b1 = 46,
.b2 = 1,
.bo = 17,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRAmbTmpOutRngLw",
.b1 = 45,
.b2 = 1,
.bo = 18,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRVltgOutRngHi",
.b1 = 44,
.b2 = 1,
.bo = 19,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRVltgOutRngLo",
.b1 = 43,
.b2 = 1,
.bo = 20,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRSnsrBlckd",
.b1 = 42,
.b2 = 1,
.bo = 21,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRMsalgnYawLt",
.b1 = 41,
.b2 = 1,
.bo = 22,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRMsalgnYawRt",
.b1 = 40,
.b2 = 1,
.bo = 23,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FLRRBurstChecksum",
.b1 = 48,
.b2 = 16,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1121[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1122[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1123[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1124[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1125[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1126[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1127[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1128[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1129[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1130[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1131[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1132[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1133[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1134[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1135[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1136[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1137[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1138[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1139[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_1140[] = {
{
.name = "TrkRange",
.b1 = 2,
.b2 = 11,
.bo = 51,
.is_signed = false,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeRate",
.b1 = 13,
.b2 = 11,
.bo = 40,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkRangeAccel",
.b1 = 24,
.b2 = 9,
.bo = 31,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkAzimuth",
.b1 = 36,
.b2 = 12,
.bo = 16,
.is_signed = true,
.factor = 0.125,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkWidth",
.b1 = 48,
.b2 = 6,
.bo = 10,
.is_signed = false,
.factor = 0.25,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TrkObjectID",
.b1 = 58,
.b2 = 6,
.bo = 0,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_3221225472[] = {
{
.name = "Always12",
.b1 = 7,
.b2 = 8,
.bo = 49,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "TimeStatusChecksum",
.b1 = 7,
.b2 = 12,
.bo = 45,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Msg msgs[] = {
{
.name = "ASCMTimeStatus",
.address = 0xA1,
.size = 7,
.num_sigs = ARRAYSIZE(sigs_161),
.sigs = sigs_161,
},
{
.name = "LHT_CameraObjConfirmation_FO",
.address = 0x135,
.size = 1,
.num_sigs = ARRAYSIZE(sigs_309),
.sigs = sigs_309,
},
{
.name = "ASCMSteeringStatus",
.address = 0x306,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_774),
.sigs = sigs_774,
},
{
.name = "ASCMAccSpeedStatus",
.address = 0x308,
.size = 7,
.num_sigs = ARRAYSIZE(sigs_776),
.sigs = sigs_776,
},
{
.name = "ASCMHeadlight",
.address = 0x310,
.size = 2,
.num_sigs = ARRAYSIZE(sigs_784),
.sigs = sigs_784,
},
{
.name = "F_Vision_Environment",
.address = 0x350,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_848),
.sigs = sigs_848,
},
{
.name = "F_Vision_Environment_2",
.address = 0x351,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_849),
.sigs = sigs_849,
},
{
.name = "F_Vision_Environment_3",
.address = 0x352,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_850),
.sigs = sigs_850,
},
{
.name = "F_Vision_Environment_4",
.address = 0x353,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_851),
.sigs = sigs_851,
},
{
.name = "F_Vision_Environment_5",
.address = 0x354,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_852),
.sigs = sigs_852,
},
{
.name = "F_Vision_Environment_6",
.address = 0x355,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_853),
.sigs = sigs_853,
},
{
.name = "F_Vision_Environment_7",
.address = 0x356,
.size = 3,
.num_sigs = ARRAYSIZE(sigs_854),
.sigs = sigs_854,
},
{
.name = "F_Vision_Obj_Header",
.address = 0x420,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_1056),
.sigs = sigs_1056,
},
{
.name = "F_Vision_Obj_Track_1",
.address = 0x421,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1057),
.sigs = sigs_1057,
},
{
.name = "F_Vision_Obj_Track_2",
.address = 0x422,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1058),
.sigs = sigs_1058,
},
{
.name = "F_Vision_Obj_Track_3",
.address = 0x423,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1059),
.sigs = sigs_1059,
},
{
.name = "F_Vision_Obj_Track_4",
.address = 0x424,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1060),
.sigs = sigs_1060,
},
{
.name = "F_Vision_Obj_Track_5",
.address = 0x425,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1061),
.sigs = sigs_1061,
},
{
.name = "F_Vision_Obj_Track_6",
.address = 0x426,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1062),
.sigs = sigs_1062,
},
{
.name = "F_Vision_Obj_Track_1_B",
.address = 0x427,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1063),
.sigs = sigs_1063,
},
{
.name = "F_Vision_Obj_Track_2_B",
.address = 0x428,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1064),
.sigs = sigs_1064,
},
{
.name = "F_Vision_Obj_Track_3_B",
.address = 0x429,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1065),
.sigs = sigs_1065,
},
{
.name = "F_Vision_Obj_Track_4_B",
.address = 0x42A,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1066),
.sigs = sigs_1066,
},
{
.name = "F_Vision_Obj_Track_5_B",
.address = 0x42B,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1067),
.sigs = sigs_1067,
},
{
.name = "F_Vision_Obj_Track_6_B",
.address = 0x42C,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1068),
.sigs = sigs_1068,
},
{
.name = "F_Vision_Obj_Header_2",
.address = 0x440,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1088),
.sigs = sigs_1088,
},
{
.name = "F_Vision_Obj_Track_7",
.address = 0x441,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1089),
.sigs = sigs_1089,
},
{
.name = "F_Vision_Obj_Track_8",
.address = 0x442,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1090),
.sigs = sigs_1090,
},
{
.name = "F_Vision_Obj_Track_9",
.address = 0x443,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1091),
.sigs = sigs_1091,
},
{
.name = "F_Vision_Obj_Track_10",
.address = 0x444,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1092),
.sigs = sigs_1092,
},
{
.name = "F_Vision_Obj_Track_11",
.address = 0x445,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1093),
.sigs = sigs_1093,
},
{
.name = "F_Vision_Obj_Track_12",
.address = 0x446,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1094),
.sigs = sigs_1094,
},
{
.name = "F_Vision_Obj_Track_7_B",
.address = 0x447,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1095),
.sigs = sigs_1095,
},
{
.name = "F_Vision_Obj_Track_8_B",
.address = 0x448,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1096),
.sigs = sigs_1096,
},
{
.name = "F_Vision_Obj_Track_9_B",
.address = 0x449,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1097),
.sigs = sigs_1097,
},
{
.name = "F_Vision_Obj_Track_10_B",
.address = 0x44A,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1098),
.sigs = sigs_1098,
},
{
.name = "F_Vision_Obj_Track_11_B",
.address = 0x44B,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1099),
.sigs = sigs_1099,
},
{
.name = "F_Vision_Obj_Track_12_B",
.address = 0x44C,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1100),
.sigs = sigs_1100,
},
{
.name = "F_LRR_Obj_Header",
.address = 0x460,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1120),
.sigs = sigs_1120,
},
{
.name = "LRRObject01",
.address = 0x461,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1121),
.sigs = sigs_1121,
},
{
.name = "LRRObject02",
.address = 0x462,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1122),
.sigs = sigs_1122,
},
{
.name = "LRRObject03",
.address = 0x463,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1123),
.sigs = sigs_1123,
},
{
.name = "LRRObject04",
.address = 0x464,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1124),
.sigs = sigs_1124,
},
{
.name = "LRRObject05",
.address = 0x465,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1125),
.sigs = sigs_1125,
},
{
.name = "LRRObject06",
.address = 0x466,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1126),
.sigs = sigs_1126,
},
{
.name = "LRRObject07",
.address = 0x467,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1127),
.sigs = sigs_1127,
},
{
.name = "LRRObject08",
.address = 0x468,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1128),
.sigs = sigs_1128,
},
{
.name = "LRRObject09",
.address = 0x469,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1129),
.sigs = sigs_1129,
},
{
.name = "LRRObject10",
.address = 0x46A,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1130),
.sigs = sigs_1130,
},
{
.name = "LRRObject11",
.address = 0x46B,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1131),
.sigs = sigs_1131,
},
{
.name = "LRRObject12",
.address = 0x46C,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1132),
.sigs = sigs_1132,
},
{
.name = "LRRObject13",
.address = 0x46D,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1133),
.sigs = sigs_1133,
},
{
.name = "LRRObject14",
.address = 0x46E,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1134),
.sigs = sigs_1134,
},
{
.name = "LRRObject15",
.address = 0x46F,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1135),
.sigs = sigs_1135,
},
{
.name = "LRRObject16",
.address = 0x470,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1136),
.sigs = sigs_1136,
},
{
.name = "LRRObject17",
.address = 0x471,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1137),
.sigs = sigs_1137,
},
{
.name = "LRRObject18",
.address = 0x472,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1138),
.sigs = sigs_1138,
},
{
.name = "LRRObject19",
.address = 0x473,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1139),
.sigs = sigs_1139,
},
{
.name = "LRRObject20",
.address = 0x474,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_1140),
.sigs = sigs_1140,
},
{
.name = "VECTOR__INDEPENDENT_SIG_MSG",
.address = 0xC0000000,
.size = 0,
.num_sigs = ARRAYSIZE(sigs_3221225472),
.sigs = sigs_3221225472,
},
};
const Val vals[] = {
{
.name = "FarRangeMode",
.address = 0x308,
.def_val = "1 ACTIVE 0 INACTIVE",
.sigs = sigs_776,
},
{
.name = "NearRangeMode",
.address = 0x308,
.def_val = "1 ACTIVE 0 INACTIVE",
.sigs = sigs_776,
},
};
}
const DBC gm_global_a_object = {
.name = "gm_global_a_object",
.num_msgs = ARRAYSIZE(msgs),
.msgs = msgs,
.vals = vals,
.num_vals = ARRAYSIZE(vals),
};
dbc_init(gm_global_a_object) | 128,884 | 57,749 |
/*
* 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 "WriteChecker.h"
#include <activemq/transport/inactivity/InactivityMonitor.h>
#include <decaf/lang/System.h>
#include <decaf/lang/exceptions/NullPointerException.h>
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::transport::inactivity;
using namespace decaf;
using namespace decaf::util;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
////////////////////////////////////////////////////////////////////////////////
WriteChecker::WriteChecker(InactivityMonitor* parent) : TimerTask(), parent(parent), lastRunTime(0) {
if (this->parent == NULL) {
throw NullPointerException(__FILE__, __LINE__, "WriteChecker created with NULL parent.");
}
}
////////////////////////////////////////////////////////////////////////////////
WriteChecker::~WriteChecker() {}
////////////////////////////////////////////////////////////////////////////////
void WriteChecker::run() {
this->lastRunTime = System::currentTimeMillis();
this->parent->writeCheck();
}
| 1,848 | 481 |
#include "connection.hpp"
#include <boost/bind.hpp>
#include <thread>
#include <string>
#include <iostream>
namespace irc {
connection::connection(const bool use_ssl)
: socket_(io_service_),
use_ssl_(use_ssl), ctx_(ssl::context::sslv23), ssl_socket_(io_service_, ctx_)
{
if (use_ssl_) {
ctx_.set_default_verify_paths(ec_);
if (ec_)
throw ec_;
}
}
boost::system::error_code connection::verify_cert()
{
boost::system::error_code ec;
ssl_socket_.set_verify_mode(ssl::verify_peer | ssl::verify_fail_if_no_peer_cert);
ssl_socket_.set_verify_callback(ssl::rfc2818_verification(addr_), ec);
return ec;
}
boost::system::error_code connection::shake_hands()
{
boost::system::error_code ec;
ssl_socket_.handshake(ssl_socket::client, ec);
return ec;
}
void connection::connect()
{
using boost::asio::ip::tcp;
tcp::resolver r(io_service_);
tcp::resolver::query query(addr_, port_);
/* default error. */
ec_ = boost::asio::error::host_not_found;
if (use_ssl_) {
boost::asio::connect(ssl_socket_.lowest_layer(), r.resolve(query), ec_);
if (!ec_) {
ec_ = verify_cert();
if (!ec_)
ec_ = shake_hands();
}
} else {
boost::asio::connect(socket_.lowest_layer(), r.resolve(query), ec_);
}
if (ec_)
throw ec_;
}
template<class S>
void connection::read_some(S &s)
{
s.async_read_some(boost::asio::buffer(read_buffer_),
boost::bind(&connection::read_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred()));
}
void connection::read_handler(const boost::system::error_code &ec, std::size_t length)
{
using std::experimental::string_view;
if (ec) {
/* Unable to read from server. */
throw ec;
} else {
const string_view content(read_buffer_.data(), length);
std::stringstream iss(content.data());
std::string command;
iss >> command;
if (command == "PING")
pong();
else
ext_read_handler_(content);
if (use_ssl_)
read_some(ssl_socket_);
else
read_some(socket_);
}
}
void connection::run()
{
std::thread ping_thread(ping_handler_);
if (use_ssl_)
read_some(ssl_socket_);
else
read_some(socket_);
boost::system::error_code ec;
io_service_.run(ec);
/*
* Remain at this point until we
* do not need the connection any more.
*/
ping_thread.join();
if (ec)
throw ec;
}
void connection::ping()
{
using namespace std::literals;
while (do_ping) {
/*
* Interval decided by mimicing WeeChat.
* The standard does not seem to explicitly
* state a ping inverval. Is it the server's
* decision?
*/
std::this_thread::sleep_for(1min + 30s);
write("PING " + addr_);
}
}
void connection::pong()
{
write("PONG :" + addr_);
}
void connection::write(std::string content)
{
/*
* The IRC protocol specifies that all messages sent to the server
* must be terminated with CR-LF (Carriage Return - Line Feed)
*/
content.append("\r\n");
#ifdef DEBUG
std::cout << "[debug] writing: " << content;
#endif
if (use_ssl_)
boost::asio::write(ssl_socket_, boost::asio::buffer(content), ec_);
else
boost::asio::write(socket_.next_layer(), boost::asio::buffer(content), ec_);
if (ec_)
throw ec_;
}
void connection::stop()
{
/*
* For a proper shutdown, we first need to terminate
* the ping thread, which might have to be done while
* it's in nanosleep. After that, we are free to stop
* the io_service.
*/
if (use_ssl_)
ssl_socket_.lowest_layer().close();
else
socket_.lowest_layer().close();
io_service_.stop();
}
/* ns irc */
}
| 4,002 | 1,323 |
/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tango-gl/camera.h"
#include "tango-gl/util.h"
namespace tango_gl {
Camera::Camera() {
field_of_view_ = 45.0f * DEGREE_2_RADIANS;
aspect_ratio_ = 4.0f / 3.0f;
width_ = 800.0f;
height_ = 600.0f;
near_clip_plane_ = 0.2f;
far_clip_plane_ = 1000.0f;
ortho_ = false;
orthoScale_ = 2.0f;
orthoCropFactor_ = -1.0f;
}
glm::mat4 Camera::GetViewMatrix() {
return glm::inverse(GetTransformationMatrix());
}
glm::mat4 Camera::GetProjectionMatrix() {
if(ortho_)
{
return glm::ortho(-orthoScale_*aspect_ratio_, orthoScale_*aspect_ratio_, -orthoScale_, orthoScale_, orthoScale_ + orthoCropFactor_, far_clip_plane_);
}
return glm::perspective(field_of_view_, aspect_ratio_, near_clip_plane_, far_clip_plane_);
}
void Camera::SetWindowSize(float width, float height) {
width_ = width;
height_ = height;
aspect_ratio_ = width/height;
}
void Camera::SetFieldOfView(float fov) {
field_of_view_ = fov * DEGREE_2_RADIANS;
}
void Camera::SetNearFarClipPlanes(const float near, const float far)
{
near_clip_plane_ = near;
far_clip_plane_ = far;
}
Camera::~Camera() {
}
glm::mat4 Camera::ProjectionMatrixForCameraIntrinsics(float width, float height,
float fx, float fy,
float cx, float cy,
float near, float far) {
const float xscale = near / fx;
const float yscale = near / fy;
const float xoffset = (cx - (width / 2.0)) * xscale;
// Color camera's coordinates has y pointing downwards so we negate this term.
const float yoffset = -(cy - (height / 2.0)) * yscale;
return glm::frustum(xscale * -width / 2.0f - xoffset,
xscale * width / 2.0f - xoffset,
yscale * -height / 2.0f - yoffset,
yscale * height / 2.0f - yoffset,
near, far);
}
} // namespace tango_gl
| 2,667 | 938 |
/*--------------------------"SABUJ-JANA"------"JADAVPUR UNIVERSITY"--------*/
/*-------------------------------@greenindia-----------------------------------*/
/*---------------------- Magic. Do not touch.-----------------------------*/
/*------------------------------God is Great/\---------------------------------*/
#include <bits/stdc++.h>
using namespace std;
#define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
//cout<<fixed<<showpoint<<setprecision(12)<<ans<<endl;
#define dbg(x) cerr << #x << " = " << x << endl
#define endl "\n"
#define int long long int
#define double long double
#define pb push_back
#define mp make_pair
#define PI acos(-1)
const int INF = 1e9 + 5; //billion
#define MAX 100007
string alpha = "abcdefghijklmnopqrstuvwxyz";
//power (a^b)%m
// int power(int a, int b, int m) {int ans = 1; while (b) {if (b & 1)ans = (ans * a) % m; b /= 2; a = (a * a) % m;} return ans;}
signed main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
crap;
int t;
cin >> t;
while (t--) {
string a, b;
cin >> a >> b;
int f1[26] = {0};
int f2[26] = {0};
for (int i = 0; i < a.length(); i++) {
f1[a[i] - 'a'] = 1;
}
for (int i = 0; i < b.length(); i++) {
f2[b[i] - 'a'] = 1;
}
bool found=false;
for(int i=0; i<26; i++){
if(f1[i]==f2[i] and f1[i]>0 and f2[i]>0){
found=true;
break;
}
}
if(found)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
| 1,510 | 672 |
#include "eval.h"
void eval::analyzer::visit(ast::seq_stmt* s) {
s->first->visit(this);
if (s->second != nullptr) s->second->visit(this);
}
void eval::analyzer::visit(ast::block_stmt* s) {
if (s->body == nullptr) return;
instrs.push_back(std::make_shared<enter_scope_instr>());
s->body->visit(this);
instrs.push_back(std::make_shared<exit_scope_instr>());
}
void eval::analyzer::visit(ast::let_stmt* s) {
s->value->visit(this);
instrs.push_back(std::make_shared<bind_instr>(ids->at(s->identifer)));
}
void eval::analyzer::visit(ast::expr_stmt* s) {
s->expr->visit(this);
instrs.push_back(std::make_shared<discard_instr>());
}
void eval::analyzer::visit(ast::if_stmt* s) {
// compute condition
// if true
// stuff
// go to end
// if false
// other stuff
// end
s->condition->visit(this);
auto true_b_mark = new_marker();
auto false_b_mark = new_marker();
instrs.push_back(std::make_shared<if_instr>(true_b_mark, false_b_mark));
instrs.push_back(std::make_shared<marker_instr>(true_b_mark));
s->if_true->visit(this);
if (s->if_false != nullptr) {
auto end_mark = new_marker();
instrs.push_back(std::make_shared<jump_to_marker_instr>(end_mark));
instrs.push_back(std::make_shared<marker_instr>(false_b_mark));
s->if_false->visit(this);
instrs.push_back(std::make_shared<marker_instr>(end_mark));
} else {
instrs.push_back(std::make_shared<marker_instr>(false_b_mark));
}
}
void eval::analyzer::visit(ast::continue_stmt* s) {
auto start = 0;
if (s->name.has_value()) {
for (int i = loop_marker_stack.size() - 1; i >= 0; --i) {
auto loop = loop_marker_stack[i];
if (std::get<0>(loop).has_value() && std::get<0>(loop).value() == s->name.value()) {
start = std::get<1>(loop);
break;
}
}
}
else {
auto loop = loop_marker_stack[loop_marker_stack.size() - 1];
start = std::get<1>(loop);
}
instrs.push_back(std::make_shared<jump_instr>(start));
}
void eval::analyzer::visit(ast::break_stmt* s) {
auto end_mark = 0;
if (s->name.has_value()) {
for (int i = loop_marker_stack.size() - 1; i >= 0; --i) {
auto loop = loop_marker_stack[i];
if (std::get<0>(loop).has_value() && std::get<0>(loop).value() == s->name.value()) {
end_mark = std::get<2>(loop);
break;
}
}
}
else {
auto loop = loop_marker_stack[loop_marker_stack.size() - 1];
end_mark = std::get<2>(loop);
}
instrs.push_back(std::make_shared<jump_to_marker_instr>(end_mark));
}
void eval::analyzer::visit(ast::loop_stmt* s) {
auto start = instrs.size();
auto endm = new_marker();
loop_marker_stack.push_back(std::tuple(s->name, start, endm));
s->body->visit(this);
instrs.push_back(std::make_shared<jump_instr>(start));
instrs.push_back(std::make_shared<marker_instr>(endm));
loop_marker_stack.pop_back();
}
void eval::analyzer::visit(ast::return_stmt* s) {
if (s->expr != nullptr) s->expr->visit(this);
instrs.push_back(std::make_shared<ret_instr>());
}
void eval::analyzer::visit(ast::named_value* x) {
instrs.push_back(std::make_shared<get_binding_instr>(ids->at(x->identifier)));
}
void eval::analyzer::visit(ast::qualified_value* x) {
std::vector<std::string> path;
for (auto i : x->path) path.push_back(ids->at(i));
instrs.push_back(std::make_shared<get_qualified_binding_instr>(path));
}
void eval::analyzer::visit(ast::integer_value* x) {
auto v = std::make_shared<int_value>(x->value);
instrs.push_back(std::make_shared<literal_instr>(v));
}
void eval::analyzer::visit(ast::str_value* x) {
auto v = std::make_shared<str_value>(x->value);
instrs.push_back(std::make_shared<literal_instr>(v));
}
void eval::analyzer::visit(ast::bool_value* x) {
auto v = std::make_shared<bool_value>(x->value);
instrs.push_back(std::make_shared<literal_instr>(v));
}
void eval::analyzer::visit(ast::list_value* x) {
auto v = std::make_shared<list_value>();
instrs.push_back(std::make_shared<literal_instr>(v));
for (auto v : x->values) {
v->visit(this);
instrs.push_back(std::make_shared<append_list_instr>());
}
}
void eval::analyzer::visit(ast::map_value* x) {
auto v = std::make_shared<map_value>();
instrs.push_back(std::make_shared<literal_instr>(v));
for (auto v : x->values) {
auto n = std::make_shared<str_value>(ids->at(v.first));
instrs.push_back(std::make_shared<literal_instr>(n));
v.second->visit(this);
instrs.push_back(std::make_shared<set_key_instr>());
}
}
void eval::analyzer::visit(ast::binary_op* x) {
if (x->op == op_type::assign) {
auto path = std::dynamic_pointer_cast<ast::binary_op>(x->left);
if (path != nullptr && path->op == op_type::dot) {
path->left->visit(this);
auto name = ids->at(std::dynamic_pointer_cast<ast::named_value>(path->right)->identifier);
instrs.push_back(std::make_shared<literal_instr>(std::make_shared<str_value>(name)));
x->right->visit(this);
instrs.push_back(std::make_shared<set_key_instr>());
return;
}
auto index = std::dynamic_pointer_cast<ast::index_into>(x->left);
if (index != nullptr) {
index->collection->visit(this);
index->index->visit(this);
x->right->visit(this);
instrs.push_back(std::make_shared<set_index_instr>());
return;
}
auto name = std::dynamic_pointer_cast<ast::named_value>(x->left)->identifier;
x->right->visit(this);
instrs.push_back(std::make_shared<set_binding_instr>(ids->at(name)));
return;
}
else if (x->op == op_type::dot) {
x->left->visit(this);
auto name = ids->at(std::dynamic_pointer_cast<ast::named_value>(x->right)->identifier);
instrs.push_back(std::make_shared<literal_instr>(std::make_shared<str_value>(name)));
instrs.push_back(std::make_shared<get_key_instr>());
return;
}
x->left->visit(this);
x->right->visit(this);
instrs.push_back(std::make_shared<bin_op_instr>(x->op));
}
void eval::analyzer::visit(ast::logical_negation* x) {
x->value->visit(this);
instrs.push_back(std::make_shared<log_not_instr>());
}
void eval::analyzer::visit(ast::index_into* x) {
x->collection->visit(this);
x->index->visit(this);
instrs.push_back(std::make_shared<get_index_instr>());
}
void eval::analyzer::visit(ast::fn_call* x) {
if (x->args.size() > 0) {
for (int i = x->args.size() - 1; i >= 0; --i) {
x->args[i]->visit(this);
}
}
x->fn->visit(this);
instrs.push_back(std::make_shared<call_instr>(x->args.size()));
}
void eval::analyzer::visit(ast::fn_value* x) {
std::vector<std::string> arg_names;
for (auto an : x->args) arg_names.push_back(ids->at(an));
eval::analyzer anl(ids, this->root_path);
instrs.push_back(std::make_shared<make_closure_instr>(arg_names, anl.analyze(x->body), x->name));
}
void eval::analyzer::visit(ast::module_stmt* s) {
if(!s->inner_import) instrs.push_back(std::make_shared<enter_scope_instr>());
if (s->body != nullptr) {
s->body->visit(this);
} else {
auto modcode = eval::load_and_assemble(root_path / (ids->at(s->name)+".bcy"));
instrs.insert(instrs.end(),
std::make_move_iterator(modcode.begin()),
std::make_move_iterator(modcode.end()));
}
if(!s->inner_import) instrs.push_back(std::make_shared<exit_scope_as_new_module_instr>(ids->at(s->name)));
}
#include <fstream>
#include "parse.h"
std::vector<std::shared_ptr<eval::instr>> eval::load_and_assemble(const std::filesystem::path& path) {
std::ifstream input_stream(path);
tokenizer tok(&input_stream);
parser par(&tok);
std::vector<std::shared_ptr<eval::instr>> code;
while (!tok.peek().is_eof()) {
try {
auto stmt = par.next_stmt();
eval::analyzer anl(&tok.identifiers, path.parent_path());
auto part = anl.analyze(stmt);
code.insert(code.end(), std::make_move_iterator(part.begin()), std::make_move_iterator(part.end()));
}
catch (const parse_error& pe) {
std::cout << "parse error: " << pe.what()
<< " [file= " << path << "line= " << tok.line_number
<< " token type=" << pe.irritant.type << " data=" << pe.irritant.data << "]";
}
catch (const std::runtime_error& e) {
std::cout << "error: " << e.what() << " in file " << path << std::endl;
}
}
return code;
}
| 7,987 | 3,404 |
/*
* Copyright 2013 Stanford University.
* 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 copyright holders 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.
*/
/*
* Object representation of an identifires.
*
* Author: Omid Mashayekhi <omidm@stanford.edu>
*/
#include "src/shared/id.h"
using namespace nimbus; // NOLINT
template<typename T>
ID<T>::ID() {
elem_ = 0;
}
template<typename T>
ID<T>::ID(const T& elem) {
elem_ = elem;
}
template<typename T>
ID<T>::ID(const ID<T>& other)
: elem_(other.elem_) {
}
template<typename T>
ID<T>::~ID() {}
template<typename T>
bool ID<T>::Parse(const std::string& input) {
std::stringstream ss(input);
T num;
ss >> num;
if (ss.fail()) {
std::cout << "ERROR: wrong element as ID." << std::endl;
return false;
}
elem_ = num;
return true;
}
template<typename T>
std::string ID<T>::ToNetworkData() {
std::ostringstream ss;
ss << elem_;
std::string rval;
return ss.str();
}
template<typename T>
void ID<T>::set_elem(T elem) {
elem_ = elem;
}
template<typename T>
T ID<T>::elem() const {
return elem_;
}
template<typename T>
ID<T>& ID<T>::operator= (const ID<T>& right) {
elem_ = right.elem_;
return *this;
}
template class ID<uint64_t>;
template class ID<uint32_t>;
template class ID<int32_t>;
| 2,727 | 991 |
/*
* simulator.cpp - interface for simulator
* Copyright 2018 MIPT-MIPS
*/
// Configurations
#include <infra/config/config.h>
#include <infra/exception.h>
// Simulators
#include <func_sim/func_sim.h>
#include <modules/core/perf_sim.h>
// ISAs
#include <mips/mips.h>
#include <risc_v/risc_v.h>
#include "simulator.h"
#include <algorithm>
namespace config {
static AliasedValue<std::string> isa = { "I", "isa", "mars", "modeled ISA"};
static AliasedSwitch disassembly_on = { "d", "disassembly", "print disassembly"};
static AliasedSwitch functional_only = { "f", "functional-only", "run functional simulation only"};
} // namespace config
void CPUModel::duplicate_all_registers_to( CPUModel* model) const
{
auto max = model->max_cpu_register();
for ( size_t i = 0; i < max; ++i)
model->write_cpu_register( i, read_cpu_register( i));
}
class SimulatorFactory {
struct Builder {
virtual std::unique_ptr<Simulator> get_funcsim( bool log) = 0;
virtual std::unique_ptr<CycleAccurateSimulator> get_perfsim() = 0;
Builder() = default;
virtual ~Builder() = default;
Builder( const Builder&) = delete;
Builder( Builder&&) = delete;
Builder& operator=( const Builder&) = delete;
Builder& operator=( Builder&&) = delete;
};
template<typename T>
struct TBuilder : public Builder {
const std::string isa;
const Endian e;
TBuilder( std::string_view isa, Endian e) : isa( isa), e( e) { }
std::unique_ptr<Simulator> get_funcsim( bool log) final { return std::make_unique<FuncSim<T>>( e, log, isa); }
std::unique_ptr<CycleAccurateSimulator> get_perfsim() final { return std::make_unique<PerfSim<T>>( e, isa); }
};
std::map<std::string, std::unique_ptr<Builder>> map;
template<typename T>
void emplace( std::string_view name, Endian e)
{
map.emplace( name, std::make_unique<TBuilder<T>>( name, e));
}
template<typename T>
void emplace_all_endians( std::string name)
{
emplace<T>( name, Endian::little);
emplace<T>( name + "le", Endian::little);
if constexpr ( std::is_base_of_v<IsMIPS, T>)
emplace<T>( name + "be", Endian::big);
}
std::string get_supported_isa_message() const
{
std::ostringstream oss;
oss << "Supported ISAs:" << std::endl;
for ( const auto& isa : get_supported_isa())
oss << "\t" << isa << std::endl;
return oss.str();
}
auto get_factory( const std::string& name) const try
{
return map.at( name).get();
}
catch ( const std::out_of_range&)
{
throw InvalidISA( name + "\n" + get_supported_isa_message());
}
SimulatorFactory()
{
emplace_all_endians<MIPSI>( "mipsI");
emplace_all_endians<MIPSII>( "mipsII");
emplace_all_endians<MIPSIII>( "mipsIII");
emplace_all_endians<MIPSIV>( "mipsIV");
emplace_all_endians<MIPS32>( "mips32");
emplace_all_endians<MIPS64>( "mips64");
emplace_all_endians<MARS>( "mars");
emplace_all_endians<MARS64>( "mars64");
emplace_all_endians<RISCV32>( "riscv32");
emplace_all_endians<RISCV64>( "riscv64");
emplace_all_endians<RISCV128>( "riscv128");
}
public:
static SimulatorFactory& get_instance()
{
static SimulatorFactory sf;
return sf;
}
std::vector<std::string> get_supported_isa() const
{
std::vector<std::string> result( map.size());
std::transform( map.begin(), map.end(), result.begin(), [](const auto& e) { return e.first; });
return result;
}
auto get_funcsim( const std::string& name, bool log) const
{
return get_factory( name)->get_funcsim( log);
}
auto get_perfsim( const std::string& name) const
{
return get_factory( name)->get_perfsim();
}
};
std::vector<std::string>
Simulator::get_supported_isa()
{
return SimulatorFactory::get_instance().get_supported_isa();
}
std::shared_ptr<Simulator>
Simulator::create_simulator( const std::string& isa, bool functional_only, bool log)
{
if ( functional_only)
return SimulatorFactory::get_instance().get_funcsim( isa, log);
return CycleAccurateSimulator::create_simulator( isa);
}
std::shared_ptr<Simulator>
Simulator::create_simulator( const std::string& isa, bool functional_only)
{
return create_simulator( isa, functional_only, false);
}
std::shared_ptr<Simulator>
Simulator::create_configured_simulator()
{
return create_simulator( config::isa, config::functional_only, config::disassembly_on);
}
std::shared_ptr<Simulator>
Simulator::create_configured_isa_simulator( const std::string& isa)
{
return create_simulator( isa, config::functional_only, config::disassembly_on);
}
std::shared_ptr<CycleAccurateSimulator>
CycleAccurateSimulator::create_simulator( const std::string& isa)
{
return SimulatorFactory::get_instance().get_perfsim( isa);
}
| 5,029 | 1,757 |
๏ปฟ#include "resetblockcommand.h"
#include "../msviewmodel.h"
ResetBlockCommand::ResetBlockCommand(MSViewModel* p) throw(): m_pVM(p),m_param(JUNIOR,8,8,10)
{
}
void ResetBlockCommand::SetParameter(const std::any& param)
{
m_param = std::any_cast<SettingParameter>(param);
}
void ResetBlockCommand::Exec()
{
m_pVM->resetblock(m_param.setting, m_param.row, m_param.col, m_param.boom_num);
}
| 397 | 157 |
#include <QObject>
#include "combinemode.h"
IMPL_CombineModeToString
IMPL_CombineModeFromString
IMPL_CombineModeToDispName
| 124 | 51 |
#ifndef COUTBUF_H
#define COUTBUF_H
#include <Ios/Osstream.hpp>
#include <Ios/Cout.hpp>
#include <3rdParty/stdfwd.hh>
namespace EnjoLib
{
class LogBuf
{
public:
LogBuf(bool verbose = true);
virtual ~LogBuf();
void Flush();
Ostream & GetLog();
private:
//SafePtrFast<std::ostream> m_cnull;
//std::wostream m_wcnull;
Osstream m_ostr;
bool m_verbose;
};
class Log
{
public:
Log();
virtual ~Log();
Ostream & GetLog();
private:
Cout m_cout;
};
}
extern std::ostream cnull;
//extern std::wostream wcnull;
std::ostream & GetLog(bool verbose);
/// Create a buffered log object "logLocal" with optional disabled logging.
/**
The log will be displayed on the destruction of the object, but may be flushed before.
Usage:
ELOG // or ELOG(verbose)
LOG << "Text" << EnjoLib::Nl;
LOG_FLUSH // optional flushing
*/
#define ELOG(verbose) EnjoLib::LogBuf logLocal(verbose);
/// Create a buffered log object logLocal with enabled logging
#define ELO ELOG(true)
#define LOG logLocal.GetLog()
#define LOG_FLUSH logLocal.Flush()
/// Create a non buffered log object "logLocal".
/**
No need to flush it, but it needs to be wraped in braces, if it's expected to be reused.
Usage:
LOGL << "Text" << EnjoLib::Nl;
or:
{LOGL << "Text1" << EnjoLib::Nl;}
{LOGL << "Text2" << EnjoLib::Nl;}
*/
#define LOGL EnjoLib::Log logLocal; logLocal.GetLog()
#endif // COUTBUF_H
| 1,475 | 536 |
/**
* Copyright (C) 2014 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "log.hpp"
#include "d3d11_runtime.hpp"
#include "d3d11_effect_compiler.hpp"
#include "lexer.hpp"
#include "input.hpp"
#include "resource_loading.hpp"
#include "..\deps\imgui\imgui.h"
#include <algorithm>
#include <map>
#include <mutex>
#include <atlbase.h>
typedef bool (__stdcall *SK_ReShade_PresentCallback_pfn)(void *user);
typedef void (__stdcall *SK_ReShade_OnCopyResourceD3D11_pfn)(void* user, ID3D11Resource *&dest, ID3D11Resource *&source);
typedef void (__stdcall *SK_ReShade_OnClearDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil);
typedef void (__stdcall *SK_ReShade_OnGetDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil);
typedef void (__stdcall *SK_ReShade_OnSetDepthStencilViewD3D11_pfn)(void* user, ID3D11DepthStencilView *&depthstencil);
typedef void (__stdcall *SK_ReShade_OnDrawD3D11_pfn)(void* user, ID3D11DeviceContext *context, unsigned int vertices);
__declspec (dllimport)
void
SK_ReShade_InstallPresentCallback (SK_ReShade_PresentCallback_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallDrawCallback (SK_ReShade_OnDrawD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallSetDepthStencilViewCallback (SK_ReShade_OnSetDepthStencilViewD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallGetDepthStencilViewCallback (SK_ReShade_OnGetDepthStencilViewD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallClearDepthStencilViewCallback (SK_ReShade_OnClearDepthStencilViewD3D11_pfn fn, void* user);
__declspec (dllimport)
void
SK_ReShade_InstallCopyResourceCallback (SK_ReShade_OnCopyResourceD3D11_pfn fn, void* user);
struct explict_draw_s
{
void* ptr;
ID3D11RenderTargetView* pRTV;
bool pass = false;
int calls = 0;
} explicit_draw;
bool
__stdcall
SK_ReShade_PresentCallbackD3D11 (void *user)
{
const auto runtime =
(reshade::d3d11::d3d11_runtime *)((explict_draw_s *)user)->ptr;
if (! explicit_draw.pass)
{
//explicit_draw.calls = ((explict_draw_s *)user)->calls;
explicit_draw.pass = true;
runtime->on_present ();
explicit_draw.pass = false;
}
return true;
}
void
__stdcall
SK_ReShade_OnCopyResourceCallbackD3D11 (void* user, ID3D11Resource *&dest, ID3D11Resource *&source)
{
((reshade::d3d11::d3d11_runtime *)user)->on_copy_resource (dest, source);
}
void
__stdcall
SK_ReShade_OnClearDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil)
{
((reshade::d3d11::d3d11_runtime *)user)->on_clear_depthstencil_view (depthstencil);
}
void
__stdcall
SK_ReShade_OnGetDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil)
{
((reshade::d3d11::d3d11_runtime *)user)->on_get_depthstencil_view (depthstencil);
}
void
__stdcall
SK_ReShade_OnSetDepthStencilViewD3D11 (void* user, ID3D11DepthStencilView *&depthstencil)
{
((reshade::d3d11::d3d11_runtime *)user)->on_set_depthstencil_view (depthstencil);
}
void
__stdcall
SK_ReShade_OnDrawD3D11 (void* user, ID3D11DeviceContext *context, unsigned int vertices)
{
((reshade::d3d11::d3d11_runtime *)user)->on_draw_call (context, vertices);
}
_Return_type_success_ (nullptr)
IUnknown*
SK_COM_ValidateRelease (IUnknown** ppObj)
{
if ((! ppObj) || (! ReadPointerAcquire ((volatile LPVOID *)ppObj)))
return nullptr;
ULONG refs =
(*ppObj)->Release ();
assert (refs == 0);
if (refs == 0)
{
InterlockedExchangePointer ((void **)ppObj, nullptr);
}
return *ppObj;
}
IMGUI_API
void
ImGui_ImplDX11_RenderDrawLists (ImDrawData* draw_data);
#if 0
struct SK_DisjointTimerQueryD3D11
{
volatile ID3D11Query* async = nullptr;
volatile LONG active = false;
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT last_results = { };
};
struct SK_TimerQueryD3D11
{
volatile ID3D11Query* async = nullptr;
volatile LONG active = FALSE;
UINT64 last_results = { };
};
struct SK_DisjointTimerQueryD3D11
{
ID3D11Query* async = nullptr;
bool active = false;
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT last_results = { };
};
struct SK_TimerQueryD3D11
{
ID3D11Query* async = nullptr;
bool active = false;
UINT64 last_results = { };
};
static SK_DisjointTimerQueryD3D11 disjoint_query;
struct duration_s
{
// Timestamp at beginning
SK_TimerQueryD3D11 start;
// Timestamp at end
SK_TimerQueryD3D11 end;
};
std::vector <duration_s> timers;
// Cumulative runtime of all timers after the disjoint query
// is finished and reading these results would not stall
// the pipeline
UINT64 runtime_ticks = 0ULL;
double runtime_ms = 0.0;
double last_runtime_ms = 0.0;
#endif
namespace reshade::d3d11
{
extern DXGI_FORMAT make_format_srgb (DXGI_FORMAT format);
extern DXGI_FORMAT make_format_normal (DXGI_FORMAT format);
extern DXGI_FORMAT make_format_typeless (DXGI_FORMAT format);
d3d11_runtime::d3d11_runtime (ID3D11Device *device, IDXGISwapChain *swapchain) : runtime (device->GetFeatureLevel ()),
_device (device),
_swapchain (swapchain),
_stateblock (device)
{
assert (device != nullptr);
assert (swapchain != nullptr);
_device->GetImmediateContext (&_immediate_context);
HRESULT hr = E_FAIL;
DXGI_ADAPTER_DESC adapter_desc = { };
com_ptr <IDXGIDevice> dxgidevice = nullptr;
com_ptr <IDXGIAdapter> dxgiadapter = nullptr;
hr =
_device->QueryInterface (&dxgidevice);
assert (SUCCEEDED (hr));
hr =
dxgidevice->GetAdapter (&dxgiadapter);
assert (SUCCEEDED (hr));
hr =
dxgiadapter->GetDesc (&adapter_desc);
assert (SUCCEEDED (hr));
_vendor_id = adapter_desc.VendorId;
_device_id = adapter_desc.DeviceId;
}
bool
d3d11_runtime::init_backbuffer_texture (void)
{
// Get back buffer texture
HRESULT hr =
_swapchain->GetBuffer (0, IID_PPV_ARGS (&_backbuffer));
assert (SUCCEEDED (hr));
D3D11_TEXTURE2D_DESC texdesc = { };
texdesc.Width = _width;
texdesc.Height = _height;
texdesc.ArraySize = texdesc.MipLevels = 1;
texdesc.Format = make_format_typeless (_backbuffer_format);
texdesc.SampleDesc = { 1, 0 };
texdesc.Usage = D3D11_USAGE_DEFAULT;
texdesc.BindFlags = D3D11_BIND_RENDER_TARGET;
OSVERSIONINFOEX verinfo_windows7 = {
sizeof (OSVERSIONINFOEX), 6, 1
};
const bool is_windows7 =
VerifyVersionInfo ( &verinfo_windows7, VER_MAJORVERSION | VER_MINORVERSION,
VerSetConditionMask ( VerSetConditionMask (0, VER_MAJORVERSION, VER_EQUAL),
VER_MINORVERSION, VER_EQUAL )
) != FALSE;
//if ( _is_multisampling_enabled ||
// make_format_normal (_backbuffer_format) != _backbuffer_format ||
// (! is_windows7) )
//{
hr =
_device->CreateTexture2D (&texdesc, nullptr, &_backbuffer_resolved);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create back buffer resolve texture ("
"Width = " << texdesc.Width << ", "
"Height = " << texdesc.Height << ", "
"Format = " << texdesc.Format << ", "
"SampleCount = " << texdesc.SampleDesc.Count << ", "
"SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
hr =
_device->CreateRenderTargetView (_backbuffer.get (), nullptr, &_backbuffer_rtv [2]);
assert (SUCCEEDED (hr));
//}
if (! ( _is_multisampling_enabled ||
make_format_normal (_backbuffer_format) != _backbuffer_format ||
(! is_windows7) )
)
{
_backbuffer_resolved = _backbuffer;
}
// Create back buffer shader texture
texdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
hr =
_device->CreateTexture2D (&texdesc, nullptr, &_backbuffer_texture);
if (SUCCEEDED (hr))
{
D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc = { };
srvdesc.Format = make_format_normal (texdesc.Format);
srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvdesc.Texture2D.MipLevels = texdesc.MipLevels;
if (SUCCEEDED(hr))
{
hr =
_device->CreateShaderResourceView (_backbuffer_texture.get (), &srvdesc, &_backbuffer_texture_srv [0]);
}
else
{
LOG(ERROR) << "Failed to create back buffer texture resource view ("
"Format = " << srvdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
}
srvdesc.Format = make_format_srgb (texdesc.Format);
if (SUCCEEDED(hr))
{
hr =
_device->CreateShaderResourceView (_backbuffer_texture.get (), &srvdesc, &_backbuffer_texture_srv [1]);
}
else
{
LOG(ERROR) << "Failed to create back buffer SRGB texture resource view ("
"Format = " << srvdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
}
}
else
{
LOG (ERROR) << "Failed to create back buffer texture ("
"Width = " << texdesc.Width << ", "
"Height = " << texdesc.Height << ", "
"Format = " << texdesc.Format << ", "
"SampleCount = " << texdesc.SampleDesc.Count << ", "
"SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
}
if (FAILED (hr))
{
return false;
}
D3D11_RENDER_TARGET_VIEW_DESC rtdesc = { };
rtdesc.Format = make_format_normal (texdesc.Format);
rtdesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
hr =
_device->CreateRenderTargetView (_backbuffer_resolved.get (), &rtdesc, &_backbuffer_rtv [0]);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create back buffer render target ("
"Format = " << rtdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
rtdesc.Format = make_format_srgb (texdesc.Format);
hr =
_device->CreateRenderTargetView (_backbuffer_resolved.get (), &rtdesc, &_backbuffer_rtv [1]);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create back buffer SRGB render target ("
"Format = " << rtdesc.Format << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
{
const resources::data_resource vs =
resources::load_data_resource (IDR_RCDATA1);
hr =
_device->CreateVertexShader (vs.data, vs.data_size, nullptr, &_copy_vertex_shader);
if (FAILED (hr))
{
return false;
}
const resources::data_resource ps =
resources::load_data_resource (IDR_RCDATA2);
hr =
_device->CreatePixelShader (ps.data, ps.data_size, nullptr, &_copy_pixel_shader);
if (FAILED (hr))
{
return false;
}
}
{
const D3D11_SAMPLER_DESC desc = {
D3D11_FILTER_MIN_MAG_MIP_POINT,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP,
D3D11_TEXTURE_ADDRESS_CLAMP
};
hr =
_device->CreateSamplerState (&desc, &_copy_sampler);
if (FAILED (hr))
{
return false;
}
}
return true;
}
bool
d3d11_runtime::init_default_depth_stencil (void)
{
const D3D11_TEXTURE2D_DESC texdesc = {
_width,
_height,
1, 1,
DXGI_FORMAT_D24_UNORM_S8_UINT,
{ 1, 0 },
D3D11_USAGE_DEFAULT,
D3D11_BIND_DEPTH_STENCIL
};
com_ptr <ID3D11Texture2D> depth_stencil_texture = nullptr;
HRESULT hr =
_device->CreateTexture2D (&texdesc, nullptr, &depth_stencil_texture);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create depth stencil texture ("
"Width = " << texdesc.Width << ", "
"Height = " << texdesc.Height << ", "
"Format = " << texdesc.Format << ", "
"SampleCount = " << texdesc.SampleDesc.Count << ", "
"SampleQuality = " << texdesc.SampleDesc.Quality << ")! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
hr =
_device->CreateDepthStencilView (depth_stencil_texture.get (), nullptr, &_default_depthstencil);
return SUCCEEDED (hr);
}
bool
d3d11_runtime::init_fx_resources (void)
{
D3D11_RASTERIZER_DESC desc = { };
desc.FillMode = D3D11_FILL_SOLID;
desc.CullMode = D3D11_CULL_NONE;
desc.DepthClipEnable = TRUE;
desc.SlopeScaledDepthBias = 0.0f;
desc.DepthBiasClamp = 0.0f;
return
SUCCEEDED (_device->CreateRasterizerState (&desc, &_effect_rasterizer_state));
}
bool
d3d11_runtime::on_init (const DXGI_SWAP_CHAIN_DESC &desc)
{
_width = desc.BufferDesc.Width;
_height = desc.BufferDesc.Height;
_backbuffer_format = desc.BufferDesc.Format;
_is_multisampling_enabled = desc.SampleDesc.Count > 1;
if ( (! init_backbuffer_texture ()) ||
(! init_default_depth_stencil ()) ||
(! init_fx_resources ()) )
{
return false;
}
// Clear reference count to make UnrealEngine happy
_backbuffer->Release ();
return runtime::on_init ();
}
void
d3d11_runtime::on_reset (void)
{
if (! is_initialized ())
{
return;
}
runtime::on_reset ();
// Reset reference count to make UnrealEngine happy
_backbuffer->AddRef ();
// Destroy resources
_backbuffer.reset ();
_backbuffer_resolved.reset ();
_backbuffer_texture.reset ();
_backbuffer_texture_srv [0].reset ();
_backbuffer_texture_srv [1].reset ();
_backbuffer_rtv [0].reset ();
_backbuffer_rtv [1].reset ();
_backbuffer_rtv [2].reset ();
_depthstencil.reset ();
_depthstencil_replacement.reset ();
for ( auto it : _depth_source_table ) it.first->Release ();
_depth_source_table.clear ();
_depthstencil_texture.reset ();
_depthstencil_texture_srv.reset ();
_default_depthstencil.reset ();
_copy_vertex_shader.reset ();
_copy_pixel_shader.reset ();
_copy_sampler.reset ();
_effect_rasterizer_state.reset ();
}
void
d3d11_runtime::on_reset_effect (void)
{
runtime::on_reset_effect ();
for (auto it : _effect_sampler_states)
{
it->Release ();
}
_effect_sampler_descs.clear ();
_effect_sampler_states.clear ();
_constant_buffers.clear ();
_effect_shader_resources.resize (3);
_effect_shader_resources [0] = _backbuffer_texture_srv [0].get ();
_effect_shader_resources [1] = _backbuffer_texture_srv [1].get ();
_effect_shader_resources [2] = _depthstencil_texture_srv.get ();
}
void
d3d11_runtime::on_present (void)
{
static int last_calls = 0;
static bool first = true;
if (is_initialized ())
{
SK_ReShade_InstallPresentCallback (SK_ReShade_PresentCallbackD3D11, this);
//SK_ReShade_InstallCopyResourceCallback (SK_ReShade_OnCopyResourceCallbackD3D11, this);
//SK_ReShade_InstallSetDepthStencilViewCallback (SK_ReShade_OnSetDepthStencilViewD3D11, this);
//SK_ReShade_InstallGetDepthStencilViewCallback (SK_ReShade_OnGetDepthStencilViewD3D11, this);
//SK_ReShade_InstallClearDepthStencilViewCallback (SK_ReShade_OnClearDepthStencilViewD3D11, this);
SK_ReShade_InstallDrawCallback (SK_ReShade_OnDrawD3D11, this);
first = false;
}
if ((! is_initialized ()) || _drawcalls.load () == 0)
{
return;
}
#if 0
if (is_effect_loaded ())
{
if (ReadPointerAcquire ((void **)&_techniques [0].timer.disjoint_query.async) == nullptr)
{
D3D11_QUERY_DESC query_desc {
D3D11_QUERY_TIMESTAMP_DISJOINT, 0x00
};
ID3D11Query* pQuery = nullptr;
if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery)))
{
InterlockedExchangePointer ((void **)&_techniques [0].timer.disjoint_query.async, pQuery);
_immediate_context->Begin (pQuery);
InterlockedExchange ((volatile unsigned long *)&_techniques [0].timer.disjoint_query.active, TRUE);
}
}
}
#endif
if (explicit_draw.pass)
{
CComPtr <ID3D11Resource> pRTVRes = nullptr;
CComPtr <ID3D11RenderTargetView> pRTV = nullptr;
D3D11_TEXTURE2D_DESC tex_desc = { };
// Apply post processing
if (is_effect_loaded ())
{
CComPtr <ID3D11DepthStencilView> pDSV = nullptr;
CComPtr <ID3D11RenderTargetView> pRTVs [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT];
_immediate_context->OMGetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, &pRTVs [0], &pDSV);
D3D11_TEXTURE2D_DESC bb_desc = { };
_backbuffer_texture.get ()->GetDesc (&bb_desc);
//pRTV = pRTVs [0];
// CComPtr <ID3D11Resource > pRTVRes = nullptr;
// pRTV->GetResource (&pRTVRes);
// CComQIPtr <ID3D11Texture2D> pRTVTex (pRTVRes);
//
// pRTVTex->GetDesc (&tex_desc);
for ( auto it : pRTVs )
{
if (it == nullptr)
continue;
D3D11_RENDER_TARGET_VIEW_DESC rt_desc = { };
it->GetDesc (&rt_desc);
if (/*make_format_typeless (rt_desc.Format) == make_format_typeless (bb_desc.Format) && */rt_desc.Texture2D.MipSlice == 0)
{
CComPtr <ID3D11Resource > pRTVRes = nullptr;
it->GetResource (&pRTVRes);
CComQIPtr <ID3D11Texture2D> pRTVTex (pRTVRes);
pRTVTex->GetDesc (&tex_desc);
if ( tex_desc.SampleDesc.Count == 1 &&
tex_desc.ArraySize == 1 &&
tex_desc.MipLevels <= 1 &&
(tex_desc.BindFlags & ( D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE ) ) )
{
pRTV = it;
break;
}
}
}
if (pRTV != nullptr)
{
// Capture device state
_stateblock.capture (_immediate_context.get ());
// Disable unused pipeline stages
_immediate_context->HSSetShader (nullptr, nullptr, 0);
_immediate_context->DSSetShader (nullptr, nullptr, 0);
_immediate_context->GSSetShader (nullptr, nullptr, 0);
const uintptr_t null = 0;
pRTV->GetResource (&pRTVRes);
D3D11_SHADER_RESOURCE_VIEW_DESC srv_desc = { };
srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srv_desc.Format = tex_desc.Format;
srv_desc.Texture2D.MipLevels = 1;
CComPtr <ID3D11ShaderResourceView> pSRV = nullptr;
bool view = SUCCEEDED (_device->CreateShaderResourceView (pRTVRes, &srv_desc, &pSRV));
const auto rtv = _backbuffer_rtv [0].get ();
_immediate_context->OMSetRenderTargets (1, &rtv, nullptr);
D3D11_DEPTH_STENCIL_DESC stencil_desc = { };
stencil_desc.DepthEnable = FALSE;
stencil_desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
stencil_desc.StencilEnable = FALSE;
CComPtr <ID3D11DepthStencilState> pDepthState = nullptr;
_device->CreateDepthStencilState (&stencil_desc, &pDepthState);
_immediate_context->OMSetDepthStencilState (pDepthState, 0);
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
_immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout (nullptr);
_immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
_immediate_context->VSSetShader (_copy_vertex_shader.get (), nullptr, 0);
_immediate_context->PSSetShader (_copy_pixel_shader.get (), nullptr, 0);
//// Setup samplers
_immediate_context->VSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
_immediate_context->PSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
const auto sst = _copy_sampler.get ();
if (view)
{
_immediate_context->PSSetSamplers (0, 1, &sst);
_immediate_context->PSSetShaderResources (0, 1, &pSRV);
_immediate_context->Draw (3, 0);
}
else
_immediate_context->ResolveSubresource (_backbuffer_resolved.get (), 0, pRTVRes, 0, _backbuffer_format);
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
int techs =
on_present_effect ();
if (techs > 0)
{
_immediate_context->CopyResource (_backbuffer_texture.get (), _backbuffer_resolved.get ());
_immediate_context->OMSetRenderTargets (1, &pRTV, nullptr);
_immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout (nullptr);
_immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
_immediate_context->VSSetShader (_copy_vertex_shader.get (), nullptr, 0);
_immediate_context->PSSetShader (_copy_pixel_shader.get (), nullptr, 0);
const auto srv = _backbuffer_texture_srv [make_format_srgb(_backbuffer_format) == _backbuffer_format].get();
_immediate_context->PSSetSamplers (0, 1, &sst);
_immediate_context->PSSetShaderResources (0, 1, &srv);
_immediate_context->Draw (3, 0);
}
// Apply previous device state
_stateblock.apply_and_release ();
explicit_draw.calls++;
}
}
}
else
{
detect_depth_source ();
// Apply presenting
runtime::on_present ();
if (last_calls == explicit_draw.calls)
{
// Apply post processing
if (is_effect_loaded ())
{
// Capture device state
_stateblock.capture (_immediate_context.get ());
// Disable unused pipeline stages
_immediate_context->HSSetShader (nullptr, nullptr, 0);
_immediate_context->DSSetShader (nullptr, nullptr, 0);
_immediate_context->GSSetShader (nullptr, nullptr, 0);
// Setup real back buffer
const auto rtv = _backbuffer_rtv [0].get ();
_immediate_context->OMSetRenderTargets (1, &rtv, nullptr);
// Resolve back buffer
if (_backbuffer_resolved != _backbuffer)
{
_immediate_context->ResolveSubresource(_backbuffer_resolved.get(), 0, _backbuffer.get(), 0, _backbuffer_format);
}
// Setup vertex input
const uintptr_t null = 0;
_immediate_context->IASetPrimitiveTopology (D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout (nullptr);
_immediate_context->IASetVertexBuffers (0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState (_effect_rasterizer_state.get ());
D3D11_DEPTH_STENCIL_DESC stencil_desc = { };
stencil_desc.DepthEnable = FALSE;
stencil_desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
stencil_desc.StencilEnable = FALSE;
CComPtr <ID3D11DepthStencilState> pDepthState = nullptr;
_device->CreateDepthStencilState (&stencil_desc, &pDepthState);
// Setup samplers
_immediate_context->VSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
_immediate_context->PSSetSamplers (0, static_cast <UINT> (_effect_sampler_states.size ()), _effect_sampler_states.data ());
int techs = on_present_effect ();
// Copy to back buffer
if (techs > 0 && _backbuffer_resolved != _backbuffer)
{
_immediate_context->CopyResource(_backbuffer_texture.get(), _backbuffer_resolved.get());
const auto rtv = _backbuffer_rtv[2].get();
_immediate_context->OMSetRenderTargets(1, &rtv, nullptr);
const uintptr_t null = 0;
_immediate_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
_immediate_context->IASetInputLayout(nullptr);
_immediate_context->IASetVertexBuffers(0, 1, reinterpret_cast<ID3D11Buffer *const *>(&null), reinterpret_cast<const UINT *>(&null), reinterpret_cast<const UINT *>(&null));
_immediate_context->RSSetState(_effect_rasterizer_state.get());
_immediate_context->VSSetShader(_copy_vertex_shader.get(), nullptr, 0);
_immediate_context->PSSetShader(_copy_pixel_shader.get(), nullptr, 0);
const auto sst = _copy_sampler.get();
_immediate_context->PSSetSamplers(0, 1, &sst);
const auto srv = _backbuffer_texture_srv[make_format_srgb(_backbuffer_format) == _backbuffer_format].get();
_immediate_context->PSSetShaderResources(0, 1, &srv);
_immediate_context->Draw(3, 0);
}
// Apply previous device state
_stateblock.apply_and_release ();
}
}
#if 0
if (is_effect_loaded ())
{
if ((! _techniques [0].timer.disjoint_done) && ReadPointerAcquire ((volatile PVOID *)_techniques [0].timer.disjoint_query.async))
{
if (ReadAcquire ((volatile const LONG *)&_techniques [0].timer.disjoint_query.active))
{
_immediate_context->End ((ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async));
InterlockedExchange ((volatile unsigned long *)&_techniques [0].timer.disjoint_query.active, FALSE);
}
else
{
HRESULT const hr =
_immediate_context->GetData ( (ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async),
&_techniques [0].timer.disjoint_query.last_results,
sizeof D3D11_QUERY_DATA_TIMESTAMP_DISJOINT,
0x0 );
if (hr == S_OK)
{
((ID3D11Asynchronous *)ReadPointerAcquire ((volatile PVOID*)&_techniques [0].timer.disjoint_query.async))->Release ();
InterlockedExchangePointer ((void **)&_techniques [0].timer.disjoint_query.async, nullptr);
// Check for failure, if so, toss out the results.
if (! _techniques [0].timer.disjoint_query.last_results.Disjoint)
_techniques [0].timer.disjoint_done = true;
else
{
for (auto& technique : _techniques)
{
technique.timer.timer.start.active = 0;
technique.timer.timer.end.active = 0;
if (technique.timer.timer.start.async != nullptr)
{
SK_COM_ValidateRelease ((IUnknown **)&technique.timer.timer.start.async);
technique.timer.timer.start.async = nullptr;
}
if (technique.timer.timer.end.async != nullptr)
{
SK_COM_ValidateRelease ((IUnknown **)&technique.timer.timer.end.async);
technique.timer.timer.end.async = nullptr;
}
}
_techniques [0].timer.disjoint_done = true;
}
}
}
}
if (_techniques [0].timer.disjoint_done)
{
for (auto& technique : _techniques)
{
auto GetTimerDataStart = [](ID3D11DeviceContext* dev_ctx, duration* pDuration, bool& success) ->
UINT64
{
if (! FAILED (dev_ctx->GetData ( (ID3D11Query *)ReadPointerAcquire ((volatile PVOID *)&pDuration->start.async), &pDuration->start.last_results, sizeof UINT64, 0x00 )))
{
SK_COM_ValidateRelease ((IUnknown **)&pDuration->start.async);
success = true;
return pDuration->start.last_results;
}
success = false;
return 0;
};
auto GetTimerDataEnd = [](ID3D11DeviceContext* dev_ctx, duration* pDuration, bool& success) ->
UINT64
{
if (pDuration->end.async == nullptr)
{
success = true;
return pDuration->start.last_results;
}
if (! FAILED (dev_ctx->GetData ( (ID3D11Query *)ReadPointerAcquire ((volatile PVOID *)&pDuration->end.async), &pDuration->end.last_results, sizeof UINT64, 0x00 )))
{
SK_COM_ValidateRelease ((IUnknown **)&pDuration->end.async);
success = true;
return pDuration->end.last_results;
}
success = false;
return 0;
};
auto CalcRuntimeMS = [&](gpu_interval_timer* timer)
{
if (ReadAcquire64 ((volatile LONG64 *)&timer->runtime_ticks) != 0LL)
{
timer->runtime_ms =
1000.0 * (((double)(ULONG64)ReadAcquire64 ((volatile LONG64 *)&timer->runtime_ticks)) / (double)_techniques [0].timer.disjoint_query.last_results.Frequency);
// Filter out queries that spanned multiple frames
//
if (timer->runtime_ms > 0.0 && timer->last_runtime_ms > 0.0)
{
if (timer->runtime_ms > timer->last_runtime_ms * 100.0 || timer->runtime_ms > 12.0)
timer->runtime_ms = timer->last_runtime_ms;
}
timer->last_runtime_ms = timer->runtime_ms;
}
};
auto AccumulateRuntimeTicks = [&](ID3D11DeviceContext* dev_ctx, gpu_interval_timer* timer) ->
void
{
std::vector <duration> rejects;
InterlockedExchange64 ((volatile LONG64 *)&timer->runtime_ticks, 0LL);
bool success0 = false, success1 = false;
UINT64 time0 = 0ULL, time1 = 0ULL;
time0 = GetTimerDataEnd (dev_ctx, &timer->timer, success0);
time1 = GetTimerDataStart (dev_ctx, &timer->timer, success1);
if (success0 && success1)
InterlockedAdd64 ((volatile LONG64 *)&timer->runtime_ticks, time0 - time1);
else
rejects.push_back (timer->timer);
// If effect was cancelled ...
//{
// InterlockedExchange64 ((volatile LONG64 *)&tracker->runtime_ticks, 0LL);
// timer->runtime_ms = 0.0;
// timer->last_runtime_ms = 0.0;
//}
// Anything that fails goes back on the list and we will try again next frame
//if (! rejects.empty ())
// timer->timer = rejects [0];
};
AccumulateRuntimeTicks (_immediate_context.get (), &technique.timer);
CalcRuntimeMS (&technique.timer);
technique.average_gpu_duration.append (technique.timer.last_runtime_ms);
}
_techniques [0].timer.disjoint_done = false;
}
}
#endif
last_calls = explicit_draw.calls;
}
}
void
d3d11_runtime::on_draw_call (ID3D11DeviceContext *context, unsigned int vertices)
{
_vertices += vertices;
_drawcalls += 1;
com_ptr <ID3D11DepthStencilView> current_depthstencil = nullptr;
context->OMGetRenderTargets ( 0, nullptr,
¤t_depthstencil );
if ( current_depthstencil == nullptr ||
current_depthstencil == _default_depthstencil )
{
return;
}
if (current_depthstencil == _depthstencil_replacement)
{
current_depthstencil = _depthstencil;
}
const auto it =
_depth_source_table.find (current_depthstencil.get ());
if (it != _depth_source_table.cend () && (! it->second.invalidated))
{
it->second.drawcall_count = _drawcalls.load ();
it->second.vertices_count += vertices;
}
}
void
d3d11_runtime::on_set_depthstencil_view (ID3D11DepthStencilView *&depthstencil)
{
if ( (! _depth_source_table.count (depthstencil)) || _depth_source_table [depthstencil].invalidated )
{
D3D11_TEXTURE2D_DESC texture_desc = { };
com_ptr <ID3D11Resource> resource = nullptr;
com_ptr <ID3D11Texture2D> texture = nullptr;
depthstencil->GetResource (&resource);
if (FAILED (resource->QueryInterface (&texture)))
{
return;
}
texture->GetDesc (&texture_desc);
// Early depth stencil rejection
if ( texture_desc.Width != _width ||
texture_desc.Height != _height ||
texture_desc.SampleDesc.Count > 1 )
{
return;
}
depthstencil->AddRef ();
// Begin tracking new depth stencil
const depth_source_info info =
{ texture_desc.Width, texture_desc.Height,
0, 0,
false
};
_depth_source_table [depthstencil] = info;
}
if (_depthstencil_replacement != nullptr && depthstencil == _depthstencil)
{
depthstencil = _depthstencil_replacement.get ();
}
}
void
d3d11_runtime::on_get_depthstencil_view (ID3D11DepthStencilView *&depthstencil)
{
if ( _depthstencil_replacement != nullptr &&
depthstencil == _depthstencil_replacement )
{
depthstencil->Release ();
depthstencil =
_depthstencil.get ();
depthstencil->AddRef ();
}
}
void
d3d11_runtime::on_clear_depthstencil_view (ID3D11DepthStencilView *&depthstencil)
{
if ( _depthstencil_replacement != nullptr &&
depthstencil == _depthstencil )
{
depthstencil =
_depthstencil_replacement.get ();
}
}
void
d3d11_runtime::on_copy_resource (ID3D11Resource *&dest, ID3D11Resource *&source)
{
if (_depthstencil_replacement != nullptr)
{
com_ptr <ID3D11Resource> resource = nullptr;
_depthstencil->GetResource (&resource);
if (dest == resource)
{
dest =
_depthstencil_texture.get ();
}
if (source == resource)
{
source =
_depthstencil_texture.get ();
}
}
}
void
d3d11_runtime::capture_frame(uint8_t *buffer) const
{
if (_backbuffer_format != DXGI_FORMAT_R8G8B8A8_UNORM &&
_backbuffer_format != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB &&
_backbuffer_format != DXGI_FORMAT_B8G8R8A8_UNORM &&
_backbuffer_format != DXGI_FORMAT_B8G8R8A8_UNORM_SRGB)
{
LOG (WARNING) << "Screenshots are not supported for back buffer format " << _backbuffer_format << ".";
return;
}
D3D11_TEXTURE2D_DESC texture_desc = { };
texture_desc.Width = _width;
texture_desc.Height = _height;
texture_desc.ArraySize = 1;
texture_desc.MipLevels = 1;
texture_desc.Format = _backbuffer_format;
texture_desc.SampleDesc.Count = 1;
texture_desc.Usage = D3D11_USAGE_STAGING;
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
com_ptr<ID3D11Texture2D> texture_staging;
HRESULT hr =
_device->CreateTexture2D (&texture_desc, nullptr, &texture_staging);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create staging resource for screenshot capture! HRESULT is '" << std::hex << hr << std::dec << "'.";
return;
}
_immediate_context->CopyResource ( texture_staging.get (),
_backbuffer_resolved.get () );
D3D11_MAPPED_SUBRESOURCE mapped = { };
hr =
_immediate_context->Map (texture_staging.get (), 0, D3D11_MAP_READ, 0, &mapped);
if (FAILED (hr))
{
LOG(ERROR) << "Failed to map staging resource with screenshot capture! HRESULT is '" << std::hex << hr << std::dec << "'.";
return;
}
auto mapped_data = static_cast <BYTE *> (mapped.pData);
const UINT pitch = texture_desc.Width * 4;
for (UINT y = 0; y < texture_desc.Height; y++)
{
CopyMemory (buffer, mapped_data, std::min (pitch, static_cast <UINT> (mapped.RowPitch)));
for (UINT x = 0; x < pitch; x += 4)
{
buffer [x + 3] = 0xFF;
if ( texture_desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM ||
texture_desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB )
{
std::swap (buffer [x + 0], buffer [x + 2]);
}
}
buffer += pitch;
mapped_data += mapped.RowPitch;
}
_immediate_context->Unmap (texture_staging.get (), 0);
}
bool
d3d11_runtime::load_effect (const reshadefx::syntax_tree &ast, std::string &errors)
{
return d3d11_effect_compiler (this, ast, errors, false).run ();
}
bool
d3d11_runtime::update_texture (texture &texture, const uint8_t *data)
{
if (texture.impl_reference != texture_reference::none)
{
return false;
}
const auto texture_impl =
texture.impl->as <d3d11_tex_data> ();
assert (data != nullptr);
assert (texture_impl != nullptr);
switch (texture.format)
{
case texture_format::r8:
{
std::vector <uint8_t> data2 (texture.width * texture.height);
for (size_t i = 0, k = 0; i < texture.width * texture.height * 4; i += 4, k++)
data2 [k] = data [i];
_immediate_context->UpdateSubresource ( texture_impl->texture.get (),
0, nullptr, data2.data (),
texture.width, texture.width * texture.height );
} break;
case texture_format::rg8:
{
std::vector <uint8_t> data2 (texture.width * texture.height * 2);
for (size_t i = 0, k = 0; i < texture.width * texture.height * 4; i += 4, k += 2)
data2 [k ] = data [i ],
data2 [k + 1] = data [i + 1];
_immediate_context->UpdateSubresource ( texture_impl->texture.get (),
0, nullptr, data2.data (),
texture.width * 2, texture.width * texture.height * 2 );
} break;
default:
{
_immediate_context->UpdateSubresource ( texture_impl->texture.get (),
0, nullptr, data,
texture.width * 4, texture.width * texture.height * 4 );
} break;
}
if (texture.levels > 1)
{
_immediate_context->GenerateMips (texture_impl->srv [0].get ());
}
return true;
}
void
d3d11_runtime::render_technique (const technique &technique)
{
#if 0
if (_techniques [0].timer.disjoint_query.active)
{
// Start a new query
D3D11_QUERY_DESC query_desc {
D3D11_QUERY_TIMESTAMP, 0x00
};
duration duration_;
ID3D11Query* pQuery = nullptr;
if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery)))
{
InterlockedExchangePointer ((void **)&technique.timer.timer.start.async, pQuery);
_immediate_context->End (pQuery);
}
}
#endif
bool is_default_depthstencil_cleared = false;
// Setup shader constants
if (technique.uniform_storage_index >= 0)
{
const auto constant_buffer =
_constant_buffers [technique.uniform_storage_index].get ();
D3D11_MAPPED_SUBRESOURCE mapped = { };
const HRESULT hr =
_immediate_context->Map (constant_buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped);
if (SUCCEEDED (hr))
{
CopyMemory (mapped.pData, get_uniform_value_storage().data() + technique.uniform_storage_offset, mapped.RowPitch);
_immediate_context->Unmap (constant_buffer, 0);
}
else
{
LOG(ERROR) << "Failed to map constant buffer! HRESULT is '" << std::hex << hr << std::dec << "'!";
}
_immediate_context->VSSetConstantBuffers (0, 1, &constant_buffer);
_immediate_context->PSSetConstantBuffers (0, 1, &constant_buffer);
}
for (const auto &pass_object : technique.passes)
{
const d3d11_pass_data &pass =
*pass_object->as <d3d11_pass_data> ();
// Setup states
_immediate_context->VSSetShader (pass.vertex_shader.get (), nullptr, 0);
_immediate_context->PSSetShader (pass.pixel_shader.get (), nullptr, 0);
//if (pass.shader_resources.empty ())
// continue;
static const float blendfactor [4] = { 1.0f, 1.0f, 1.0f, 1.0f };
_immediate_context->OMSetBlendState (pass.blend_state.get (), blendfactor, D3D11_DEFAULT_SAMPLE_MASK);
_immediate_context->OMSetDepthStencilState (pass.depth_stencil_state.get (), pass.stencil_reference);
// Save back buffer of previous pass
_immediate_context->CopyResource ( _backbuffer_texture.get (),
_backbuffer_resolved.get () );
// Setup shader resources
_immediate_context->VSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), pass.shader_resources.data ());
_immediate_context->PSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), pass.shader_resources.data ());
// Setup render targets
if ( static_cast <UINT> (pass.viewport.Width) == _width &&
static_cast <UINT> (pass.viewport.Height) == _height )
{
_immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, pass.render_targets, _default_depthstencil.get());
if (!is_default_depthstencil_cleared)
{
is_default_depthstencil_cleared = true;
_immediate_context->ClearDepthStencilView (_default_depthstencil.get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}
}
else
{
_immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, pass.render_targets, nullptr);
}
_immediate_context->RSSetViewports (1, &pass.viewport);
if (pass.clear_render_targets)
{
for (const auto target : pass.render_targets)
{
if (target != nullptr)
{
constexpr float color [4] = { 0.0f, 0.0f, 0.0f, 0.0f };
_immediate_context->ClearRenderTargetView(target, color);
}
}
}
// Draw triangle
_immediate_context->Draw (3, 0);
_vertices += 3;
_drawcalls += 1;
// Reset render targets
_immediate_context->OMSetRenderTargets ( 0, nullptr, nullptr );
// Reset shader resources
ID3D11ShaderResourceView* null [D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT] = { nullptr };
_immediate_context->VSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), null);
_immediate_context->PSSetShaderResources (0, static_cast <UINT> (pass.shader_resources.size ()), null);
// Update shader resources
for (const auto resource : pass.render_target_resources)
{
if (resource == nullptr)
{
continue;
}
D3D11_SHADER_RESOURCE_VIEW_DESC resource_desc = { };
resource->GetDesc (&resource_desc);
if (resource_desc.Texture2D.MipLevels > 1)
{
_immediate_context->GenerateMips (resource);
}
}
}
#if 0
if (_techniques [0].timer.disjoint_query.active)
{
D3D11_QUERY_DESC query_desc {
D3D11_QUERY_TIMESTAMP, 0x00
};
ID3D11Query* pQuery = nullptr;
if (SUCCEEDED (_device->CreateQuery (&query_desc, &pQuery)))
{
InterlockedExchangePointer ((void **)&technique.timer.timer.end.async, pQuery);
_immediate_context->End (pQuery);
}
}
#endif
}
void
d3d11_runtime::render_imgui_draw_data (ImDrawData *draw_data)
{
ImGui_ImplDX11_RenderDrawLists (draw_data);
}
void
d3d11_runtime::detect_depth_source (void)
{
if ( _is_multisampling_enabled || _depth_source_table.empty () )
{
return;
}
depth_source_info best_info = { 0 };
ID3D11DepthStencilView *best_match = nullptr;
for (auto it = _depth_source_table.begin (); it != _depth_source_table.end ();)
{
const auto depthstencil = it->first;
auto &depthstencil_info = it->second;
if ((! depthstencil_info.invalidated) && (depthstencil->AddRef (), depthstencil->Release ()) == 1)
{
depthstencil_info.invalidated = TRUE;
depthstencil->Release ();
++it;
continue;
}
else
{
++it;
}
if (depthstencil_info.drawcall_count == 0)
{
continue;
}
if ((depthstencil_info.vertices_count * (1.2f - float(depthstencil_info.drawcall_count) / _drawcalls.load ())) >= (best_info.vertices_count * (1.2f - float(best_info.drawcall_count) / _drawcalls.load ())))
{
best_match = depthstencil;
best_info = depthstencil_info;
}
depthstencil_info.drawcall_count = depthstencil_info.vertices_count = 0;
}
static int overload_iters = 0;
if (_depth_source_table.load_factor () > 0.75f && (! (overload_iters++ % 15)))
{
concurrency::concurrent_unordered_map <ID3D11DepthStencilView *, depth_source_info> live_map;
// Trim the table
for (auto& it : _depth_source_table)
{
if (! it.second.invalidated)
{
live_map.insert (std::make_pair (it.first, it.second));
}
}
_depth_source_table.swap (live_map);
}
if (best_match != nullptr && _depthstencil != best_match)
{
create_depthstencil_replacement (best_match);
}
}
bool
d3d11_runtime::create_depthstencil_replacement (ID3D11DepthStencilView *depthstencil)
{
_depthstencil.reset ();
_depthstencil_replacement.reset ();
_depthstencil_texture.reset ();
_depthstencil_texture_srv.reset ();
if (depthstencil != nullptr)
{
_depthstencil = depthstencil;
depthstencil->GetResource (reinterpret_cast <ID3D11Resource **> (&_depthstencil_texture));
D3D11_TEXTURE2D_DESC texdesc = { };
_depthstencil_texture->GetDesc (&texdesc);
HRESULT hr = S_OK;
if ((texdesc.BindFlags & D3D11_BIND_SHADER_RESOURCE) == 0)
{
_depthstencil_texture.reset ();
switch (texdesc.Format)
{
case DXGI_FORMAT_R16_TYPELESS:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_D16_UNORM:
texdesc.Format = DXGI_FORMAT_R16_TYPELESS;
break;
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R32_TYPELESS:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_D32_FLOAT:
texdesc.Format = DXGI_FORMAT_R32_TYPELESS;
break;
default:
case DXGI_FORMAT_R24G8_TYPELESS:
case DXGI_FORMAT_D24_UNORM_S8_UINT:
texdesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
break;
case DXGI_FORMAT_R32G8X24_TYPELESS:
case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
texdesc.Format = DXGI_FORMAT_R32G8X24_TYPELESS;
break;
}
texdesc.BindFlags = D3D11_BIND_DEPTH_STENCIL |
D3D11_BIND_SHADER_RESOURCE;
hr =
_device->CreateTexture2D (&texdesc, nullptr, &_depthstencil_texture);
if (SUCCEEDED (hr))
{
D3D11_DEPTH_STENCIL_VIEW_DESC dsvdesc = { };
dsvdesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
switch (texdesc.Format)
{
case DXGI_FORMAT_R16_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D16_UNORM;
break;
case DXGI_FORMAT_R32_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D32_FLOAT;
break;
case DXGI_FORMAT_R24G8_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
break;
case DXGI_FORMAT_R32G8X24_TYPELESS:
dsvdesc.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
break;
}
hr =
_device->CreateDepthStencilView (_depthstencil_texture.get (), &dsvdesc, &_depthstencil_replacement);
}
}
if (FAILED (hr))
{
LOG(ERROR) << "Failed to create depth stencil replacement texture! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc = { };
srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvdesc.Texture2D.MipLevels = 1;
switch (texdesc.Format)
{
case DXGI_FORMAT_R16_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R16_FLOAT;
break;
case DXGI_FORMAT_R32_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R32_FLOAT;
break;
case DXGI_FORMAT_R24G8_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
break;
case DXGI_FORMAT_R32G8X24_TYPELESS:
srvdesc.Format = DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
break;
}
hr =
_device->CreateShaderResourceView (_depthstencil_texture.get (), &srvdesc, &_depthstencil_texture_srv);
if (FAILED (hr))
{
LOG (ERROR) << "Failed to create depth stencil replacement resource view! HRESULT is '" << std::hex << hr << std::dec << "'.";
return false;
}
if (_depthstencil != _depthstencil_replacement)
{
// Update auto depth stencil
com_ptr <ID3D11DepthStencilView> current_depthstencil = nullptr;
ID3D11RenderTargetView *targets [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
_immediate_context->OMGetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, ¤t_depthstencil);
if (current_depthstencil != nullptr && current_depthstencil == _depthstencil)
{
_immediate_context->OMSetRenderTargets (D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, targets, _depthstencil_replacement.get ());
}
for (auto& target : targets)
{
if (target != nullptr)
{
target->Release ();
}
}
}
}
// Update effect textures
_effect_shader_resources [2] = _depthstencil_texture_srv.get ();
for (const auto &technique : _techniques)
for (const auto &pass : technique.passes)
pass->as <d3d11_pass_data> ()->shader_resources [2] = _depthstencil_texture_srv.get ();
return true;
}
} | 50,562 | 20,086 |
// Copyright (C) 2020 Jรฉrรดme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <Client/States/AbstractState.hpp>
namespace bw
{
AbstractState::AbstractState(std::shared_ptr<StateData> stateData) :
m_stateData(std::move(stateData)),
m_isVisible(false)
{
m_onTargetChangeSizeSlot.Connect(m_stateData->window->OnRenderTargetSizeChange, [this](const Nz::RenderTarget*)
{
if (m_isVisible)
LayoutWidgets();
});
}
AbstractState::~AbstractState()
{
for (const auto& cleanupFunc : m_cleanupFunctions)
cleanupFunc();
for (WidgetEntry& entry : m_widgets)
entry.widget->Destroy();
}
void AbstractState::Enter(Ndk::StateMachine& /*fsm*/)
{
m_isVisible = true;
for (WidgetEntry& entry : m_widgets)
{
if (entry.wasVisible)
entry.widget->Show();
}
for (auto it = m_entities.begin(); it != m_entities.end();)
{
const Ndk::EntityHandle& entity = *it;
if (entity)
{
entity->Enable();
++it;
}
else
it = m_entities.erase(it);
}
LayoutWidgets();
}
void AbstractState::Leave(Ndk::StateMachine& /*fsm*/)
{
m_isVisible = false;
for (WidgetEntry& entry : m_widgets)
{
entry.wasVisible = entry.widget->IsVisible();
entry.widget->Hide();
}
for (auto it = m_entities.begin(); it != m_entities.end();)
{
const Ndk::EntityHandle& entity = *it;
if (entity)
{
entity->Disable();
++it;
}
else
it = m_entities.erase(it);
}
}
bool AbstractState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/)
{
return true;
}
void AbstractState::LayoutWidgets()
{
}
}
| 1,672 | 712 |
#ifndef PIXELWRITER_HPP
#define PIXELWRITER_HPP
#include "displayadapter.hpp"
#define PACKET_SINGLE_COLOR 0
#define PACKET_SOURCE_COPY 1
#define PACKET_SKIP 2
#define PACKET_NEXT_LINE 3
typedef struct pixel_packet
{
int count;
int value;
void *data;
int type;
} pixel_packet;
class PixelWriter
{
protected:
surface_rect dimensions;
int line_length;
public:
PixelWriter(surface_rect dimensions);
void set_line_length(int width);
virtual void write_pixeldata(int x_origin, int y_origin, const pixel_packet *operations, int packet_count) = 0;
virtual void copy_line(int x_origin, int y_origin, void *source, int numpixels) = 0;
};
#endif
| 715 | 263 |
#include <time.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include "../include/ttime.h"
#include "../include/arguments.h"
#include "../include/log.h"
// ___________________________________________
ttime::ttime()
{
period_set(CHECKPOINT_TTIME, arguments::checkpointv);
// std::cout<<"lasts 1 "<<arguments::checkpointv<<" "<<lasts[CHECKPOINT_TTIME]<<" "<<periods[CHECKPOINT_TTIME]<<std::endl;
period_set(WORKER_BALANCING, arguments::balancingv);
// std::cout<<"lasts 2 "<<lasts[WORKER_BALANCING]<<" "<<periods[WORKER_BALANCING]<<std::endl;
processRequest = new mytimer();
masterWalltime = new mytimer();
wall = new mytimer();
update = new mytimer();
split = new mytimer();
test = new mytimer();
workerExploretime = new mytimer();
pthread_mutex_init(&mutex_lasttime, NULL);
// printElapsed(wserver,"WSERVER");
}
ttime::~ttime()
{
delete processRequest;
delete masterWalltime;
delete wall;
delete update;
delete split;
}
void ttime::reset()
{
wall->isOn=false;
wall->elapsed.tv_sec=0;
wall->elapsed.tv_nsec=0;
processRequest->isOn=false;
processRequest->elapsed.tv_sec=0;
processRequest->elapsed.tv_nsec=0;
// wall.tv_nsec=0;
masterWalltime->isOn=false;
masterWalltime->elapsed.tv_sec=0;
masterWalltime->elapsed.tv_nsec=0;
// masterWalltime.tv_nsec=0;
// processRequest.tv_sec=0;
// processRequest.tv_nsec=0;
}
time_t
ttime::time_get()
{
time_t tmp;
time(&tmp);
return tmp;
}
void
ttime::wait(int index)
{
srand48(getpid());
double t = (unsigned int) (periods[index] * 1.0) * drand48();
std::cout << (unsigned int) t << std::endl << std::flush;
std::cout << "debut" << std::endl << std::flush;
sleep((unsigned int) t);
std::cout << "fin" << std::endl << std::flush;
}
// ___________________________________________
void
ttime::period_set(int index, time_t t)
{
srand48(getpid());
lasts[index] = (time_t) (time_get() - (t * 1.0) * drand48());
periods[index] = t;
}
bool
ttime::period_passed(int index)
{
time_t tmp = time_get();
// std::cout<<"time? "<<tmp<<"\t"<<lasts[index]<<"\t"<<periods[index]<<std::endl<<std::flush;
if ((tmp - lasts[index]) < periods[index]) return false;
// multi-core worker threads execute this function...
pthread_mutex_lock(&mutex_lasttime);
lasts[index] = tmp;
// std::cout<<"PASSED "<<lasts[index]<<"\n"<<std::flush;
pthread_mutex_unlock(&mutex_lasttime);
return true;
}
// ======================================
void
ttime::on(mytimer * t)
{
t->isOn = true;
clock_gettime(CLOCK_MONOTONIC, &t->start);
}
void
ttime::off(mytimer * t)
{
clock_gettime(CLOCK_MONOTONIC, &t->stop);
struct timespec diff = subtractTime(t->stop, t->start);
if (t->isOn) t->elapsed = addTime(t->elapsed, diff);
t->isOn = false;
}
void
ttime::printElapsed(mytimer * t, const char * name)
{
printf("%s\t:\t %lld.%.9ld\n", name, (long long) t->elapsed.tv_sec, t->elapsed.tv_nsec);
}
void
ttime::logElapsed(mytimer * t, const char * name)
{
FILE_LOG(logINFO) << name << "\t:" << (long long) t->elapsed.tv_sec << "." << t->elapsed.tv_nsec;
}
float
ttime::divide(mytimer * t1, mytimer * t2)
{
return (t1->elapsed.tv_sec + t1->elapsed.tv_nsec / 1e9) / (t2->elapsed.tv_sec + t2->elapsed.tv_nsec / 1e9);
}
float
ttime::masterLoadPerc()
{
return 100.0 * divide(masterWalltime, wall);
}
timespec
ttime::subtractTime(struct timespec t2, struct timespec t1)
{
t2.tv_sec -= t1.tv_sec;
t2.tv_nsec -= t1.tv_nsec;
while (t2.tv_nsec < 0) {
t2.tv_sec--;
t2.tv_nsec += NSECS;
}
return t2;
}
timespec
ttime::addTime(struct timespec t1, struct timespec t2)
{
t1.tv_sec += t2.tv_sec;
t1.tv_nsec += t2.tv_nsec;
while (t1.tv_nsec > NSECS) {
t1.tv_sec++;
t1.tv_nsec -= NSECS;
}
return t1;
}
| 3,974 | 1,624 |
/* ---------------------------------------------------------------------------
** This software is furnished "as is", without technical support,
** and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** nnfield2similarity.cpp
** Converts a nearest neighbour field to its equivalent similarity matrix
**
** Author: Sk. Mohammadul Haque
** Copyright (c) 2013 Sk. Mohammadul Haque
** For more details and updates, visit http://mohammadulhaque.alotspace.com
** -------------------------------------------------------------------------*/
#include <mex.h>
#include <cmath>
#include <vector>
#include <algorithm>
#include <functional>
#include <climits>
#include <stdint.h>
#ifdef __PARALLEL__
#include <omp.h>
#endif
#define DATA_TYPE int64_t
#define IS_REAL_2D_FULL_DOUBLE(P) (!mxIsComplex(P) && \
mxGetNumberOfDimensions(P)==2 && !mxIsSparse(P) && mxIsDouble(P))
#define IS_REAL_3D_OR_4D_FULL_INT32(P) (!mxIsComplex(P) && \
(mxGetNumberOfDimensions(P)==3 || mxGetNumberOfDimensions(P)==4) && !mxIsEmpty(P) && !mxIsSparse(P) && mxIsInt32(P))
#define IS_REAL_SCALAR(P) (IS_REAL_2D_FULL_DOUBLE(P) && mxGetNumberOfElements(P)==1)
#define SIMILARITY_OUT plhs[0]
#define NNF_IN prhs[0]
#define WTTYPE_IN prhs[1]
#define SIGMA_IN prhs[2]
#define NORMALIZED_IN prhs[3]
#define SYMMETRIC_IN prhs[4]
#define PATCHSIZE_IN prhs[5]
#define ALPHA_IN prhs[6]
#define THRESHOLD_IN prhs[7]
#define MASK_IN prhs[8]
#define REFIMG_SIZE_IN prhs[9]
using namespace std;
typedef vector<DATA_TYPE>::const_iterator vecintiter;
struct ordering
{
bool operator ()(pair<DATA_TYPE, vecintiter> const& a, pair<DATA_TYPE, vecintiter> const& b)
{
return *(a.second)<*(b.second);
}
};
typedef vector<double>::const_iterator vecdoubleiter;
template <typename T>vector<T> sort_from_ref(vector<T> const& in, vector<pair<DATA_TYPE, vecintiter> > const& reference)
{
vector<T> ret(in.size());
DATA_TYPE const size = in.size();
for (DATA_TYPE i=0; i<size; ++i)ret[i] = in[reference[i].first];
return ret;
}
template <typename T>vector<T> sort_from_ref(vector<T> const& in, vector<pair<DATA_TYPE, vecdoubleiter> > const& reference)
{
vector<T> ret(in.size());
DATA_TYPE const size = in.size();
for(DATA_TYPE i=0; i<size; ++i) ret[i] = in[reference[i].first];
return ret;
}
template <typename T> pair<bool,double*> get_element(const T& row, const T& col, const mxArray *spmat)
{
bool flag = 0;
double *valmat = mxGetPr(spmat), *val = NULL;
mwIndex *is = mxGetIr(spmat), *js = mxGetJc(spmat);
for(T i = js[col]; i<js[col+1]; i++)
{
if(is[i]==row)
{
flag = true;
val = &(valmat[i]);
break;
}
}
pair<bool, double*> ret = make_pair(flag, val);
return ret;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double sigmasquared = 65536.0, *similarity = NULL, *texturemat = NULL, *refimg_size = NULL, alpha = 1.0, threshold = static_cast<double>(DBL_MAX);
double **mask = NULL, *rmask = NULL;
int32_t *nnf = NULL;
bool normalized = false, texture = false, symmetric = false, same_image = false;
int ndims, NNN = 0, wttype = 0;
DATA_TYPE NNF_DIMS[4] = {0,0,0,0}, NELEMS = 0, winoffset[2] = {0,0}, patchsize_minus_one[2] = {0,0}, patchsize[2] = {1,1};
DATA_TYPE REFIMG_SIZE[2] = {0,0}, REFIMG_SIZE_REDUCED[2] = {0,0};
vector<vector<DATA_TYPE> > idx_x;
vector<vector<DATA_TYPE> > idx_y;
vector<vector<double> > idx_d;
const mwSize *NNF_DIMS_ORI = NULL;
mwIndex *is = NULL, *js = NULL;
/* check number of arguments */
if(nrhs<1 || nrhs>10) mexErrMsgTxt("Wrong number of input arguments.");
else if(nlhs>1) mexErrMsgTxt("Too many output arguments.");
/* check all arguments one by one if valid or set default if empty */
if(!IS_REAL_3D_OR_4D_FULL_INT32(NNF_IN)||mxIsEmpty(NNF_IN)) mexErrMsgTxt("NNF must be a real 3D or 4D full int32 array.");
if(nrhs<8) threshold = static_cast<double>(DBL_MAX);
else
{
if(mxIsEmpty(THRESHOLD_IN)) threshold = static_cast<double>(DBL_MAX);
else
{
if(!IS_REAL_SCALAR(THRESHOLD_IN) ||(mxGetScalar(THRESHOLD_IN)<=0.0)) mexErrMsgTxt("THRESHOLD must be real positive scalar or empty.");
threshold = mxGetScalar(THRESHOLD_IN);
}
}
if(nrhs<7) alpha = 1.0;
else
{
if(mxIsEmpty(ALPHA_IN)) alpha = 1.0;
else
{
if(!IS_REAL_SCALAR(ALPHA_IN)) mexErrMsgTxt("ALPHA must be real scalar or empty.");
alpha = mxGetScalar(ALPHA_IN);
}
}
if(nrhs<6)
{
winoffset[0] = 0;
winoffset[1] = 0;
}
else
{
if(mxIsEmpty(PATCHSIZE_IN))
{
winoffset[0] = 0;
winoffset[1] = 0;
}
else
{
if(!IS_REAL_SCALAR(PATCHSIZE_IN)||mxGetScalar(PATCHSIZE_IN)<1.0||(static_cast<int>(mxGetScalar(PATCHSIZE_IN))%2==0))
{
if(!IS_REAL_2D_FULL_DOUBLE(PATCHSIZE_IN)||(mxGetM(PATCHSIZE_IN)*mxGetN(PATCHSIZE_IN))!=2||(static_cast<int>(mxGetPr(PATCHSIZE_IN)[0])%2==0)||(static_cast<int>(mxGetPr(PATCHSIZE_IN)[1])%2==0)) mexErrMsgTxt("PATCHSIZE must be real positive scalar odd integer or 2 element odd integer matrix or empty.");
winoffset[0] = (static_cast<int>(mxGetPr(PATCHSIZE_IN)[0])-1)/2;
winoffset[1] = (static_cast<int>(mxGetPr(PATCHSIZE_IN)[1])-1)/2;
}
else
{
winoffset[0] = (static_cast<int>(mxGetScalar(PATCHSIZE_IN))-1)/2;
winoffset[1] = winoffset[0];
}
}
}
patchsize_minus_one[0] = 2*winoffset[0];
patchsize_minus_one[1] = 2*winoffset[1];
patchsize[0] = patchsize_minus_one[0]+1;
patchsize[1] = patchsize_minus_one[1]+1;
if(nrhs<5) symmetric = false;
else
{
if(mxIsEmpty(SYMMETRIC_IN)) symmetric = false;
else
{
if(!IS_REAL_SCALAR(SYMMETRIC_IN)) mexErrMsgTxt("SYMMETRIC must be 0, 1 or empty.");
symmetric = static_cast<bool>(mxGetScalar(SYMMETRIC_IN));
}
}
if(nrhs<4) normalized = false;
else
{
if(mxIsEmpty(NORMALIZED_IN)) normalized = false;
else
{
if(!IS_REAL_SCALAR(NORMALIZED_IN)) mexErrMsgTxt("NORMALIZED must be real scalar or empty.");
normalized = static_cast<bool>(mxGetScalar(NORMALIZED_IN));
}
}
if(nrhs<3) sigmasquared = 32768.0; /* 65536.0/2 */
else
{
if((!IS_REAL_SCALAR(SIGMA_IN))&&(!IS_REAL_2D_FULL_DOUBLE(SIGMA_IN))) mexErrMsgTxt("SIGMA must be real scalar, matrix or empty.");
if(IS_REAL_SCALAR(SIGMA_IN)) texture = false;
else texture = true;
if(mxIsEmpty(SIGMA_IN))
{
texture = false;
sigmasquared = 32768.0; /* 65536.0/2 */
}
else if(texture==false)
{
sigmasquared = mxGetScalar(SIGMA_IN);
sigmasquared *= sigmasquared;
sigmasquared *= 2;
}
else texturemat = mxGetPr(SIGMA_IN);
}
if(nrhs<2) wttype = 0;
else
{
if(mxIsEmpty(WTTYPE_IN)) wttype = 0;
else
{
if(!IS_REAL_SCALAR(WTTYPE_IN)) mexErrMsgTxt("WTTYPE must be real scalar or empty.");
wttype = mxGetScalar(WTTYPE_IN);
}
}
if((wttype==1)&&(texture==1)) wttype = 2;
/* get pointer to NN-Field and its dimensions */
nnf = reinterpret_cast<int32_t*>(mxGetPr(NNF_IN));
NNF_DIMS_ORI = mxGetDimensions(NNF_IN);
ndims = mxGetNumberOfDimensions(NNF_IN);
switch(ndims)
{
case 3:
NNF_DIMS[0] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[0]);
NNF_DIMS[1] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[1]);
NNF_DIMS[2] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[2]);
NNF_DIMS[3] = 1;
NNN = 1;
break;
case 4:
NNF_DIMS[0] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[0]);
NNF_DIMS[1] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[1]);
NNF_DIMS[2] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[2]);
NNF_DIMS[3] = static_cast<DATA_TYPE>(NNF_DIMS_ORI[3]);
NNN = NNF_DIMS[3];
break;
default:
mexErrMsgTxt("NNF size error.");
break;
}
size_t matelem = NNF_DIMS[0]*NNF_DIMS[1];
size_t refmatelem;
idx_x.resize(NNN);
idx_y.resize(NNN);
idx_d.resize(NNN);
if(nrhs<10)
{
REFIMG_SIZE[0] = NNF_DIMS[0];
REFIMG_SIZE[1] = NNF_DIMS[1];
}
else
{
if(mxIsEmpty(REFIMG_SIZE_IN))
{
REFIMG_SIZE[0] = NNF_DIMS[0];
REFIMG_SIZE[1] = NNF_DIMS[1];
}
else
{
if(!IS_REAL_2D_FULL_DOUBLE(REFIMG_SIZE_IN)||(mxGetM(REFIMG_SIZE_IN)*mxGetN(REFIMG_SIZE_IN)!=2)) mexErrMsgTxt("REFIMG_SIZE must be real positive 2X1 matrix or empty.");
refimg_size = mxGetPr(REFIMG_SIZE_IN);
REFIMG_SIZE[0] = static_cast<DATA_TYPE>(refimg_size[0]);
REFIMG_SIZE[1] = static_cast<DATA_TYPE>(refimg_size[1]);
}
}
refmatelem = REFIMG_SIZE[0]*REFIMG_SIZE[1];
if((REFIMG_SIZE[0]==NNF_DIMS[0]) && (REFIMG_SIZE[1]==NNF_DIMS[1])) same_image = true;
else same_image = false;
REFIMG_SIZE_REDUCED[0] = REFIMG_SIZE[0]-2*winoffset[0];
REFIMG_SIZE_REDUCED[1] = REFIMG_SIZE[1]-2*winoffset[1];
if(nrhs<9||mxIsEmpty(MASK_IN))
{
mask = new double*[patchsize[0]];
for(int i=0; i<patchsize[0]; ++i)
{
mask[i] = new double[patchsize[1]];
for(int j=0; j<patchsize[1]; ++j)
{
if((i==winoffset[0])&&(j==winoffset[1])) mask[i][j] = 1.0;
else mask[i][j] = 0.0;
}
}
}
else
{
if(!IS_REAL_2D_FULL_DOUBLE(MASK_IN)) mexErrMsgTxt("MASK must be real full array or empty.");
rmask = mxGetPr(MASK_IN);
mask = new double*[patchsize[0]];
for(int i=0; i<patchsize[0]; ++i)
{
mask[i] = new double[patchsize[1]];
for(int j=0; j<patchsize[1]; ++j) mask[i][j] = rmask[j*patchsize[0]+i];
}
}
/* based on the conditions */
switch(wttype)
{
case 0: /* uniform weights without texture */
{
#ifdef __PARALLEL__
#pragma omp parallel for shared(NNF_DIMS, nnf, idx_x, idx_y, idx_d)
#endif
for(DATA_TYPE k=0; k<NNN; ++k)
{
DATA_TYPE tsz = NNF_DIMS[0]*NNF_DIMS[1];
DATA_TYPE idx_start_y = tsz*NNF_DIMS[2]*k;
DATA_TYPE idx_start_x = tsz + idx_start_y;
DATA_TYPE idx_start_d = tsz + idx_start_x;
for(DATA_TYPE j=0; j<static_cast<DATA_TYPE>(NNF_DIMS[1]-patchsize_minus_one[1]); ++j)
{
DATA_TYPE idx_curr = (NNF_DIMS[0]*j);
DATA_TYPE idx_start_xx = idx_start_x+idx_curr;
DATA_TYPE idx_start_yy = idx_start_y+idx_curr;
DATA_TYPE idx_start_dd = idx_start_d+idx_curr;
for(DATA_TYPE i=0; i<static_cast<DATA_TYPE>(NNF_DIMS[0]-patchsize_minus_one[0]); ++i)
{
DATA_TYPE curr_x, curr_y, curr_d;
curr_d = nnf[idx_start_dd+i];
for(DATA_TYPE mj=0; mj<=patchsize_minus_one[1]; ++mj)
{
curr_y = nnf[idx_start_yy+i]+mj;
for(DATA_TYPE mi=0; mi<=patchsize_minus_one[0]; ++mi)
{
curr_x = nnf[idx_start_xx+i]+mi;
if(mask[mi][mj]>0.0 && (curr_x>=0 && curr_x<REFIMG_SIZE[0] && curr_y>=0 && curr_y<REFIMG_SIZE[1] )&& (!same_image ||((idx_curr+i+(mj*NNF_DIMS[0]+mi))!=(curr_x+curr_y*REFIMG_SIZE[0]))) && (static_cast<double>(curr_d)<threshold))
{
idx_x[k].push_back(idx_curr+i+(mj*NNF_DIMS[0]+mi));
idx_y[k].push_back(curr_x+curr_y*REFIMG_SIZE[0]);
idx_d[k].push_back(mask[mi][mj]);
if(symmetric && same_image)
{
idx_y[k].push_back(idx_curr+i+(mj*NNF_DIMS[0]+mi));
idx_x[k].push_back(curr_x+curr_y*REFIMG_SIZE[0]);
idx_d[k].push_back(mask[mi][mj]);
}
}
}
}
}
}
if(k==0 && same_image)
{
for(DATA_TYPE j=winoffset[1]; j<static_cast<DATA_TYPE>(NNF_DIMS[1]-winoffset[1]); ++j)
{
DATA_TYPE idx_curr = (NNF_DIMS[0]*j);
for(DATA_TYPE i=winoffset[0]; i<static_cast<DATA_TYPE>(NNF_DIMS[0]-winoffset[0]); ++i)
{
idx_x[k].push_back(idx_curr+i);
idx_y[k].push_back(idx_curr+i);
idx_d[k].push_back(alpha);
}
}
}
}
break;
}
case 1: /* gaussian weights without texture */
{
#ifdef __PARALLEL__
#pragma omp parallel for shared(NNF_DIMS, nnf, idx_x, idx_y, idx_d)
#endif
for(DATA_TYPE k=0; k<NNN; ++k)
{
DATA_TYPE tsz = NNF_DIMS[0]*NNF_DIMS[1];
DATA_TYPE idx_start_y = tsz*NNF_DIMS[2]*k;
DATA_TYPE idx_start_x = tsz + idx_start_y;
DATA_TYPE idx_start_d = tsz + idx_start_x;
double expval;
for(DATA_TYPE j=0; j<static_cast<DATA_TYPE>(NNF_DIMS[1]-patchsize_minus_one[1]); ++j)
{
DATA_TYPE idx_curr = (NNF_DIMS[0]*j);
DATA_TYPE idx_start_xx = idx_start_x+idx_curr;
DATA_TYPE idx_start_yy = idx_start_y+idx_curr;
DATA_TYPE idx_start_dd = idx_start_d+idx_curr;
for(DATA_TYPE i=0; i<static_cast<DATA_TYPE>(NNF_DIMS[0]-patchsize_minus_one[0]); ++i)
{
DATA_TYPE curr_x, curr_y, curr_d;
curr_d = nnf[idx_start_dd+i];
for(DATA_TYPE mj=0; mj<=patchsize_minus_one[1]; ++mj)
{
curr_y = nnf[idx_start_yy+i]+mj;
for(DATA_TYPE mi=0; mi<=patchsize_minus_one[0]; ++mi)
{
curr_x = nnf[idx_start_xx+i]+mi;
if(mask[mi][mj]>0.0 && (curr_x>=0 && curr_x<REFIMG_SIZE[0] && curr_y>=0 && curr_y<REFIMG_SIZE[1] )&& (!same_image ||((idx_curr+i+(mj*NNF_DIMS[0]+mi))!=(curr_x+curr_y*REFIMG_SIZE[0]))) && (static_cast<double>(curr_d)<threshold))
{
expval = exp(-static_cast<double>(curr_d)/sigmasquared)*mask[mi][mj];
idx_x[k].push_back(idx_curr+i+(mj*NNF_DIMS[0]+mi));
idx_y[k].push_back(curr_x+curr_y*REFIMG_SIZE[0]);
idx_d[k].push_back(expval);
if(symmetric && same_image)
{
idx_y[k].push_back(idx_curr+i+(mj*NNF_DIMS[0]+mi));
idx_x[k].push_back(curr_x+curr_y*REFIMG_SIZE[0]);
idx_d[k].push_back(expval);
}
}
}
}
}
}
if(k==0 && same_image)
{
for(DATA_TYPE j=winoffset[1]; j<static_cast<DATA_TYPE>(NNF_DIMS[1]-winoffset[1]); ++j)
{
DATA_TYPE idx_curr = (NNF_DIMS[0]*j);
for(DATA_TYPE i=winoffset[0]; i<static_cast<DATA_TYPE>(NNF_DIMS[0]-winoffset[0]); ++i)
{
idx_x[k].push_back(idx_curr+i);
idx_y[k].push_back(idx_curr+i);
idx_d[k].push_back(alpha);
}
}
}
}
break;
}
case 2: /* gaussian weight with texture */
{
/* check if texturemat is valid */
if((NNF_DIMS[0]!=static_cast<DATA_TYPE>(mxGetM(SIGMA_IN))) || (NNF_DIMS[1]!=static_cast<DATA_TYPE>(mxGetN(SIGMA_IN))))
{
// free mask memory created here before abnormal exit
for(int i=0; i<patchsize[0]; ++i)
{
delete []mask[i];
}
delete []mask;
mexErrMsgTxt("SIGMA TEXTURE size error.");
}
#ifdef __PARALLEL__
#pragma omp parallel for shared(NNF_DIMS, nnf, idx_x, idx_y, idx_d)
#endif
for(DATA_TYPE k=0; k<NNN; ++k)
{
DATA_TYPE curr_x, curr_y, curr_d;
DATA_TYPE tsz = NNF_DIMS[0]*NNF_DIMS[1];
DATA_TYPE idx_start_y = tsz*NNF_DIMS[2]*k;
DATA_TYPE idx_start_x = tsz + idx_start_y;
DATA_TYPE idx_start_d = tsz + idx_start_x;
double expval;
for(DATA_TYPE j=0; j<static_cast<DATA_TYPE>(NNF_DIMS[1]-patchsize_minus_one[1]); ++j)
{
DATA_TYPE idx_curr = (NNF_DIMS[0]*j);
DATA_TYPE idx_start_xx = idx_start_x+idx_curr;
DATA_TYPE idx_start_yy = idx_start_y+idx_curr;
DATA_TYPE idx_start_dd = idx_start_d+idx_curr;
for(DATA_TYPE i=0; i<static_cast<DATA_TYPE>(NNF_DIMS[0]-patchsize_minus_one[0]); ++i)
{
DATA_TYPE curr_x, curr_y, curr_d;
curr_d = nnf[idx_start_dd+i];
for(DATA_TYPE mj=0; mj<=patchsize_minus_one[1]; ++mj)
{
curr_y = nnf[idx_start_yy+i]+mj;
for(DATA_TYPE mi=0; mi<=patchsize_minus_one[0]; ++mi)
{
curr_x = nnf[idx_start_xx+i]+mi;
if(mask[mi][mj]>0.0 && (curr_x>=0 && curr_x<REFIMG_SIZE[0] && curr_y>=0 && curr_y<REFIMG_SIZE[1] )&& (!same_image ||((idx_curr+i+(mj*NNF_DIMS[0]+mi))!=(curr_x+curr_y*REFIMG_SIZE[0]))) && (static_cast<double>(curr_d)<threshold))
{
expval = exp(-static_cast<double>(curr_d)*texturemat[idx_curr+i]/sigmasquared)*mask[mi][mj]; /* texture_mat */
idx_x[k].push_back(idx_curr+i+(mj*NNF_DIMS[0]+mi));
idx_y[k].push_back(curr_x+curr_y*REFIMG_SIZE[0]);
idx_d[k].push_back(expval);
if(symmetric && same_image)
{
idx_y[k].push_back(idx_curr+i+(mj*NNF_DIMS[0]+mi));
idx_x[k].push_back(curr_x+curr_y*REFIMG_SIZE[0]);
idx_d[k].push_back(expval);
}
}
}
}
}
}
if(k==0 && same_image)
{
for(DATA_TYPE j=winoffset[1]; j<static_cast<DATA_TYPE>(NNF_DIMS[1]-winoffset[1]); ++j)
{
DATA_TYPE idx_curr = (NNF_DIMS[0]*j);
for(DATA_TYPE i=winoffset[0]; i<static_cast<DATA_TYPE>(NNF_DIMS[0]-winoffset[0]); ++i)
{
idx_x[k].push_back(idx_curr+i);
idx_y[k].push_back(idx_curr+i);
idx_d[k].push_back(alpha);
}
}
}
}
break;
}
default:
// free mask memory created here before abnormal exit
for(int i=0; i<patchsize[0]; ++i)
{
delete []mask[i];
}
delete []mask;
mexErrMsgTxt("WTTYPE is invalid.");
break;
}
// free mask memory created here before abnormal exit
for(int i=0; i<patchsize[0]; ++i)
{
delete []mask[i];
}
delete []mask;
/* collect all the entries in NNF in 3 single vectors */
for(int k=1; k<NNN; ++k)
{
idx_x[0].insert(idx_x[0].end(), idx_x[k].begin(), idx_x[k].end());
idx_y[0].insert(idx_y[0].end(), idx_y[k].begin(), idx_y[k].end());
idx_d[0].insert(idx_d[0].end(), idx_d[k].begin(), idx_d[k].end());
idx_x[k].clear();
idx_y[k].clear();
idx_d[k].clear();
}
/* sort the 3 vectors in order of location in matrix */
vector<DATA_TYPE> tempvec(idx_y[0]);
transform(tempvec.begin(), tempvec.end(), tempvec.begin(), bind1st(multiplies<DATA_TYPE>(), matelem));
transform(tempvec.begin(), tempvec.end(), idx_x[0].begin(), tempvec.begin(), plus<DATA_TYPE>());
vector<pair<DATA_TYPE, vecintiter> > order(tempvec.size());
DATA_TYPE n = 0;
for (vecintiter it = tempvec.begin(); it != tempvec.end(); ++it, ++n) order[n] = make_pair(n, it);
sort(order.begin(), order.end(), ordering());
vector<DATA_TYPE> sorted_idx_x = sort_from_ref(idx_x[0], order), trimmed_idx_x;
vector<DATA_TYPE> sorted_idx_y = sort_from_ref(idx_y[0], order), trimmed_idx_y;
vector<double> sorted_idx_d = sort_from_ref(idx_d[0], order), trimmed_idx_d;
DATA_TYPE oldidx = -1, tmp_x, tmp_y;
double maxval = 0;
size_t m;
for(m=0; m<order.size(); ++m)
{
if(oldidx==*(order[m].second))
{
/* if(maxval<sorted_idx_d[m])
* {
* tmp_x = sorted_idx_x[m];
* tmp_y = sorted_idx_y[m];
* }
*/
maxval += sorted_idx_d[m];
}
else
{
if(m>0)
{
trimmed_idx_x.push_back(tmp_x);
trimmed_idx_y.push_back(tmp_y);
trimmed_idx_d.push_back(maxval);
maxval = 0;
}
maxval = sorted_idx_d[m];
tmp_x = sorted_idx_x[m];
tmp_y = sorted_idx_y[m];
}
oldidx = *(order[m].second);
}
if(m>0)
{
trimmed_idx_x.push_back(tmp_x);
trimmed_idx_y.push_back(tmp_y);
trimmed_idx_d.push_back(maxval);
}
NELEMS = trimmed_idx_d.size();
/* first check if ref image size is large enough */
if((NELEMS>0) && ((trimmed_idx_y[NELEMS-1])>=(REFIMG_SIZE[1]*REFIMG_SIZE[0]))) mexErrMsgTxt("REF IMG SIZE is smaller than required.");
/* create the output similarity matrix */
SIMILARITY_OUT = mxCreateSparse(matelem, refmatelem, NELEMS, mxREAL);
if(SIMILARITY_OUT == NULL) mexErrMsgTxt("Cannot allocate enough space.");
similarity = mxGetPr(SIMILARITY_OUT);
is = mxGetIr(SIMILARITY_OUT);
js = mxGetJc(SIMILARITY_OUT);
DATA_TYPE tmp = -1, col_counter = 0;
size_t k;
for(k=0; k<trimmed_idx_d.size(); ++k)
{
is[k] = trimmed_idx_x[k];
if((trimmed_idx_y[k])>tmp)
{
for(DATA_TYPE i=1+tmp; i<=trimmed_idx_y[k] ; ++i)
{
js[col_counter] = k;
++col_counter;
}
tmp = trimmed_idx_y[k];
}
similarity[k] = trimmed_idx_d[k];
}
for(size_t i=col_counter; i<=refmatelem; ++i) js[i] = k;
/* normalize if any */
if(normalized)
{
vector<double> rowsum(matelem, 0.0) ;
for(DATA_TYPE i=0; i<NELEMS; ++i)
{
rowsum[is[i]] += trimmed_idx_d[i];
}
for(DATA_TYPE i=0; i<NELEMS; ++i)
{
if(rowsum[is[i]]>0.0) similarity[i] /= rowsum[is[i]];
}
}
}
| 23,850 | 9,048 |
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/detail/sandbox/hash_map.hpp>
#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/functional.hpp>
#include <boost/hana/integral.hpp>
#include <boost/hana/list/instance.hpp>
#include <boost/hana/pair.hpp>
using namespace boost::hana;
BOOST_HANA_CONSTEXPR_LAMBDA auto check_fold = [](auto ...pairs) {
auto values = fmap(second, list(pairs...));
auto result = foldr(hash_map(pairs...), list(), cons);
BOOST_HANA_CONSTANT_ASSERT(elem(permutations(values), result));
};
template <int k, int v>
BOOST_HANA_CONSTEXPR_LAMBDA auto p = pair(int_<k>, int_<v>);
int main() {
check_fold();
check_fold(p<1, 1>);
check_fold(p<1, 1>, p<2, 2>);
check_fold(p<1, 1>, p<2, 2>, p<3, 3>);
check_fold(p<1, 1>, p<2, 2>, p<3, 3>, p<4, 4>);
}
| 1,001 | 432 |
// 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 "chrome/browser/install_verification/win/module_ids.h"
#include <utility>
#include "base/logging.h"
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "chrome/grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
struct { size_t id; const char* module_name_digest; }
kExpectedInstallModules[] = {
{1u, "c8cc47613e155f2129f480c6ced84549"}, // chrome.dll
{2u, "49b78a23b0d8d5d8fb60d4e472b22764"}, // chrome_child.dll
};
// Parses a line consisting of a positive decimal number and a 32-digit
// hexadecimal number, separated by a space. Inserts the output, if valid, into
// |module_ids|. Unexpected leading or trailing characters will cause
// the line to be ignored, as will invalid decimal/hexadecimal characters.
void ParseAdditionalModuleID(
const base::StringPiece& line,
ModuleIDs* module_ids) {
DCHECK(module_ids);
base::CStringTokenizer line_tokenizer(line.begin(), line.end(), " ");
if (!line_tokenizer.GetNext())
return; // Empty string.
base::StringPiece id_piece(line_tokenizer.token_piece());
if (!line_tokenizer.GetNext())
return; // No delimiter (' ').
base::StringPiece digest_piece(line_tokenizer.token_piece());
if (line_tokenizer.GetNext())
return; // Unexpected trailing characters.
unsigned id = 0;
if (!StringToUint(id_piece, &id))
return; // First token was not decimal.
if (digest_piece.length() != 32)
return; // Second token is not the right length.
for (base::StringPiece::const_iterator it = digest_piece.begin();
it != digest_piece.end(); ++it) {
if (!base::IsHexDigit(*it))
return; // Second token has invalid characters.
}
// This is a valid line.
module_ids->insert(std::make_pair(digest_piece.as_string(), id));
}
} // namespace
void ParseAdditionalModuleIDs(
const base::StringPiece& raw_data,
ModuleIDs* module_ids) {
DCHECK(module_ids);
base::CStringTokenizer file_tokenizer(raw_data.begin(),
raw_data.end(),
"\r\n");
while (file_tokenizer.GetNext()) {
ParseAdditionalModuleID(base::StringPiece(file_tokenizer.token_piece()),
module_ids);
}
}
void LoadModuleIDs(ModuleIDs* module_ids) {
for (size_t i = 0; i < arraysize(kExpectedInstallModules); ++i) {
module_ids->insert(
std::make_pair(
kExpectedInstallModules[i].module_name_digest,
kExpectedInstallModules[i].id));
}
base::StringPiece additional_module_ids;
#if defined(GOOGLE_CHROME_BUILD)
additional_module_ids =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_ADDITIONAL_MODULE_IDS);
#endif
ParseAdditionalModuleIDs(additional_module_ids, module_ids);
}
| 3,123 | 1,095 |
/*
* @lc app=leetcode.cn id=50 lang=cpp
*
* [50] Pow(x, n)
*/
// @lc code=start
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Solution {
public:
double myPow(double x, int n) {
long long N = n;
return (N > 0 ? quickMul(x, N) : (1.0 / quickMul(x, -N)));
}
double quickMul(double x, long long N)
{
// if(N == 0)
// return 1.0;
// double y = quickMul(x, N/2);
// return N % 2 == 0 ? y * y : y * y * x;
double ans = 1.0;
double x_contribute = x;
while(N > 0)
{
if(N & 1 == 1)
{
ans *= x_contribute;
}
x_contribute *= x_contribute;
N >>= 1;
}
return ans;
}
};
// @lc code=end
| 951 | 366 |
#include "DynamicSuffixArray.h"
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include <string.h>
#include <time.h>
#include <sys/time.h>
using namespace std;
//Common variables for some tests
dynsa::DynamicSuffixArray *a;
ustring dist_string;
float *fs;
int main( int argc, char* const argv[]){
dist_string = (ustring) "CCGAACACCCGTACCGAGGTGAGCACCCTCTGCATCAGCCAGTTCCGCTACAGCGCACAAATCCGTCCTTCNNNNNNNNNNNNNNNNNNNTTCCGTAGTGACCAAAGACTACACCTTTAAACGCCCCGGCTGGGCCGGACGTTTTGAACAGGAAGGCCAGCACCAGGACTACCAGCGCACGCAGTATGAAGTGTATGACTACCCCGGACGTTTCAAGAGCGCCCACGGGCAGAACTTTGCCCGCTGGCAGATGGACGGCTGGCGAAACAACGCAGAAACCGCGCGGGGAATGAGCCGCTCGCCGGAGATATGGCCGGGACGGCGAATTGTGCTGACGGGGCATCCGCAGGCGAACCTGAACCGGGAATGGCAGGTGGTGGCAAGTGAACTGCACGGCGAACAGCCACAGGCGGTGCCAGGACGGCAGGGAGCGGGGACGGCGCTGGAGAACCATTTTGCGGTGATCCCGGCAGACAGAACATGGCGACCACAGCCGTTGCTGAAACCGCTGGTCGACGGCCCGCAGAGCGC";
fs = DynRankS::createCharDistribution(dist_string, 512, 1);
a = new dynsa::DynamicSuffixArray(fs);
int result = Catch::Session().run(argc, argv);
return result;
}
TEST_CASE("Short setText", "[short]"){
ustring s = (ustring) "GTGAGTGAG";
ustring bwt = (ustring) "GGGATTA$GG";
a->setText(s, 10);
int sz = strlen((char*)s);
CHECK((memcmp(a->getText(), s, sz) == 0));
sz = strlen((char*)bwt);
REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0));
}
TEST_CASE("Short insert", "[short]"){
ustring s = (ustring) "GAAGT";
a->insertFactor(s, 3, 5);
s = (ustring) "GTGAAGTGAGTGAG";
ustring bwt = (ustring) "GGGGAATTT$AAGGG";
int sz = strlen((char*)s);
CHECK((memcmp(a->getText(), s, sz) == 0));
sz = strlen((char*)bwt);
REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0));
}
TEST_CASE("Short delete", "[short]"){
ustring s = (ustring) "GTGAGTGAG";
ustring bwt = (ustring) "GGGATTA$GG";
a -> deleteAt(3,5);
int sz = strlen((char*)s);
CHECK((memcmp(a->getText(), s, sz) == 0));
sz = strlen((char*)bwt);
REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0));
}
TEST_CASE("Short replace", "[short]"){
a -> replace((ustring) "TT", 3, 2);
ustring s = (ustring) "GTTTGTGAG";
ustring bwt = (ustring) "GGATT$GTTG";
int sz = strlen((char*)s);
CHECK((memcmp(a->getText(), s, sz) == 0));
sz = strlen((char*)bwt);
REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0));
}
TEST_CASE("Single insert", "[short]"){
a -> insertToText((uchar)'C', 4);
ustring s = (ustring) "GTTCTGTGAG";
ustring bwt = (ustring) "GGTATT$TGCG";
int sz = strlen((char*)s);
CHECK((memcmp(a->getText(), s, sz) == 0));
sz = strlen((char*)bwt);
REQUIRE((memcmp(a->getBWT(), bwt, sz) == 0));
}
TEST_CASE("1031 long bwt verification - test1", "[verification]"){
FILE* input = fopen("testdata/test1/GCA_000731455_1031.in", "r");
ustring s = new uchar[1033];
fscanf(input," %s", s);
fclose(input);
FILE* expected = fopen("testdata/test1/GCA_000731455_1031.out", "r");
ustring bwt = new uchar[1033];
fscanf(expected," %s", bwt);
fclose(expected);
int sz = strlen((char*)bwt);
a = new dynsa::DynamicSuffixArray(fs);
a -> setText(s, 1032);
REQUIRE((memcmp(a -> getBWT(), bwt, sz) == 0));
}
TEST_CASE("5385 long bwt verification - test2", "[verification]"){
FILE* input = fopen("testdata/test2/GCA_000731455_5385.in", "r");
ustring s = new uchar[5388];
fscanf(input," %s", s);
fclose(input);
FILE* expected = fopen("testdata/test2/GCA_000731455_5385.out", "r");
ustring bwt = new uchar[5388];
fscanf(expected," %s", bwt);
fclose(expected);
int sz = strlen((char*)bwt);
a = new dynsa::DynamicSuffixArray(fs);
a -> setText(s, 5386);
REQUIRE((memcmp(a -> getBWT(), bwt, sz) == 0));
}
TEST_CASE("35970 long bwt verification - test3", "[verification]"){
FILE* input = fopen("testdata/test3/GCA_000731455_35970.in", "r");
ustring s = new uchar[35972];
fscanf(input," %s", s);
fclose(input);
FILE* expected = fopen("testdata/test3/GCA_000731455_35970.out", "r");
ustring bwt = new uchar[35972];
fscanf(expected," %s", bwt);
fclose(expected);
int sz = strlen((char*)bwt);
a = new dynsa::DynamicSuffixArray(fs);
a -> setText(s, 35971);
REQUIRE((memcmp(a -> getBWT(), bwt, sz) == 0));
}
TEST_CASE("176616 large time monitor - test4", "[time]"){
FILE* input = fopen("testdata/test4/GCA_000731455_176616.in", "r");
ustring s = new uchar[176620];
fscanf(input," %s", s);
fclose(input);
a = new dynsa::DynamicSuffixArray(fs);
int sz = strlen((char*)s);
a -> setText(s, 176617);
REQUIRE(memcmp(a -> getText(), s, sz) == 0);
}
TEST_CASE("Check size after modifications", "[size]"){
FILE* input = fopen("testdata/test5/GCA_000731455_189561.in", "r");
ustring s = new uchar[189565];
fscanf(input," %s", s);
fclose(input);
a = new dynsa::DynamicSuffixArray(fs);
int sz = strlen((char*)s);
CHECK( a -> size() == 0);
CHECK( a -> isEmpty() == true);
a -> setText(s, 148);
CHECK( a -> size() == 148);
a -> insertFactor(s+1200, 37, 231);
CHECK( a -> size() == 379);
a -> deleteAt(47, 85);
CHECK( a -> size() == 294);
a -> deleteAt(1,280);
CHECK( a -> size() == 14);
a -> deleteAt(1,12);
CHECK( a -> isEmpty() == false);
REQUIRE( a -> size() == 2);
}
/*
* BWT for the example used in documentation
*/
TEST_CASE("Short setText1"," [short]") {
ustring s=(ustring) "CTCTGC";
ustring bwt=(ustring) "CG$TTCC";
a = new dynsa::DynamicSuffixArray(fs);
a->setText(s,7);
int sz=strlen((char*)s);
CHECK((memcmp(a->getText(),s,sz)==0));
sz=strlen((char*)s);
REQUIRE((memcmp(a->getBWT(),bwt,sz)==0));
}
TEST_CASE("Short insert1","[short]") {
ustring s=(ustring) "G";
a->insertFactor(s,3,1);
ustring bwt = (ustring) "CGG$TTCC";
s=(ustring) "CTGCTGC";
int sz=strlen((char*)s);
CHECK((memcmp(a->getText(),s,sz)==0));
sz=strlen((char*)bwt);
REQUIRE((memcmp(a->getBWT(),bwt,sz)==0));
}
TEST_CASE("524 into 3631 long bwt insert", "[insert]"){
FILE* input = fopen("testdata/test6/GCA_000731455_3631.in", "r");
ustring s1 = new uchar[3631];
fscanf(input," %s", s1);
fclose(input);
FILE* insert = fopen("testdata/test6/GCA_000731455_524.in", "r");
ustring s2 = new uchar[524];
fscanf(insert," %s", s2);
fclose(insert);
int sz1 = strlen((char*)s1);
int sz2 = strlen((char*)s2);
FILE* bwt = fopen("testdata/test6/GCA_000731455_3631ins.out", "r");
ustring s3 = new uchar[sz2+sz1];
fscanf(insert," %s", s3);
fclose(insert);
a = new dynsa::DynamicSuffixArray(fs);
a -> setText(s1, 3632);
a->insertFactor(s2,500,524);
REQUIRE((memcmp(a -> getBWT(), s3, sz1+sz2+1) == 0));
}
TEST_CASE("35970 delete - test7", "[delete]"){
FILE* input = fopen("testdata/test7/GCA_000731455_35970.in", "r");
ustring s = new uchar[35972];
fscanf(input," %s", s);
fclose(input);
FILE* deleted = fopen("testdata/test7/GCA_000731455_35970del.in", "r");
ustring del = new uchar[35972];
fscanf(deleted," %s", del);
fclose(deleted);
int sz = strlen((char*)del);
a = new dynsa::DynamicSuffixArray(fs);
a -> setText(s, 35971);
a ->deleteAt(4000,4000);
CHECK((memcmp(a -> getText(), del, 31970) == 0));
FILE* expected = fopen("testdata/test7/GCA_000731455_35970del", "r");
ustring bwt = new uchar[31971];
fscanf(expected," %s", bwt);
fclose(expected);
REQUIRE((memcmp(a -> getBWT(), bwt, 31971) == 0));
}
| 7,612 | 3,506 |
#include "abc185/d.cc"
#include "gtest/gtest.h"
TEST(abc185d, 1) { EXPECT_EQ(3, solve(5, 2, {1, 3})); }
TEST(abc185d, 2) { EXPECT_EQ(6, solve(13, 3, {13, 3, 9})); }
TEST(abc185d, 3) { EXPECT_EQ(0, solve(5, 5, {5, 2, 1, 4, 3})); }
TEST(abc185d, 4) { EXPECT_EQ(1, solve(1, 0, {})); }
| 286 | 184 |
#include "catch.h"
#include "Bucket.h"
#include "ServerStorage.h"
#include "OramInterface.h"
#include "RandForOramInterface.h"
#include "RandomForOram.h"
#include "UntrustedStorageInterface.h"
#include "OramReadPathEviction.h"
#include "OramReadPathEviction.h"
int* sampleDataReadPathEviction(int i) {
int* newArray = new int[Block::BLOCK_SIZE];
for (int j = 0; j < Block::BLOCK_SIZE; ++j) {
newArray[j] = i;
}
return newArray;
}
TEST_CASE("Test ORAM with read path eviction read very small numBlocks")
{
int bucketSize = 2;
int numBlocks = 1;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read small numBlocks")
{
int bucketSize = 2;
int numBlocks = 32;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read larger numBlocks")
{
int bucketSize = 2;
int numBlocks = 1024;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read numBlocks not power of 2")
{
int bucketSize = 2;
int numBlocks = 30;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read very small numBlocks, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 1;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read small numBlocks, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 32;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read larger numBlocks, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 1024;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
TEST_CASE("Test ORAM with read path eviction read numBlocks not power of 2, bucketSize = 4")
{
int bucketSize = 4;
int numBlocks = 30;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
// Uncomment the below test case to run for when the number of blocks is very large (=2^20).
/*
TEST_CASE("Test ORAM read path eviction read very large numBlocks", "[setup_det2]")
{
int bucketSize = 2;
int numBlocks = 1048576;
Bucket::setMaxSize(bucketSize);
UntrustedStorageInterface* storage = new ServerStorage();
RandForOramInterface* random = new RandomForOram();
OramInterface* oram = new OramReadPathEviction(storage, random, bucketSize, numBlocks);
int bound = numBlocks;
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::WRITE, i % numBlocks, sampleDataReadPathEviction(i%numBlocks));
}
for(int i = 0; i < bound; i++){
int* accessed = oram->access(OramInterface::Operation::READ, i % numBlocks, NULL);
for (unsigned int j = 0; j<Block::BLOCK_SIZE; ++j) {
int temp = accessed[j];
REQUIRE(temp == i%numBlocks);
}
}
Bucket::resetState();
ServerStorage::is_initialized = false;
ServerStorage::is_capacity_set = false;
RandomForOram::is_initialized = false;
RandomForOram::bound = -1;
}
*/
| 10,277 | 3,479 |
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void reverseArr(int arr[],int start,int end)
{
while(start<end)
{
swap(arr[start],arr[end]);
start++;
end--;
}
}
void rotateArr(int arr[],int d, int n)
{
d=d%n;
if(d==0) return;
reverseArr(arr,0,n-1);
reverseArr(arr,0,d-1);
reverseArr(arr,d,n-1);
}
};
int main() {
int t;
//taking testcases
cin >> t;
while(t--){
int n, d;
//input n and d
cin >> n >> d;
int arr[n];
//inserting elements in the array
for(int i = 0; i < n; i++){
cin >> arr[i];
}
Solution ob;
//calling rotateArr() function
ob.rotateArr(arr, d,n);
//printing the elements of the array
for(int i =0;i<n;i++){
cout << arr[i] << " ";
}
cout << endl;
}
return 0;
} // } Driver Code Ends
| 967 | 386 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "commands/SetBallHolder.h"
SetBallHolder::SetBallHolder(BallHolder * ballholder, double indexer, double magazine) {
AddRequirements({ballholder});
m_indexerTarget = indexer;
m_magazineTarget = magazine;
m_ballholder = ballholder;
}
// Called when the command is initially scheduled.
void SetBallHolder::Initialize() {
m_ballholder->SetIndexer(m_indexerTarget);
m_ballholder->SetMagazine(m_magazineTarget);
}
// Called repeatedly when this Command is scheduled to run
void SetBallHolder::Execute() {}
// Called once the command ends or is interrupted.
void SetBallHolder::End(bool interrupted) {}
// Returns true when the command should end.
bool SetBallHolder::IsFinished() { return true; }
| 1,204 | 310 |
// license:BSD-3-Clause
/**************************************************************************
Pirate Ship
PWB(A)354460B
MC68HC00FN16
054539 - 8-Channel ADPCM sound generator. Clock input 18.432MHz. Clock outputs 18.432/4 & 18.432/8
053250 - LVC road generator
053246A - Sprite generator
055673 - Sprite generator
055555 - Mixer/Priority encoder
056832 - Tilemap generator
054156 - Tilemap generator
053252 - CRTC
053250 config:
SELC (69) GND
SEL1 (83) GND
SEL0 (82) GND
MODE (68) GND
TODO: Music stops if a coin is inserted. MAME or BTNAB?
**************************************************************************/
#include "emu.h"
#include "speaker.h"
#include "video/k053250_ps.h"
#include "machine/nvram.h"
#include "machine/timer.h"
#include "cpu/m68000/m68000.h"
#include "sound/k054539.h"
#include "includes/konamigx.h" // TODO: WHY?
#include "video/konami_helper.h"
#include "machine/ticket.h"
#include "machine/gen_latch.h"
#include "machine/k053252.h"
#include "video/k055555.h"
#include "video/k054000.h"
#include "video/k053246_k053247_k055673.h"
class piratesh_state : public driver_device
{
public:
piratesh_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_maincpu(*this,"maincpu"),
m_k053250(*this, "k053250"),
m_k053252(*this, "k053252"),
m_k056832(*this, "k056832"),
m_k055673(*this, "k055673"),
m_k055555(*this, "k055555"),
// m_k053246(*this, "k053246"),
m_k054539(*this, "k054539"),
m_spriteram(*this,"spriteram")
{ }
required_device<cpu_device> m_maincpu;
required_device<k053250ps_device> m_k053250;
required_device<k053252_device> m_k053252;
required_device<k056832_device> m_k056832;
required_device<k055673_device> m_k055673;
required_device<k055555_device> m_k055555;
required_device<k054539_device> m_k054539;
// required_device<k053247_device> m_k053246;
optional_shared_ptr<uint16_t> m_spriteram;
int m_layer_colorbase[6];
int m_sprite_colorbase;
int m_lvc_colorbase;
uint8_t m_int_enable;
uint8_t m_int_status;
uint8_t m_sound_ctrl;
uint8_t m_sound_nmi_clk;
uint16_t m_control;
void update_interrupts();
DECLARE_READ16_MEMBER(K056832_rom_r);
DECLARE_WRITE16_MEMBER(control1_w);
DECLARE_WRITE16_MEMBER(control2_w);
DECLARE_WRITE16_MEMBER(control3_w);
DECLARE_WRITE16_MEMBER(irq_ack_w);
DECLARE_READ16_MEMBER(k053247_scattered_word_r);
DECLARE_WRITE16_MEMBER(k053247_scattered_word_w);
DECLARE_READ16_MEMBER(k053247_martchmp_word_r);
DECLARE_WRITE16_MEMBER(k053247_martchmp_word_w);
DECLARE_CUSTOM_INPUT_MEMBER(helm_r);
DECLARE_CUSTOM_INPUT_MEMBER(battery_r);
DECLARE_MACHINE_START(piratesh);
DECLARE_MACHINE_RESET(piratesh);
DECLARE_VIDEO_START(piratesh);
uint32_t screen_update_piratesh(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
DECLARE_WRITE_LINE_MEMBER(k054539_nmi_gen);
TIMER_DEVICE_CALLBACK_MEMBER(piratesh_interrupt);
K056832_CB_MEMBER(piratesh_tile_callback);
K055673_CB_MEMBER(piratesh_sprite_callback);
void piratesh(machine_config &config);
void piratesh_map(address_map &map);
};
void piratesh_state::update_interrupts()
{
m_maincpu->set_input_line(M68K_IRQ_2, m_int_status & 2 ? ASSERT_LINE : CLEAR_LINE); // INT 1
m_maincpu->set_input_line(M68K_IRQ_4, m_int_status & 1 ? ASSERT_LINE : CLEAR_LINE);
m_maincpu->set_input_line(M68K_IRQ_5, m_int_status & 4 ? ASSERT_LINE : CLEAR_LINE);
}
/*
Priority issues:
1. On title screen, stars should be behind the helm
2. The Konami logo is a square transition
3.
*/
K056832_CB_MEMBER(piratesh_state::piratesh_tile_callback)
{
// Layer
// Code
// Color
// Flags
// if (*color != 0)
// printf("%x %x %x\n", layer, *code, *color >> 2);
*color = (m_layer_colorbase[layer] << 4) + ((*color >> 2));// & 0x0f);
}
K055673_CB_MEMBER(piratesh_state::piratesh_sprite_callback)
{
int c = *color;
*color = (c & 0x001f);
//int pri = (c >> 5) & 7;
// .... .... ...x xxxx - Color
// .... .... xxx. .... - Priority?
// .... ..x. .... .... - ?
// ..x. .... .... .... - ?
#if 0
int layerpri[4];
static const int pris[4] = { K55_PRIINP_0, K55_PRIINP_3, K55_PRIINP_6, K55_PRIINP_7 };
for (uint32_t i = 0; i < 4; i++)
{
layerpri[i] = m_k055555->K055555_read_register(pris[i]);
}
// TODO: THIS IS ALL WRONG
if (pri <= layerpri[0])
*priority_mask = 0;
else if (pri <= layerpri[1])
*priority_mask = 0xf0;
else if (pri <= layerpri[2])
*priority_mask = 0xf0|0xcc;
else
*priority_mask = 0xf0|0xcc|0xaa;
#endif
*priority_mask = 0;
// 0 - Sprites over everything
// f0 -
// f0 cc -
// f0 cc aa -
// 1111 0000
// 1100 1100
// 1010 1010
}
VIDEO_START_MEMBER(piratesh_state, piratesh)
{
// TODO: These come from the 055555
m_layer_colorbase[0] = 0;
m_layer_colorbase[1] = 2;
m_layer_colorbase[2] = 4;
m_layer_colorbase[3] = 6;
m_sprite_colorbase = 1;
m_lvc_colorbase = 3;
#if 0
konamigx_mixer_init(*m_screen, 0);
m_k056832->set_layer_offs(0, -2+2-1, 0-1);
m_k056832->set_layer_offs(1, 0+2, 0);
m_k056832->set_layer_offs(2, 2+2, 0);
m_k056832->set_layer_offs(3, 3+2, 0);
#endif
}
uint32_t piratesh_state::screen_update_piratesh(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
bitmap.fill(0, cliprect);
#if 1
int layers[4], layerpri[4];
static const int pris[4] = { K55_PRIINP_0, K55_PRIINP_3, K55_PRIINP_6, K55_PRIINP_7 };
static const int enables[4] = { K55_INP_VRAM_A, K55_INP_VRAM_B, K55_INP_VRAM_C, K55_INP_VRAM_D };
for (uint32_t i = 0; i < 4; i++)
{
layers[i] = i;
layerpri[i] = m_k055555->K055555_read_register(pris[i]);
}
konami_sortlayers4(layers, layerpri);
screen.priority().fill(0, cliprect);
const uint32_t input_enables = m_k055555->K055555_read_register(K55_INPUT_ENABLES);
// TODO: FIX COLORBASES
if (input_enables & K55_INP_SUB3)
m_k053250->draw(bitmap, cliprect, 0x20, 0, screen.priority(), 2);
for (uint32_t i = 0; i < 4; i++)
{
if (input_enables & enables[layers[i]])
{
m_k056832->tilemap_draw(screen, bitmap, cliprect, layers[i], 0, 1 << i);
}
}
if (input_enables & K55_INP_SUB2)
m_k055673->k053247_sprites_draw(bitmap, cliprect);
#if 0
#define K55_INP_VRAM_A 0x01
#define K55_INP_VRAM_B 0x02
#define K55_INP_VRAM_C 0x04
#define K55_INP_VRAM_D 0x08
#define K55_INP_OBJ 0x10
#define K55_INP_SUB1 0x20
#define K55_INP_SUB2 0x40
#define K55_INP_SUB3 0x80
#endif
//055555: 4 to reg 7 (A PRI 0)
//055555: 0 to reg 8 (A PRI 1)
//055555: 0 to reg 9 (A COLPRI)
//055555: 6 to reg a (B PRI 0)
//055555: 0 to reg b (B PRI 1)
//055555: 0 to reg c (B COLPRI)
//055555: 16 to reg d (C PRI)
//055555: 18 to reg e (D PRI)
//055555: 0 to reg 11 (SUB2 PRI)
//055555: 0 to reg 12 (SUB3 PRI)
//055555: 0 to reg 17 (A PAL)
//055555: 2 to reg 18 (B PAL)
//055555: 4 to reg 19 (C PAL)
//055555: 6 to reg 1a (D PAL)
//055555: 3 to reg 1d (SUB2 PAL)
//055555: 1 to reg 1e (SUB3 PAL)
#else
// LAYER, FLAGS, PRIORITY
m_k056832->tilemap_draw(screen, bitmap, cliprect, 3, K056832_DRAW_FLAG_MIRROR, 1);
m_k056832->tilemap_draw(screen, bitmap, cliprect, 2, K056832_DRAW_FLAG_MIRROR, 2);
// TODO: Fix priority
m_k053250->draw(bitmap, cliprect, 0x20, 0, screen.priority(), 8);
m_k055673->k053247_sprites_draw(bitmap, cliprect);
m_k056832->tilemap_draw(screen, bitmap, cliprect, 1, K056832_DRAW_FLAG_MIRROR, 4);
m_k056832->tilemap_draw(screen, bitmap, cliprect, 0, K056832_DRAW_FLAG_MIRROR, 0);
#endif
return 0;
}
/**********************************************************************************/
/* IRQ controllers */
TIMER_DEVICE_CALLBACK_MEMBER(piratesh_state::piratesh_interrupt)
{
int scanline = param;
// IRQ2 - CCUINT1 (VBL START)
// IRQ4 - Sound
// IRQ5 - CCUINT2 (VBL END)
if (scanline == 240)
{
m_k053250->vblank_w(1);
if (m_int_enable & 2)
{
m_int_status |= 2;
update_interrupts();
}
}
if (scanline == 0)
{
m_k053250->vblank_w(0);
if (m_int_enable & 4)
{
m_int_status |= 4;
update_interrupts();
}
}
}
READ16_MEMBER(piratesh_state::K056832_rom_r)
{
uint16_t offs;
offs = (m_control & 2 ? 0x1000 : 0) + offset;
return m_k056832->piratesh_rom_r(space, offs, mem_mask);
}
WRITE16_MEMBER(piratesh_state::control1_w)
{
// .... ..xx .... .... - Unknown
// .... .x.. .... .... - Unknown - Active during attract, clear during game
// .... x... .... .... - Lamp? (active when waiting to start game)
if (data & ~0x0f00)
printf("CTRL3: %x %x %x\n", offset, data, mem_mask);
}
WRITE16_MEMBER(piratesh_state::control2_w)
{
// .... .... ...x .... - Unknown (always 1?)
// .... .... ..x. .... - Unknown
// .... .... .x.. .... - Counter out
// .... .... x... .... - Counter in
// .... ...x .... .... - 053246A OBJCRBK (Pin 9)
// .... ..x. .... .... - LV related
// .... x... .... .... - INT4/SND control (0=clear 1=enable)
// ...x .... .... .... - INT2/CCUINT1 control (0=clear 1=enable)
// ..x. .... .... .... - INT5/CCUINT2 control (0=clear 1=enable)
// .x.. .... .... .... - Unknown
// x... .... .... .... - Unknown
m_int_enable = (data >> 11) & 7;
m_int_status &= m_int_enable;
update_interrupts();
if (data & ~0xfbf0)
printf("CTRL2: %x %x %x\n", offset, data, mem_mask);
}
WRITE16_MEMBER(piratesh_state::control3_w)
{
// .... .... .... ...x - Watchdog? (051550?)
// .... .... .... ..x. - 056832 ROM bank control
// .... .... ...x .... - Ticket dispenser enable (active high)
// .... .... ..x. .... - Hopper enable (active high)
// .... ...x .... .... - Unknown (always 1?)
if ((data & ~0x0133) || (~data & 0x100))
printf("CTRL1 W: %x %x %x\n", offset, data, mem_mask);
// printf("CTRL 1: %x\n", data & 0x0010);
machine().device<ticket_dispenser_device>("ticket")->motor_w(data & 0x0010 ? 1 : 0);
machine().device<ticket_dispenser_device>("hopper")->motor_w(data & 0x0020 ? 1 : 0);
m_control = data;
}
void piratesh_state::piratesh_map(address_map &map)
{
map(0x000000, 0x07ffff).rom();
map(0x080000, 0x083fff).ram().share("nvram");
map(0x084000, 0x087fff).ram();
map(0x100000, 0x10001f).rw(m_k053252, FUNC(k053252_device::read), FUNC(k053252_device::write)).umask16(0x00ff); // CRTC
map(0x180000, 0x18003f).w(m_k056832, FUNC(k056832_device::word_w)); // TILEMAP
map(0x280000, 0x280007).w(m_k055673, FUNC(k055673_device::k053246_word_w)); // SPRITES
map(0x290000, 0x29000f).r(m_k055673, FUNC(k055673_device::k055673_ps_rom_word_r)); // SPRITES
map(0x290010, 0x29001f).w(m_k055673, FUNC(k055673_device::k055673_reg_word_w)); // SPRITES
map(0x2a0000, 0x2a0fff).rw(m_k055673, FUNC(k055673_device::k053247_word_r), FUNC(k055673_device::k053247_word_w)); // SPRITES
map(0x2a1000, 0x2a3fff).nopw();
map(0x2b0000, 0x2b000f).rw(m_k053250, FUNC(k053250ps_device::reg_r), FUNC(k053250ps_device::reg_w)); // LVC
map(0x300000, 0x3000ff).w(m_k055555, FUNC(k055555_device::K055555_word_w));
map(0x380000, 0x381fff).ram().w("palette", FUNC(palette_device::write16)).share("palette");
map(0x400000, 0x400001).portr("IN0");
map(0x400002, 0x400003).portr("IN1");
map(0x400004, 0x400005).portr("DSW1");
map(0x400006, 0x400007).portr("DSW2");
map(0x400008, 0x400009).portr("SPECIAL");
map(0x40000c, 0x40000d).w(this, FUNC(piratesh_state::control1_w));
map(0x400010, 0x400011).w(this, FUNC(piratesh_state::control2_w));
map(0x400014, 0x400015).w(this, FUNC(piratesh_state::control3_w));
map(0x500000, 0x50ffff).r(this, FUNC(piratesh_state::K056832_rom_r)); // VRAM ROM
map(0x580000, 0x581fff).r(m_k053250, FUNC(k053250ps_device::rom_r)); // LVC ROM access
map(0x600000, 0x6004ff).rw("k054539", FUNC(k054539_device::read), FUNC(k054539_device::write)).umask16(0xff00); // SOUND
map(0x680000, 0x681fff).rw(m_k056832, FUNC(k056832_device::ram_word_r), FUNC(k056832_device::ram_word_w)); // TILEMAP
map(0x700000, 0x703fff).rw(m_k053250, FUNC(k053250ps_device::ram_r), FUNC(k053250ps_device::ram_w)); // LVC
}
WRITE_LINE_MEMBER(piratesh_state::k054539_nmi_gen)
{
static int m_sound_intck = 0; // TODO: KILL ME
// Trigger an interrupt on the rising edge
if (!m_sound_intck && state)
{
if (m_int_enable & 1)
{
m_int_status |= 1;
update_interrupts();
}
}
m_sound_intck = state;
}
CUSTOM_INPUT_MEMBER(piratesh_state::helm_r)
{
// Appears to be a quadrature encoder
uint8_t xa, xb;
uint16_t dx = ioport("HELM")->read();
xa = ((dx + 1) & 7) <= 3;
xb = (dx & 7) <= 3;
return (xb << 1) | xa;
}
CUSTOM_INPUT_MEMBER(piratesh_state::battery_r)
{
// .x MB3790 /ALARM1
// x. MB3790 /ALARM2
return 0x3;
}
/**********************************************************************************/
static INPUT_PORTS_START( piratesh )
PORT_START("IN0")
PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_BUTTON3 ) // 7f60 btst $7,$40000
PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) // HELM?
PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) // HELM?
PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_SERVICE2 ) PORT_NAME("Reset")
PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_START )
PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME(DEF_STR( Test )) PORT_CODE(KEYCODE_F2)
PORT_START("SPECIAL")
PORT_BIT( 0x0100, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_READ_LINE_DEVICE_MEMBER("k053250", k053250ps_device, dmairq_r)
PORT_BIT( 0x0200, IP_ACTIVE_HIGH, IPT_UNKNOWN ) // FIXME: NCPU from 053246 (DMA)
PORT_BIT( 0x0c00, IP_ACTIVE_HIGH, IPT_SPECIAL )PORT_CUSTOM_MEMBER(DEVICE_SELF, piratesh_state, battery_r, nullptr)
PORT_START("HELM")
PORT_BIT( 0xff, 0x00, IPT_DIAL ) PORT_SENSITIVITY(25) PORT_KEYDELTA(1)
PORT_START("IN1")
PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_NAME("Service")
PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_SPECIAL ) PORT_READ_LINE_DEVICE_MEMBER("ticket", ticket_dispenser_device, line_r)
PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_SPECIAL ) PORT_READ_LINE_DEVICE_MEMBER("hopper", ticket_dispenser_device, line_r)
PORT_BIT( 0x1800, IP_ACTIVE_HIGH, IPT_SPECIAL )PORT_CUSTOM_MEMBER(DEVICE_SELF, piratesh_state, helm_r, nullptr)
PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("DSW1") // TODO: DIP switches are used for settings when battery failure has occurred
PORT_DIPNAME( 0x0100, 0x0100, "DSW1:0" ) PORT_DIPLOCATION("DSW1:1")
PORT_DIPSETTING( 0x0100, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x0200, 0x0200, "DSW1:1" ) PORT_DIPLOCATION("DSW1:2")
PORT_DIPSETTING( 0x0200, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x0400, 0x0400, "DSW1:2" ) PORT_DIPLOCATION("DSW1:3")
PORT_DIPSETTING( 0x0400, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x0800, 0x0800, "DSW1:3" ) PORT_DIPLOCATION("DSW1:4")
PORT_DIPSETTING( 0x0800, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x3000, 0x1000, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("DSW1:5,6")
PORT_DIPSETTING( 0x0000, "A" )
PORT_DIPSETTING( 0x1000, "B" )
PORT_DIPSETTING( 0x2000, "C" )
PORT_DIPSETTING( 0x3000, "D" )
PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("DSW1:7")
PORT_DIPSETTING( 0x0000, DEF_STR( Off ) )
PORT_DIPSETTING( 0x4000, DEF_STR( On ) )
PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Free_Play ) ) PORT_DIPLOCATION("DSW1:8")
PORT_DIPSETTING( 0x8000, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_START("DSW2") // TODO: Finish me
PORT_DIPNAME( 0x0100, 0x0100, "DSW2:0" ) PORT_DIPLOCATION("DSW2:1")
PORT_DIPSETTING( 0x0100, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x0200, 0x0200, "DSW2:1" ) PORT_DIPLOCATION("DSW2:2")
PORT_DIPSETTING( 0x0200, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x0400, 0x0400, "DSW2:2" ) PORT_DIPLOCATION("DSW2:3")
PORT_DIPSETTING( 0x0400, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x0800, 0x0800, "DSW2:3" ) PORT_DIPLOCATION("DSW2:4")
PORT_DIPSETTING( 0x0800, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x1000, 0x1000, "DSW2:4" ) PORT_DIPLOCATION("DSW2:5")
PORT_DIPSETTING( 0x1000, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x2000, 0x2000, "DSW2:5" ) PORT_DIPLOCATION("DSW2:6")
PORT_DIPSETTING( 0x2000, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x4000, 0x4000, "DSW2:6" ) PORT_DIPLOCATION("DSW2:7")
PORT_DIPSETTING( 0x4000, DEF_STR( Off ) )
PORT_DIPSETTING( 0x0000, DEF_STR( On ) )
PORT_DIPNAME( 0x8000, 0x8000, "Redemption Type" ) PORT_DIPLOCATION("DSW2:8")
PORT_DIPSETTING( 0x8000, "Ticket" )
PORT_DIPSETTING( 0x0000, "Capsule" )
INPUT_PORTS_END
/**********************************************************************************/
MACHINE_START_MEMBER(piratesh_state, piratesh)
{
#if 0
m_sound_ctrl = 2;
m_mw_irq_control = 0;
/* konamigx_mixer uses this, so better initialize it */
m_gx_wrport1_0 = 0;
save_item(NAME(m_mw_irq_control));
save_item(NAME(m_sound_ctrl));
save_item(NAME(m_sound_nmi_clk));
#endif
}
MACHINE_RESET_MEMBER(piratesh_state,piratesh)
{
m_int_status = 0;
int i;
// soften chorus(chip 0 channel 0-3), boost voice(chip 0 channel 4-7)
for (i=0; i<=7; i++)
{
// m_k054539->set_gain(i, 0.5);
}
// // soften percussions(chip 1 channel 0-7)
// for (i=0; i<=7; i++) m_k054539_2->set_gain(i, 0.5);
}
MACHINE_CONFIG_START(piratesh_state::piratesh)
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", M68000, XTAL(32'000'000)/2)
MCFG_CPU_PROGRAM_MAP(piratesh_map)
MCFG_TIMER_DRIVER_ADD_SCANLINE("scantimer", piratesh_state, piratesh_interrupt, "screen", 0, 1)
MCFG_NVRAM_ADD_0FILL("nvram")
MCFG_DEVICE_ADD("k053252", K053252, XTAL(32'000'000)/4)
MCFG_K053252_OFFSETS(40, 16) // TODO
MCFG_MACHINE_START_OVERRIDE(piratesh_state, piratesh)
MCFG_MACHINE_RESET_OVERRIDE(piratesh_state, piratesh)
MCFG_TICKET_DISPENSER_ADD("ticket", attotime::from_msec(200), TICKET_MOTOR_ACTIVE_HIGH, TICKET_STATUS_ACTIVE_HIGH)
MCFG_TICKET_DISPENSER_ADD("hopper", attotime::from_msec(200), TICKET_MOTOR_ACTIVE_HIGH, TICKET_STATUS_ACTIVE_HIGH)
/* video hardware */
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_VIDEO_ATTRIBUTES(VIDEO_UPDATE_AFTER_VBLANK)
// MCFG_SCREEN_REFRESH_RATE(60)
MCFG_SCREEN_RAW_PARAMS(6000000, 288+16+32+48, 0, 287, 224+16+8+16, 0, 223) // TODO
MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(600))
MCFG_SCREEN_SIZE(64*8, 32*8)
MCFG_SCREEN_VISIBLE_AREA(24, 24+288-1, 16, 16+224-1)
MCFG_SCREEN_UPDATE_DRIVER(piratesh_state, screen_update_piratesh)
MCFG_PALETTE_ADD("palette", 2048)
MCFG_PALETTE_FORMAT(BGRX)
MCFG_PALETTE_ENABLE_SHADOWS()
MCFG_PALETTE_ENABLE_HILIGHTS()
MCFG_DEVICE_ADD("k056832", K056832, 0)
MCFG_K056832_CB(piratesh_state, piratesh_tile_callback)
MCFG_K056832_CONFIG("gfx1", K056832_BPP_4PIRATESH, 1, 0, "none")
MCFG_K056832_PALETTE("palette")
MCFG_K055555_ADD("k055555")
MCFG_K053250PS_ADD("k053250", "palette", "screen", -16, 0)
MCFG_DEVICE_ADD("k055673", K055673, 0)
MCFG_K055673_CB(piratesh_state, piratesh_sprite_callback)
MCFG_K055673_CONFIG("gfx2", K055673_LAYOUT_PS, -60, 24)
MCFG_K055673_PALETTE("palette")
// ????
//MCFG_DEVICE_ADD("k053246", K053246, 0)
//MCFG_K053246_CB(moo_state, sprite_callback)
//MCFG_K053246_CONFIG("gfx2", NORMAL_PLANE_ORDER, -48+1, 23)
//MCFG_K053246_PALETTE("palette")
MCFG_DEVICE_ADD("k054338", K054338, 0)
MCFG_K054338_ALPHAINV(1)
MCFG_K054338_MIXER("k055555")
MCFG_VIDEO_START_OVERRIDE(piratesh_state, piratesh)
/* sound hardware */
MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
MCFG_DEVICE_ADD("k054539", K054539, XTAL(18'432'000))
MCFG_K054539_TIMER_HANDLER(WRITELINE(piratesh_state, k054539_nmi_gen))
MCFG_SOUND_ROUTE(0, "lspeaker", 0.2)
MCFG_SOUND_ROUTE(1, "rspeaker", 0.2)
MACHINE_CONFIG_END
ROM_START( piratesh )
ROM_REGION( 0x80000, "maincpu", 0 )
ROM_LOAD16_WORD_SWAP( "360ua-c04.4p", 0x000000, 0x80000, CRC(6d69dd90) SHA1(ccbdbfea406d9cbc3f242211290ba82ccbbe3795) )
/* tiles */
ROM_REGION( 0x80000, "gfx1", ROMREGION_ERASE00 ) // 27C4096
ROM_LOAD( "360ua-a01.17g", 0x000000, 0x80000, CRC(e39153f5) SHA1(5da9132a2c24a15b55c3f65c26e2ad0467411a88) )
/* sprites */
ROM_REGION( 0x80000*8, "gfx2", ROMREGION_ERASE00 ) // 27C4096
ROM_LOAD16_BYTE( "360ua-a02.21l", 0x000000, 0x80000, CRC(82207997) SHA1(fe143285a12fab5227e883113d798acad7bf4c97) )
ROM_LOAD16_BYTE( "360ua-a03.23l", 0x000001, 0x80000, CRC(a9e36d51) SHA1(1a8de8d8d2abfee5ac0f0822e203846f7f5f1767) )
/* road generator */
ROM_REGION( 0x080000, "k053250", ROMREGION_ERASE00 ) // 27C040
ROM_LOAD( "360ua-a05.26p", 0x000000, 0x80000, CRC(dab7f439) SHA1(2372612c0b04c77a85ccbadc100cb741b85f0481) )
/* sound data */
ROM_REGION( 0x100000, "k054539", 0 ) // 27C040
ROM_LOAD( "360ua-a06.15t", 0x000000, 0x80000, CRC(6816a493) SHA1(4fc4cfbc164d84bbf8d75ccd78c9f40f3273d852) )
ROM_LOAD( "360ua-a07.17t", 0x080000, 0x80000, CRC(af7127c5) SHA1(b525f3c6b831e3354eba46016d414bedcb3ae8dc) )
// ROM_REGION( 0x80, "eeprom", 0 ) // default eeprom to prevent game booting upside down with error
// ROM_LOAD( "piratesh.nv", 0x0000, 0x080, CRC(28df2269) SHA1(3f071c97662745a199f96964e2e79f795bd5a391) )
ROM_END
// year name parent machine input state init
GAME( 1995, piratesh, 0, piratesh, piratesh, piratesh_state, 0, ROT90, "Konami", "Pirate Ship (ver UAA)", MACHINE_IMPERFECT_GRAPHICS )
| 22,392 | 12,703 |
/*++
Copyright (C) 2020 Autodesk 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 Autodesk 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 AUTODESK INC. 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 "amc_parameterhandler.hpp"
#include "libmc_interfaceexception.hpp"
#define AMC_MAXPARAMETERGROUPCOUNT (1024 * 1024)
namespace AMC {
CParameterHandler::CParameterHandler()
{
m_DataStore = std::make_shared <CParameterGroup>();
}
CParameterHandler::~CParameterHandler()
{
}
bool CParameterHandler::hasGroup(const std::string& sName)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
auto iter = m_Groups.find(sName);
return (iter != m_Groups.end());
}
void CParameterHandler::addGroup(PParameterGroup pGroup)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
if (pGroup.get() == nullptr)
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDPARAM);
auto sName = pGroup->getName();
if (m_Groups.find(sName) != m_Groups.end())
throw ELibMCInterfaceException(LIBMC_ERROR_DUPLICATEPARAMETERGROUPNAME);
if (m_GroupList.size() >= AMC_MAXPARAMETERGROUPCOUNT)
throw ELibMCInterfaceException(LIBMC_ERROR_TOOMANYPARAMETERGROUPS);
m_Groups.insert(std::make_pair(sName, pGroup));
m_GroupList.push_back(pGroup);
}
PParameterGroup CParameterHandler::addGroup(const std::string& sName, const std::string& sDescription)
{
PParameterGroup pGroup = std::make_shared<CParameterGroup>(sName, sDescription);
addGroup(pGroup);
return pGroup;
}
uint32_t CParameterHandler::getGroupCount()
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
return (uint32_t)m_GroupList.size();
}
CParameterGroup* CParameterHandler::getGroup(const uint32_t nIndex)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
if (nIndex >= m_GroupList.size())
throw ELibMCInterfaceException(LIBMC_ERROR_INVALIDINDEX);
return m_GroupList[nIndex].get();
}
CParameterGroup* CParameterHandler::findGroup(const std::string& sName, const bool bFailIfNotExisting)
{
std::lock_guard <std::mutex> lockGuard(m_Mutex);
auto iter = m_Groups.find(sName);
if (iter != m_Groups.end())
return iter->second.get();
if (bFailIfNotExisting)
throw ELibMCInterfaceException(LIBMC_ERROR_PARAMETERGROUPNOTFOUND);
return nullptr;
}
CParameterGroup* CParameterHandler::getDataStore()
{
return m_DataStore.get();
}
}
| 3,654 | 1,369 |
/*
Copyright (C) 2018 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
// clang-format off
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
// clang-format on
#include <oret/datapaths.hpp>
#include <oret/toplevelfixture.hpp>
#include <boost/make_shared.hpp>
#include <cmath>
#include <ored/configuration/curveconfigurations.hpp>
#include <ored/marketdata/commodityvolcurve.hpp>
#include <ored/marketdata/csvloader.hpp>
#include <ored/marketdata/curvespec.hpp>
#include <ored/marketdata/loader.hpp>
#include <ored/marketdata/todaysmarket.hpp>
#include <ored/utilities/csvfilereader.hpp>
#include <ored/utilities/parsers.hpp>
#include <ored/utilities/to_string.hpp>
#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>
#include <qle/termstructures/aposurface.hpp>
#include <qle/termstructures/blackvariancesurfacesparse.hpp>
#include <qle/termstructures/blackvolsurfacedelta.hpp>
#include <qle/termstructures/blackvolsurfacewithatm.hpp>
using namespace std;
using namespace boost::unit_test_framework;
using namespace QuantLib;
using namespace QuantExt;
using namespace ore::data;
namespace bdata = boost::unit_test::data;
namespace {
// testTolerance for Real comparison
Real testTolerance = 1e-10;
class MockLoader : public Loader {
public:
MockLoader();
const vector<boost::shared_ptr<MarketDatum>>& loadQuotes(const Date&) const { return data_; }
const boost::shared_ptr<MarketDatum>& get(const string& name, const Date&) const { return dummyDatum_; }
const vector<Fixing>& loadFixings() const { return dummyFixings_; }
const vector<Fixing>& loadDividends() const { return dummyDividends_; }
void add(QuantLib::Date date, const string& name, QuantLib::Real value) {}
void addFixing(QuantLib::Date date, const string& name, QuantLib::Real value) {}
void addDividend(Date date, const string& name, Real value) {}
private:
vector<boost::shared_ptr<MarketDatum>> data_;
boost::shared_ptr<MarketDatum> dummyDatum_;
vector<Fixing> dummyFixings_;
vector<Fixing> dummyDividends_;
};
MockLoader::MockLoader() {
Date asof(5, Feb, 2016);
data_ = {
boost::make_shared<CommodityOptionQuote>(0.11, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/1Y/ATM/AtmFwd",
MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD",
boost::make_shared<ExpiryPeriod>(1 * Years),
boost::make_shared<AtmStrike>(DeltaVolQuote::AtmFwd)),
boost::make_shared<CommodityOptionQuote>(0.10, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/2Y/ATM/AtmFwd",
MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD",
boost::make_shared<ExpiryPeriod>(2 * Years),
boost::make_shared<AtmStrike>(DeltaVolQuote::AtmFwd)),
boost::make_shared<CommodityOptionQuote>(0.09, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/5Y/ATM/AtmFwd",
MarketDatum::QuoteType::RATE_LNVOL, "GOLD", "USD",
boost::make_shared<ExpiryPeriod>(5 * Years),
boost::make_shared<AtmStrike>(DeltaVolQuote::AtmFwd)),
boost::make_shared<CommodityOptionQuote>(
0.105, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/1Y/1150", MarketDatum::QuoteType::RATE_LNVOL,
"GOLD", "USD", boost::make_shared<ExpiryPeriod>(1 * Years), boost::make_shared<AbsoluteStrike>(1150)),
boost::make_shared<CommodityOptionQuote>(
0.115, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/1Y/1190", MarketDatum::QuoteType::RATE_LNVOL,
"GOLD", "USD", boost::make_shared<ExpiryPeriod>(1 * Years), boost::make_shared<AbsoluteStrike>(1190)),
boost::make_shared<CommodityOptionQuote>(
0.095, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/2Y/1150", MarketDatum::QuoteType::RATE_LNVOL,
"GOLD", "USD", boost::make_shared<ExpiryPeriod>(2 * Years), boost::make_shared<AbsoluteStrike>(1150)),
boost::make_shared<CommodityOptionQuote>(
0.105, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/2Y/1190", MarketDatum::QuoteType::RATE_LNVOL,
"GOLD", "USD", boost::make_shared<ExpiryPeriod>(2 * Years), boost::make_shared<AbsoluteStrike>(1190)),
boost::make_shared<CommodityOptionQuote>(
0.085, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/5Y/1150", MarketDatum::QuoteType::RATE_LNVOL,
"GOLD", "USD", boost::make_shared<ExpiryPeriod>(5 * Years), boost::make_shared<AbsoluteStrike>(1150)),
boost::make_shared<CommodityOptionQuote>(
0.095, asof, "COMMODITY_OPTION/RATE_LNVOL/GOLD_USD_VOLS/USD/5Y/1190", MarketDatum::QuoteType::RATE_LNVOL,
"GOLD", "USD", boost::make_shared<ExpiryPeriod>(5 * Years), boost::make_shared<AbsoluteStrike>(1190))};
}
boost::shared_ptr<TodaysMarket> createTodaysMarket(const Date& asof, const string& inputDir,
const string& curveConfigFile,
const string& marketFile = "market.txt",
const string& fixingsFile = "fixings.txt") {
auto conventions = boost::make_shared<Conventions>();
conventions->fromFile(TEST_INPUT_FILE(string(inputDir + "/conventions.xml")));
auto curveConfigs = boost::make_shared<CurveConfigurations>();
curveConfigs->fromFile(TEST_INPUT_FILE(string(inputDir + "/" + curveConfigFile)));
auto todaysMarketParameters = boost::make_shared<TodaysMarketParameters>();
todaysMarketParameters->fromFile(TEST_INPUT_FILE(string(inputDir + "/todaysmarket.xml")));
auto loader = boost::make_shared<CSVLoader>(TEST_INPUT_FILE(string(inputDir + "/" + marketFile)),
TEST_INPUT_FILE(string(inputDir + "/" + fixingsFile)), false);
return boost::make_shared<TodaysMarket>(asof, todaysMarketParameters, loader, curveConfigs, conventions);
}
// clang-format off
// NYMEX input volatility data that is provided in the input market data file
struct NymexVolatilityData {
vector<Date> expiries;
map<Date, vector<Real>> strikes;
map<Date, vector<Real>> volatilities;
map<Date, Real> atmVolatilities;
NymexVolatilityData() {
expiries = { Date(17, Oct, 2019), Date(16, Dec, 2019), Date(17, Mar, 2020) };
strikes = {
{ Date(17, Oct, 2019), { 60, 61, 62 } },
{ Date(16, Dec, 2019), { 59, 60, 61 } },
{ Date(17, Mar, 2020), { 57, 58, 59 } }
};
volatilities = {
{ Date(17, Oct, 2019), { 0.4516, 0.4558, 0.4598 } },
{ Date(16, Dec, 2019), { 0.4050, 0.4043, 0.4041 } },
{ Date(17, Mar, 2020), { 0.3599, 0.3573, 0.3545 } }
};
atmVolatilities = {
{ Date(17, Oct, 2019), 0.4678 },
{ Date(16, Dec, 2019), 0.4353 },
{ Date(17, Mar, 2020), 0.3293 }
};
}
};
// clang-format on
} // namespace
BOOST_FIXTURE_TEST_SUITE(OREDataTestSuite, ore::test::TopLevelFixture)
BOOST_AUTO_TEST_SUITE(CommodityVolCurveTests)
BOOST_AUTO_TEST_CASE(testCommodityVolCurveTypeConstant) {
BOOST_TEST_MESSAGE("Testing commodity vol curve building with a single configured volatility");
// As of date
Date asof(5, Feb, 2016);
// Constant volatility config
auto cvc = boost::make_shared<ConstantVolatilityConfig>("COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/2Y/ATM/AtmFwd");
// Volatility configuration with a single quote
boost::shared_ptr<CommodityVolatilityConfig> curveConfig =
boost::make_shared<CommodityVolatilityConfig>("GOLD_USD_VOLS", "", "USD", cvc, "A365", "NullCalendar");
// Curve configurations
CurveConfigurations curveConfigs;
curveConfigs.commodityVolatilityConfig("GOLD_USD_VOLS") = curveConfig;
// Commodity curve spec
CommodityVolatilityCurveSpec curveSpec("USD", "GOLD_USD_VOLS");
// Market data loader
MockLoader loader;
// Empty Conventions
Conventions conventions;
// Check commodity volatility construction works
boost::shared_ptr<CommodityVolCurve> curve;
BOOST_CHECK_NO_THROW(curve =
boost::make_shared<CommodityVolCurve>(asof, curveSpec, loader, curveConfigs, conventions));
// Check volatilities are all equal to the configured volatility regardless of strike and expiry
Real configuredVolatility = 0.10;
boost::shared_ptr<BlackVolTermStructure> volatility = curve->volatility();
BOOST_CHECK_CLOSE(volatility->blackVol(0.25, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(0.25, 1200.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Months, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Months, 1200.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(50.0, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(50.0, 1200.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 50 * Years, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 50 * Years, 1200.0), configuredVolatility, testTolerance);
}
BOOST_AUTO_TEST_CASE(testCommodityVolCurveTypeCurve) {
BOOST_TEST_MESSAGE("Testing commodity vol curve building with time dependent volatilities");
// As of date
Date asof(5, Feb, 2016);
// Quotes for the volatility curve
vector<string> quotes{"COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/1Y/ATM/AtmFwd",
"COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/2Y/ATM/AtmFwd",
"COMMODITY_OPTION/RATE_LNVOL/GOLD/USD/5Y/ATM/AtmFwd"};
// Volatility curve config with linear interpolation and flat extrapolation.
auto vcc = boost::make_shared<VolatilityCurveConfig>(quotes, "Linear", "Flat");
// Commodity volatility configuration with time dependent volatilities
boost::shared_ptr<CommodityVolatilityConfig> curveConfig =
boost::make_shared<CommodityVolatilityConfig>("GOLD_USD_VOLS", "", "USD", vcc, "A365", "NullCalendar");
// Curve configurations
CurveConfigurations curveConfigs;
curveConfigs.commodityVolatilityConfig("GOLD_USD_VOLS") = curveConfig;
// Commodity curve spec
CommodityVolatilityCurveSpec curveSpec("USD", "GOLD_USD_VOLS");
// Market data loader
MockLoader loader;
// Empty Conventions
Conventions conventions;
// Check commodity volatility construction works
boost::shared_ptr<CommodityVolCurve> curve;
BOOST_CHECK_NO_THROW(curve =
boost::make_shared<CommodityVolCurve>(asof, curveSpec, loader, curveConfigs, conventions));
// Check time depending volatilities are as expected
boost::shared_ptr<BlackVolTermStructure> volatility = curve->volatility();
Real configuredVolatility;
// Check configured pillar points: { (1Y, 0.11), (2Y, 0.10), (5Y, 0.09) }
// Check also strike independence
configuredVolatility = 0.11;
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1200.0), configuredVolatility, testTolerance);
configuredVolatility = 0.10;
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1200.0), configuredVolatility, testTolerance);
configuredVolatility = 0.09;
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1000.0), configuredVolatility, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1200.0), configuredVolatility, testTolerance);
// Check briefly the default linear interpolation and extrapolation
Time t_s = volatility->dayCounter().yearFraction(asof, asof + 2 * Years);
Real v_s = 0.10;
Time t_e = volatility->dayCounter().yearFraction(asof, asof + 5 * Years);
Real v_e = 0.09;
// at 3 years
Time t = volatility->dayCounter().yearFraction(asof, asof + 3 * Years);
Real v = sqrt((v_s * v_s * t_s + (v_e * v_e * t_e - v_s * v_s * t_s) * (t - t_s) / (t_e - t_s)) / t);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Years, 1000.0), v, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 3 * Years, 1200.0), v, testTolerance);
// at 6 years, extrapolation is with a flat vol
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 6 * Years, 1000.0), v_e, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 6 * Years, 1200.0), v_e, testTolerance);
}
BOOST_AUTO_TEST_CASE(testCommodityVolCurveTypeSurface) {
BOOST_TEST_MESSAGE("Testing commodity vol curve building with time and strike dependent volatilities");
// As of date
Date asof(5, Feb, 2016);
// Volatility configuration with expiry period vs. absolute strike matrix. Bilinear interpolation and flat
// extrapolation.
vector<string> strikes{"1150", "1190"};
vector<string> expiries{"1Y", "2Y", "5Y"};
auto vssc =
boost::make_shared<VolatilityStrikeSurfaceConfig>(strikes, expiries, "Linear", "Linear", true, "Flat", "Flat");
// Commodity volatility configuration
boost::shared_ptr<CommodityVolatilityConfig> curveConfig =
boost::make_shared<CommodityVolatilityConfig>("GOLD_USD_VOLS", "", "USD", vssc, "A365", "NullCalendar");
// Curve configurations
CurveConfigurations curveConfigs;
curveConfigs.commodityVolatilityConfig("GOLD_USD_VOLS") = curveConfig;
// Commodity curve spec
CommodityVolatilityCurveSpec curveSpec("USD", "GOLD_USD_VOLS");
// Market data loader
MockLoader loader;
// Empty Conventions
Conventions conventions;
// Check commodity volatility construction works
boost::shared_ptr<CommodityVolCurve> curve;
BOOST_CHECK_NO_THROW(curve =
boost::make_shared<CommodityVolCurve>(asof, curveSpec, loader, curveConfigs, conventions));
// Check time and strike depending volatilities are as expected
boost::shared_ptr<BlackVolTermStructure> volatility = curve->volatility();
// Check configured pillar points
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1150.0), 0.105, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 1 * Years, 1190.0), 0.115, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1150.0), 0.095, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 2 * Years, 1190.0), 0.105, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1150.0), 0.085, testTolerance);
BOOST_CHECK_CLOSE(volatility->blackVol(asof + 5 * Years, 1190.0), 0.095, testTolerance);
}
BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceWildcardExpiriesWildcardStrikes) {
// Testing commodity volatility curve building wildcard expiries and strikes in configuration and more than one
// set of commodity volatility quotes in the market data. In particular, the market data in the wildcard_data
// folder has commodity volatility data for two surfaces NYMEX:CL and ICE:B. Check here that the commodity
// volatility curve building for NYMEX:CL uses only the 9 NYMEX:CL quotes - 3 tenors, each with 3 strikes.
BOOST_TEST_MESSAGE("Testing commodity volatility curve building wildcard expiries and strikes in configuration");
auto todaysMarket =
createTodaysMarket(Date(16, Sep, 2019), "wildcard_data", "curveconfig_surface_wc_expiries_wc_strikes.xml");
auto vts = todaysMarket->commodityVolatility("NYMEX:CL");
// Wildcards in configuration so we know that a BlackVarianceSurfaceSparse has been created and fed to a
// BlackVolatilityWithATM surface in TodaysMarket
auto tmSurface = boost::dynamic_pointer_cast<BlackVolatilityWithATM>(*vts);
BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket"
<< " to be of type BlackVolatilityWithATM");
auto surface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(tmSurface->surface());
BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket to contain"
<< " a surface of type BlackVarianceSurfaceSparse");
// The expected NYMEX CL volatility data
NymexVolatilityData expData;
// Check what is loaded against expected data as provided in market data file for NYMEX:CL.
// Note: the BlackVarianceSurfaceSparse adds a dummy expiry slice at time zero
BOOST_REQUIRE_EQUAL(surface->expiries().size() - 1, expData.expiries.size());
for (Size i = 0; i < expData.strikes.size(); i++) {
BOOST_CHECK_EQUAL(surface->expiries()[i + 1], expData.expiries[i]);
}
BOOST_REQUIRE_EQUAL(surface->strikes().size() - 1, expData.strikes.size());
for (Size i = 0; i < expData.strikes.size(); i++) {
// Check the strikes against the input
Date e = expData.expiries[i];
BOOST_REQUIRE_EQUAL(surface->strikes()[i + 1].size(), expData.strikes[e].size());
for (Size j = 0; j < surface->strikes()[i + 1].size(); j++) {
BOOST_CHECK_CLOSE(expData.strikes[e][j], surface->strikes()[i + 1][j], 1e-12);
}
// Check the volatilities against the input
BOOST_REQUIRE_EQUAL(surface->values()[i + 1].size(), expData.volatilities[e].size());
for (Size j = 0; j < surface->values()[i + 1].size(); j++) {
BOOST_CHECK_CLOSE(expData.volatilities[e][j], surface->blackVol(e, surface->strikes()[i + 1][j]), 1e-12);
}
}
}
BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceWildcardExpiriesExplicitStrikes) {
BOOST_TEST_MESSAGE(
"Testing commodity volatility curve building wildcard expiries and explicit strikes in configuration");
auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data",
"curveconfig_surface_wc_expiries_explicit_strikes.xml");
auto vts = todaysMarket->commodityVolatility("NYMEX:CL");
// Wildcards in configuration so we know that a BlackVarianceSurfaceSparse has been created and fed to a
// BlackVolatilityWithATM surface in TodaysMarket
auto tmSurface = boost::dynamic_pointer_cast<BlackVolatilityWithATM>(*vts);
BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket"
<< " to be of type BlackVolatilityWithATM");
auto surface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(tmSurface->surface());
BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket to contain"
<< " a surface of type BlackVarianceSurfaceSparse");
// The expected NYMEX CL volatility data
NymexVolatilityData expData;
// Check what is loaded against expected data as provided in market data file for NYMEX:CL. The explicit strikes
// that we have chosen lead have only two corresponding expiries i.e. 2019-10-17 and 2019-12-16
// Note: the BlackVarianceSurfaceSparse adds a dummy expiry slice at time zero
vector<Date> expExpiries{Date(17, Oct, 2019), Date(16, Dec, 2019)};
BOOST_REQUIRE_EQUAL(surface->expiries().size() - 1, expExpiries.size());
for (Size i = 0; i < expExpiries.size(); i++) {
BOOST_CHECK_EQUAL(surface->expiries()[i + 1], expExpiries[i]);
}
// The explicit strikes in the config are 60 and 61
vector<Real> expStrikes{60, 61};
BOOST_REQUIRE_EQUAL(surface->strikes().size() - 1, expExpiries.size());
for (Size i = 0; i < expExpiries.size(); i++) {
// Check the strikes against the expected explicit strikes
BOOST_REQUIRE_EQUAL(surface->strikes()[i + 1].size(), expStrikes.size());
for (Size j = 0; j < surface->strikes()[i + 1].size(); j++) {
BOOST_CHECK_CLOSE(expStrikes[j], surface->strikes()[i + 1][j], 1e-12);
}
// Check the volatilities against the input
Date e = expExpiries[i];
BOOST_REQUIRE_EQUAL(surface->values()[i + 1].size(), expStrikes.size());
for (Size j = 0; j < surface->values()[i + 1].size(); j++) {
// Find the index of the explicit strike in the input data
Real expStrike = expStrikes[j];
auto it = find_if(expData.strikes[e].begin(), expData.strikes[e].end(),
[expStrike](Real s) { return close(expStrike, s); });
BOOST_REQUIRE_MESSAGE(it != expData.strikes[e].end(), "Strike not found in input strikes");
auto idx = distance(expData.strikes[e].begin(), it);
BOOST_CHECK_CLOSE(expData.volatilities[e][idx], surface->blackVol(e, surface->strikes()[i + 1][j]), 1e-12);
}
}
}
BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceExplicitExpiriesWildcardStrikes) {
BOOST_TEST_MESSAGE(
"Testing commodity volatility curve building explicit expiries and wildcard strikes in configuration");
auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data",
"curveconfig_surface_explicit_expiries_wc_strikes.xml");
auto vts = todaysMarket->commodityVolatility("NYMEX:CL");
// Wildcards in configuration so we know that a BlackVarianceSurfaceSparse has been created and fed to a
// BlackVolatilityWithATM surface in TodaysMarket
auto tmSurface = boost::dynamic_pointer_cast<BlackVolatilityWithATM>(*vts);
BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket"
<< " to be of type BlackVolatilityWithATM");
auto surface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(tmSurface->surface());
BOOST_REQUIRE_MESSAGE(tmSurface, "Expected the commodity vol structure in TodaysMarket to contain"
<< " a surface of type BlackVarianceSurfaceSparse");
// The expected NYMEX CL volatility data
NymexVolatilityData expData;
// Check what is loaded against expected data as provided in market data file for NYMEX:CL.
// We have chosen the explicit expiries 2019-10-17 and 2019-12-16
// Note: the BlackVarianceSurfaceSparse adds a dummy expiry slice at time zero
vector<Date> expExpiries{Date(17, Oct, 2019), Date(16, Dec, 2019)};
BOOST_REQUIRE_EQUAL(surface->expiries().size() - 1, expExpiries.size());
for (Size i = 0; i < expExpiries.size(); i++) {
BOOST_CHECK_EQUAL(surface->expiries()[i + 1], expExpiries[i]);
}
BOOST_REQUIRE_EQUAL(surface->strikes().size() - 1, expExpiries.size());
for (Size i = 0; i < expExpiries.size(); i++) {
// Check the strikes against the input
Date e = expExpiries[i];
BOOST_REQUIRE_EQUAL(surface->strikes()[i + 1].size(), expData.strikes[e].size());
for (Size j = 0; j < surface->strikes()[i + 1].size(); j++) {
BOOST_CHECK_CLOSE(expData.strikes[e][j], surface->strikes()[i + 1][j], 1e-12);
}
// Check the volatilities against the input
BOOST_REQUIRE_EQUAL(surface->values()[i + 1].size(), expData.volatilities[e].size());
for (Size j = 0; j < surface->values()[i + 1].size(); j++) {
BOOST_CHECK_CLOSE(expData.volatilities[e][j], surface->blackVol(e, surface->strikes()[i + 1][j]), 1e-12);
}
}
}
BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceExplicitExpiriesExplicitStrikes) {
BOOST_TEST_MESSAGE(
"Testing commodity volatility curve building explicit expiries and explicit strikes in configuration");
auto todaysMarket = createTodaysMarket(Date(16, Sep, 2019), "wildcard_data",
"curveconfig_surface_explicit_expiries_explicit_strikes.xml");
auto vts = todaysMarket->commodityVolatility("NYMEX:CL");
// The expected NYMEX CL volatility data
NymexVolatilityData expData;
// We have provided two explicit expiries, 2019-10-17 and 2019-12-16, and two explicit strikes, 60 and 61.
// We check the volatility term structure at these 4 points against the input data
vector<Date> expExpiries{Date(17, Oct, 2019), Date(16, Dec, 2019)};
vector<Real> expStrikes{60, 61};
for (const Date& e : expExpiries) {
for (Real s : expStrikes) {
// Find the index of the explicit strike in the input data
auto it = find_if(expData.strikes[e].begin(), expData.strikes[e].end(),
[s](Real strike) { return close(strike, s); });
BOOST_REQUIRE_MESSAGE(it != expData.strikes[e].end(), "Strike not found in input strikes");
auto idx = distance(expData.strikes[e].begin(), it);
Real inputVol = expData.volatilities[e][idx];
BOOST_CHECK_CLOSE(inputVol, vts->blackVol(e, s), 1e-12);
}
}
}
// As of dates for delta surface building below.
// 15 Jan is when c1 contract rolls from NYMEX WTI Feb option contract to NYMEX WTI Mar option contract
vector<Date> asofDates{Date(13, Jan, 2020), Date(15, Jan, 2020)};
// Different curve configurations for the surface building below.
vector<string> curveConfigs{"curveconfig_explicit_expiries.xml", "curveconfig_wildcard_expiries.xml"};
BOOST_DATA_TEST_CASE(testCommodityVolDeltaSurface, bdata::make(asofDates) * bdata::make(curveConfigs), asof,
curveConfig) {
BOOST_TEST_MESSAGE("Testing commodity volatility delta surface building");
auto todaysMarket = createTodaysMarket(asof, "delta_surface", curveConfig, "market.txt");
// Get the built commodity volatility surface
auto vts = todaysMarket->commodityVolatility("NYMEX:CL");
// Cast to expected type and check that it succeeds
// For some reason, todaysmarket wraps the surface built in CommodityVolCurve in a BlackVolatilityWithATM.
auto bvwa = dynamic_pointer_cast<BlackVolatilityWithATM>(*vts);
BOOST_REQUIRE(bvwa);
auto bvsd = boost::dynamic_pointer_cast<BlackVolatilitySurfaceDelta>(bvwa->surface());
BOOST_REQUIRE(bvsd);
// Tolerance for float comparison
Real tol = 1e-12;
// Read in the expected on-grid results for the given date.
string filename = "delta_surface/expected_grid_" + to_string(io::iso_date(asof)) + ".csv";
CSVFileReader reader(TEST_INPUT_FILE(filename), true, ",");
BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 3);
while (reader.next()) {
// Get the expected expiry date, strike and volatility grid point
Date expiryDate = parseDate(reader.get(0));
Real strike = parseReal(reader.get(1));
Real volatility = parseReal(reader.get(2));
// Check that the expected grid expiry date is one of the surface dates
auto itExpiry = find(bvsd->dates().begin(), bvsd->dates().end(), expiryDate);
BOOST_REQUIRE(itExpiry != bvsd->dates().end());
// Get the smile section, cast to expected type and check cast succeeds.
auto fxss = bvsd->blackVolSmile(expiryDate);
auto iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss);
BOOST_REQUIRE(iss);
// Check that the expected grid strike is one of the smile section strikes.
auto itStrike =
find_if(iss->strikes().begin(), iss->strikes().end(), [&](Real s) { return std::abs(s - strike) < tol; });
BOOST_REQUIRE(itStrike != iss->strikes().end());
// Check that the expected volatility is equal to that at the grid strike
auto pos = distance(iss->strikes().begin(), itStrike);
BOOST_CHECK_SMALL(volatility - iss->volatilities()[pos], tol);
}
// Check flat time extrapolation
auto fxss = bvsd->blackVolSmile(bvsd->dates().back());
auto iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss);
BOOST_REQUIRE(iss);
vector<Real> lastVolatilities = iss->volatilities();
fxss = bvsd->blackVolSmile(bvsd->dates().back() + 1 * Years);
iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss);
BOOST_REQUIRE(iss);
vector<Real> extrapVolatilities = iss->volatilities();
BOOST_REQUIRE_EQUAL(lastVolatilities.size(), extrapVolatilities.size());
for (Size i = 0; i < lastVolatilities.size(); i++) {
BOOST_CHECK_SMALL(lastVolatilities[i] - extrapVolatilities[i], tol);
}
// Check flat strike extrapolation.
Date testDate = asof + 1 * Years;
fxss = bvsd->blackVolSmile(testDate);
iss = boost::dynamic_pointer_cast<InterpolatedSmileSection>(fxss);
BOOST_REQUIRE(iss);
Volatility volAtMinStrike = iss->volatilities().front();
Real minStrike = iss->strikes().front();
Real extrapStrike = minStrike / 2.0;
BOOST_CHECK_SMALL(volAtMinStrike - bvsd->blackVol(testDate, extrapStrike), tol);
Volatility volAtMaxStrike = iss->volatilities().back();
Real maxStrike = iss->strikes().back();
extrapStrike = maxStrike * 2.0;
BOOST_CHECK_SMALL(volAtMaxStrike - bvsd->blackVol(testDate, extrapStrike), tol);
}
BOOST_DATA_TEST_CASE(testCommodityVolMoneynessSurface, bdata::make(asofDates) * bdata::make(curveConfigs), asof,
curveConfig) {
BOOST_TEST_MESSAGE("Testing commodity volatility forward moneyness surface building");
Settings::instance().evaluationDate() = asof;
auto todaysMarket = createTodaysMarket(asof, "moneyness_surface", curveConfig, "market.txt");
// Get the built commodity volatility surface
auto vts = todaysMarket->commodityVolatility("NYMEX:CL");
// Tolerance for float comparison
Real tol = 1e-12;
// Read in the expected on-grid results for the given date.
string filename = "moneyness_surface/expected_grid_" + to_string(io::iso_date(asof)) + ".csv";
CSVFileReader reader(TEST_INPUT_FILE(filename), true, ",");
BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 3);
while (reader.next()) {
// Get the expected expiry date, strike and volatility grid point
Date expiryDate = parseDate(reader.get(0));
Real strike = parseReal(reader.get(1));
Real volatility = parseReal(reader.get(2));
// Check the surface on the grid point.
BOOST_CHECK_SMALL(volatility - vts->blackVol(expiryDate, strike), tol);
}
// Price term structure
auto pts = todaysMarket->commodityPriceCurve("NYMEX:CL");
// Pick two future expiries beyond max vol surface time and get their prices
// This should correspond to moneyness 1.0 and we should see flat vol extrapolation.
// This only passes because we have set sticky strike to false in CommodityVolCurve.
Date extrapDate_1(20, Mar, 2024);
Date extrapDate_2(22, Apr, 2024);
Real strike_1 = pts->price(extrapDate_1);
Real strike_2 = pts->price(extrapDate_2);
Volatility vol_1 = vts->blackVol(extrapDate_1, strike_1);
Volatility vol_2 = vts->blackVol(extrapDate_2, strike_2);
BOOST_TEST_MESSAGE("The two time extrapolated volatilities are: " << fixed << setprecision(12) << vol_1 << ","
<< vol_2 << ".");
BOOST_CHECK_SMALL(vol_1 - vol_2, tol);
// Test flat strike extrapolation at lower and upper strikes i.e. at 50% and 150% forward moneyness.
Date optionExpiry(14, Jan, 2021);
Date futureExpiry(20, Jan, 2021);
Real futurePrice = pts->price(futureExpiry);
Real lowerStrike = 0.5 * futurePrice;
Volatility volLowerStrike = vts->blackVol(optionExpiry, lowerStrike);
Volatility volLowerExtrapStrike = vts->blackVol(optionExpiry, lowerStrike / 2.0);
BOOST_TEST_MESSAGE("The two lower strike extrapolated volatilities are: "
<< fixed << setprecision(12) << volLowerStrike << "," << volLowerExtrapStrike << ".");
BOOST_CHECK_SMALL(volLowerStrike - volLowerExtrapStrike, tol);
Real upperStrike = 1.5 * futurePrice;
Volatility volUpperStrike = vts->blackVol(optionExpiry, upperStrike);
Volatility volUpperExtrapStrike = vts->blackVol(optionExpiry, upperStrike * 2.0);
BOOST_TEST_MESSAGE("The two upper strike extrapolated volatilities are: "
<< fixed << setprecision(12) << volUpperStrike << "," << volUpperExtrapStrike << ".");
BOOST_CHECK_SMALL(volUpperStrike - volUpperExtrapStrike, tol);
}
BOOST_DATA_TEST_CASE(testCommodityApoSurface, bdata::make(asofDates), asof) {
BOOST_TEST_MESSAGE("Testing commodity volatility forward moneyness surface building");
Settings::instance().evaluationDate() = asof;
string fixingsFile = "fixings_" + to_string(io::iso_date(asof)) + ".txt";
auto todaysMarket = createTodaysMarket(asof, "apo_surface", "curveconfig.xml", "market.txt", fixingsFile);
// Get the built commodity volatility surface
auto vts = todaysMarket->commodityVolatility("NYMEX:FF");
// Tolerance for float comparison
Real tol = 1e-12;
// Read in the expected on-grid results for the given date.
string filename = "apo_surface/expected_grid_" + to_string(io::iso_date(asof)) + ".csv";
CSVFileReader reader(TEST_INPUT_FILE(filename), true, ",");
BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 3);
BOOST_TEST_MESSAGE("exp_vol,calc_vol,difference");
while (reader.next()) {
// Get the expected expiry date, strike and volatility grid point
Date expiryDate = parseDate(reader.get(0));
Real strike = parseReal(reader.get(1));
Real volatility = parseReal(reader.get(2));
// Check the surface on the grid point.
auto calcVolatility = vts->blackVol(expiryDate, strike);
auto difference = volatility - calcVolatility;
BOOST_TEST_MESSAGE(std::fixed << std::setprecision(12) << strike << "," << volatility << "," << calcVolatility
<< "," << difference);
BOOST_CHECK_SMALL(difference, tol);
}
}
// Main point of this test is to test that the option expiries are interpreted correctly.
BOOST_AUTO_TEST_CASE(testCommodityVolSurfaceMyrCrudePalmOil) {
BOOST_TEST_MESSAGE("Testing commodity volatility delta surface building for MYR Crude Palm Oil");
Date asof(14, Oct, 2020);
auto todaysMarket = createTodaysMarket(asof, "myr_crude_palm_oil", "curveconfig.xml", "market.txt");
// Get the built commodity volatility surface
auto vts = todaysMarket->commodityVolatility("XKLS:FCPO");
// Check that it built ok i.e. can query a volatility.
BOOST_CHECK_NO_THROW(vts->blackVol(1.0, 2800));
// Cast to expected type and check that it succeeds
// For some reason, todaysmarket wraps the surface built in CommodityVolCurve in a BlackVolatilityWithATM.
auto bvwa = dynamic_pointer_cast<BlackVolatilityWithATM>(*vts);
BOOST_REQUIRE(bvwa);
auto bvsd = boost::dynamic_pointer_cast<BlackVolatilitySurfaceDelta>(bvwa->surface());
BOOST_REQUIRE(bvsd);
// Now check that the surface dates are as expected.
// Calculated surface dates.
const vector<Date>& surfaceDates = bvsd->dates();
// Read in the expected dates.
vector<Date> expectedDates;
string filename = "myr_crude_palm_oil/expected_expiries.csv";
CSVFileReader reader(TEST_INPUT_FILE(filename), true, ",");
BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 1);
while (reader.next()) {
expectedDates.push_back(parseDate(reader.get(0)));
}
// Check equal.
BOOST_CHECK_EQUAL_COLLECTIONS(surfaceDates.begin(), surfaceDates.end(), expectedDates.begin(), expectedDates.end());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 36,721 | 13,049 |
auto Cartridge::readIO(n16 address) -> n8 {
n8 data;
switch(address) {
case 0x00c0: //BANK_ROM2
data = io.romBank2;
break;
case 0x00c1: //BANK_SRAM
data = io.sramBank;
break;
case 0x00c2: //BANK_ROM0
data = io.romBank0;
break;
case 0x00c3: //BANK_ROM1
data = io.romBank1;
break;
case 0x00c4: //EEP_DATALO
data = eeprom.read(EEPROM::DataLo);
break;
case 0x00c5: //EEP_DATAHI
data = eeprom.read(EEPROM::DataHi);
break;
case 0x00c6: //EEP_ADDRLO
data = eeprom.read(EEPROM::AddressLo);
break;
case 0x00c7: //EEP_ADDRHI
data = eeprom.read(EEPROM::AddressHi);
break;
case 0x00c8: //EEP_STATUS
data = eeprom.read(EEPROM::Status);
break;
case 0x00ca: //RTC_STATUS
data = rtc.status();
break;
case 0x00cb: //RTC_DATA
data = rtc.read();
break;
case 0x00cc: //GPO_EN
data = io.gpoEnable;
break;
case 0x00cd: //GPO_DATA
data = io.gpoData;
break;
}
return data;
}
auto Cartridge::writeIO(n16 address, n8 data) -> void {
switch(address) {
case 0x00c0: //BANK_ROM2
io.romBank2 = data;
break;
case 0x00c1: //BANK_SRAM
io.sramBank = data;
break;
case 0x00c2: //BANK_ROM0
io.romBank0 = data;
break;
case 0x00c3: //BANK_ROM1
io.romBank1 = data;
break;
case 0x00c4: //EEP_DATALO
eeprom.write(EEPROM::DataLo, data);
break;
case 0x00c5: //EEP_DATAHI
eeprom.write(EEPROM::DataHi, data);
break;
case 0x00c6: //EEP_ADDRLO
eeprom.write(EEPROM::AddressLo, data);
break;
case 0x00c7: //EEP_ADDRHI
eeprom.write(EEPROM::AddressHi, data);
break;
case 0x00c8: //EEP_CMD
eeprom.write(EEPROM::Command, data);
break;
case 0x00ca: //RTC_CMD
rtc.execute(data);
break;
case 0x00cb: //RTC_DATA
rtc.write(data);
break;
case 0x00cc: //GPO_EN
io.gpoEnable = data;
break;
case 0x00cd: //GPO_DATA
io.gpoData = data;
break;
}
return;
}
| 2,023 | 1,011 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////////
// ResFile.CPP
#include "common.h"
#include "assemblynativeresource.h"
#include <limits.h>
#ifndef CP_WINUNICODE
#define CP_WINUNICODE 1200
#endif
#ifndef MAKEINTRESOURCE
#define MAKEINTRESOURCE MAKEINTRESOURCEW
#endif
Win32Res::Win32Res()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
m_szFile = NULL;
m_Icon = NULL;
int i;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
m_fDll = false;
m_pData = NULL;
m_pCur = NULL;
m_pEnd = NULL;
}
Win32Res::~Win32Res()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
m_szFile = NULL;
m_Icon = NULL;
int i;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
for (i = 0; i < NUM_VALUES; i++)
m_Values[i] = NULL;
m_fDll = false;
if (m_pData)
delete [] m_pData;
m_pData = NULL;
m_pCur = NULL;
m_pEnd = NULL;
}
//*****************************************************************************
// Initializes the structures with version information.
//*****************************************************************************
VOID Win32Res::SetInfo(
LPCWSTR szFile,
LPCWSTR szTitle,
LPCWSTR szIconName,
LPCWSTR szDescription,
LPCWSTR szCopyright,
LPCWSTR szTrademark,
LPCWSTR szCompany,
LPCWSTR szProduct,
LPCWSTR szProductVersion,
LPCWSTR szFileVersion,
LCID lcid,
BOOL fDLL)
{
STANDARD_VM_CONTRACT;
_ASSERTE(szFile != NULL);
m_szFile = szFile;
if (szIconName && szIconName[0] != 0)
m_Icon = szIconName; // a non-mepty string
#define NonNull(sz) (sz == NULL || *sz == W('\0') ? W(" ") : sz)
m_Values[v_Description] = NonNull(szDescription);
m_Values[v_Title] = NonNull(szTitle);
m_Values[v_Copyright] = NonNull(szCopyright);
m_Values[v_Trademark] = NonNull(szTrademark);
m_Values[v_Product] = NonNull(szProduct);
m_Values[v_ProductVersion] = NonNull(szProductVersion);
m_Values[v_Company] = NonNull(szCompany);
m_Values[v_FileVersion] = NonNull(szFileVersion);
#undef NonNull
m_fDll = fDLL;
m_lcid = lcid;
}
VOID Win32Res::MakeResFile(const void **pData, DWORD *pcbData)
{
STANDARD_VM_CONTRACT;
static const RESOURCEHEADER magic = { 0x00000000, 0x00000020, 0xFFFF, 0x0000, 0xFFFF, 0x0000,
0x00000000, 0x0000, 0x0000, 0x00000000, 0x00000000 };
_ASSERTE(pData != NULL && pcbData != NULL);
*pData = NULL;
*pcbData = 0;
m_pData = new BYTE[(sizeof(RESOURCEHEADER) * 3 + sizeof(EXEVERRESOURCE))];
m_pCur = m_pData;
m_pEnd = m_pData + sizeof(RESOURCEHEADER) * 3 + sizeof(EXEVERRESOURCE);
// inject the magic empty entry
Write( &magic, sizeof(magic) );
WriteVerResource();
if (m_Icon)
{
WriteIconResource();
}
*pData = m_pData;
*pcbData = (DWORD)(m_pCur - m_pData);
return;
}
/*
* WriteIconResource
* Writes the Icon resource into the RES file.
*
* RETURNS: TRUE on succes, FALSE on failure (errors reported to user)
*/
VOID Win32Res::WriteIconResource()
{
STANDARD_VM_CONTRACT;
HandleHolder hIconFile = INVALID_HANDLE_VALUE;
WORD wTemp, wCount, resID = 2; // Skip 1 for the version ID
DWORD dwRead = 0, dwWritten = 0;
RESOURCEHEADER grpHeader = { 0x00000000, 0x00000020, 0xFFFF, (WORD)(size_t)RT_GROUP_ICON, 0xFFFF, 0x7F00, // 0x7F00 == IDI_APPLICATION
0x00000000, 0x1030, 0x0000, 0x00000000, 0x00000000 };
// Read the icon
hIconFile = WszCreateFile( m_Icon, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (hIconFile == INVALID_HANDLE_VALUE) {
COMPlusThrowWin32();
}
// Read the magic reserved WORD
if (ReadFile( hIconFile, &wTemp, sizeof(WORD), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
} else if (wTemp != 0 || dwRead != sizeof(WORD)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
// Verify the Type WORD
if (ReadFile( hIconFile, &wCount, sizeof(WORD), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
} else if (wCount != 1 || dwRead != sizeof(WORD)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
// Read the Count WORD
if (ReadFile( hIconFile, &wCount, sizeof(WORD), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
} else if (wCount == 0 || dwRead != sizeof(WORD)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
NewArrayHolder<ICONRESDIR> grp = new ICONRESDIR[wCount];
grpHeader.DataSize = 3 * sizeof(WORD) + wCount * sizeof(ICONRESDIR);
// For each Icon
for (WORD i = 0; i < wCount; i++) {
ICONDIRENTRY ico;
DWORD icoPos, newPos;
RESOURCEHEADER icoHeader = { 0x00000000, 0x00000020, 0xFFFF, (WORD)(size_t)RT_ICON, 0xFFFF, 0x0000,
0x00000000, 0x1010, 0x0000, 0x00000000, 0x00000000 };
icoHeader.Name = resID++;
// Read the Icon header
if (ReadFile( hIconFile, &ico, sizeof(ICONDIRENTRY), &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
}
else if (dwRead != sizeof(ICONDIRENTRY)) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
_ASSERTE(sizeof(ICONRESDIR) + sizeof(WORD) == sizeof(ICONDIRENTRY));
memcpy(grp + i, &ico, sizeof(ICONRESDIR));
grp[i].IconId = icoHeader.Name;
icoHeader.DataSize = ico.dwBytesInRes;
NewArrayHolder<BYTE> icoBuffer = new BYTE[icoHeader.DataSize];
// Write the header to the RES file
Write( &icoHeader, sizeof(RESOURCEHEADER) );
// Position to read the Icon data
icoPos = SetFilePointer( hIconFile, 0, NULL, FILE_CURRENT);
if (icoPos == INVALID_SET_FILE_POINTER) {
COMPlusThrowWin32();
}
newPos = SetFilePointer( hIconFile, ico.dwImageOffset, NULL, FILE_BEGIN);
if (newPos == INVALID_SET_FILE_POINTER) {
COMPlusThrowWin32();
}
// Actually read the data
if (ReadFile( hIconFile, icoBuffer, icoHeader.DataSize, &dwRead, NULL) == FALSE) {
COMPlusThrowWin32();
}
else if (dwRead != icoHeader.DataSize) {
COMPlusThrowHR(HRESULT_FROM_WIN32(ERROR_INVALID_DATA));
}
// Because Icon files don't seem to record the actual Planes and BitCount in
// the ICONDIRENTRY, get the info from the BITMAPINFOHEADER at the beginning
// of the data here:
grp[i].Planes = ((BITMAPINFOHEADER*)(BYTE*)icoBuffer)->biPlanes;
grp[i].BitCount = ((BITMAPINFOHEADER*)(BYTE*)icoBuffer)->biBitCount;
// Now write the data to the RES file
Write( (BYTE*)icoBuffer, icoHeader.DataSize );
// Reposition to read the next Icon header
newPos = SetFilePointer( hIconFile, icoPos, NULL, FILE_BEGIN);
if (newPos != icoPos) {
COMPlusThrowWin32();
}
}
// inject the icon group
Write( &grpHeader, sizeof(RESOURCEHEADER) );
// Write the header to the RES file
wTemp = 0; // the reserved WORD
Write( &wTemp, sizeof(WORD) );
wTemp = RES_ICON; // the GROUP type
Write( &wTemp, sizeof(WORD) );
Write( &wCount, sizeof(WORD) );
// now write the entries
Write( grp, sizeof(ICONRESDIR) * wCount );
return;
}
/*
* WriteVerResource
* Writes the version resource into the RES file.
*
* RETURNS: TRUE on succes, FALSE on failure (errors reported to user)
*/
VOID Win32Res::WriteVerResource()
{
STANDARD_VM_CONTRACT;
WCHAR szLangCp[9]; // language/codepage string.
EXEVERRESOURCE VerResource;
WORD cbStringBlocks;
int i;
bool bUseFileVer = false;
WCHAR rcFile[_MAX_PATH] = {0}; // Name of file without path
WCHAR rcFileExtension[_MAX_PATH] = {0}; // file extension
WCHAR rcFileName[_MAX_PATH]; // Name of file with extension but without path
DWORD cbTmp;
SplitPath(m_szFile, 0, 0, 0, 0, rcFile, _MAX_PATH, rcFileExtension, _MAX_PATH);
wcscpy_s(rcFileName, COUNTOF(rcFileName), rcFile);
wcscat_s(rcFileName, COUNTOF(rcFileName), rcFileExtension);
static const EXEVERRESOURCE VerResourceTemplate = {
sizeof(EXEVERRESOURCE), sizeof(VS_FIXEDFILEINFO), 0, W("VS_VERSION_INFO"),
{
VS_FFI_SIGNATURE, // Signature
VS_FFI_STRUCVERSION, // structure version
0, 0, // file version number
0, 0, // product version number
VS_FFI_FILEFLAGSMASK, // file flags mask
0, // file flags
VOS__WINDOWS32,
VFT_APP, // file type
0, // subtype
0, 0 // file date/time
},
sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES("VarFileInfo") + KEYBYTES("Translation"),
0,
1,
W("VarFileInfo"),
sizeof(WORD) * 2 + HDRSIZE + KEYBYTES("Translation"),
sizeof(WORD) * 2,
0,
W("Translation"),
0,
0,
2 * HDRSIZE + KEYBYTES("StringFileInfo") + KEYBYTES("12345678"),
0,
1,
W("StringFileInfo"),
HDRSIZE + KEYBYTES("12345678"),
0,
1,
W("12345678")
};
static const WCHAR szComments[] = W("Comments");
static const WCHAR szCompanyName[] = W("CompanyName");
static const WCHAR szFileDescription[] = W("FileDescription");
static const WCHAR szCopyright[] = W("LegalCopyright");
static const WCHAR szTrademark[] = W("LegalTrademarks");
static const WCHAR szProdName[] = W("ProductName");
static const WCHAR szFileVerResName[] = W("FileVersion");
static const WCHAR szProdVerResName[] = W("ProductVersion");
static const WCHAR szInternalNameResName[] = W("InternalName");
static const WCHAR szOriginalNameResName[] = W("OriginalFilename");
// If there's no product version, use the file version
if (m_Values[v_ProductVersion][0] == 0) {
m_Values[v_ProductVersion] = m_Values[v_FileVersion];
bUseFileVer = true;
}
// Keep the two following arrays in the same order
#define MAX_KEY 10
static const LPCWSTR szKeys [MAX_KEY] = {
szComments,
szCompanyName,
szFileDescription,
szFileVerResName,
szInternalNameResName,
szCopyright,
szTrademark,
szOriginalNameResName,
szProdName,
szProdVerResName,
};
LPCWSTR szValues [MAX_KEY] = { // values for keys
m_Values[v_Description], //compiler->assemblyDescription == NULL ? W("") : compiler->assemblyDescription,
m_Values[v_Company], // Company Name
m_Values[v_Title], // FileDescription //compiler->assemblyTitle == NULL ? W("") : compiler->assemblyTitle,
m_Values[v_FileVersion], // FileVersion
rcFileName, // InternalName
m_Values[v_Copyright], // Copyright
m_Values[v_Trademark], // Trademark
rcFileName, // OriginalName
m_Values[v_Product], // Product Name //compiler->assemblyTitle == NULL ? W("") : compiler->assemblyTitle,
m_Values[v_ProductVersion] // Product Version
};
memcpy(&VerResource, &VerResourceTemplate, sizeof(VerResource));
if (m_fDll)
VerResource.vsFixed.dwFileType = VFT_DLL;
else
VerResource.vsFixed.dwFileType = VFT_APP;
// Extract the numeric version from the string.
m_Version[0] = m_Version[1] = m_Version[2] = m_Version[3] = 0;
int nNumStrings = swscanf_s(m_Values[v_FileVersion], W("%hu.%hu.%hu.%hu"), m_Version, m_Version + 1, m_Version + 2, m_Version + 3);
// Fill in the FIXEDFILEINFO
VerResource.vsFixed.dwFileVersionMS =
((DWORD)m_Version[0] << 16) + m_Version[1];
VerResource.vsFixed.dwFileVersionLS =
((DWORD)m_Version[2] << 16) + m_Version[3];
if (bUseFileVer) {
VerResource.vsFixed.dwProductVersionLS = VerResource.vsFixed.dwFileVersionLS;
VerResource.vsFixed.dwProductVersionMS = VerResource.vsFixed.dwFileVersionMS;
}
else {
WORD v[4];
v[0] = v[1] = v[2] = v[3] = 0;
// Try to get the version numbers, but don't waste time or give any errors
// just default to zeros
nNumStrings = swscanf_s(m_Values[v_ProductVersion], W("%hu.%hu.%hu.%hu"), v, v + 1, v + 2, v + 3);
VerResource.vsFixed.dwProductVersionMS =
((DWORD)v[0] << 16) + v[1];
VerResource.vsFixed.dwProductVersionLS =
((DWORD)v[2] << 16) + v[3];
}
// There is no documentation on what units to use for the date! So we use zero.
// The Windows resource compiler does too.
VerResource.vsFixed.dwFileDateMS = VerResource.vsFixed.dwFileDateLS = 0;
// Fill in codepage/language -- we'll assume the IDE language/codepage
// is the right one.
if (m_lcid != -1)
VerResource.langid = static_cast<WORD>(m_lcid);
else
VerResource.langid = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
VerResource.codepage = CP_WINUNICODE; // Unicode codepage.
swprintf_s(szLangCp, NumItems(szLangCp), W("%04x%04x"), VerResource.langid, VerResource.codepage);
wcscpy_s(VerResource.szLangCpKey, COUNTOF(VerResource.szLangCpKey), szLangCp);
// Determine the size of all the string blocks.
cbStringBlocks = 0;
for (i = 0; i < MAX_KEY; i++) {
if (szValues[i] == NULL || wcslen(szValues[i]) == 0)
continue;
cbTmp = SizeofVerString( szKeys[i], szValues[i]);
if ((cbStringBlocks + cbTmp) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
cbStringBlocks += (WORD) cbTmp;
}
if ((cbStringBlocks + VerResource.cbLangCpBlock) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
VerResource.cbLangCpBlock += cbStringBlocks;
if ((cbStringBlocks + VerResource.cbStringBlock) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
VerResource.cbStringBlock += cbStringBlocks;
if ((cbStringBlocks + VerResource.cbRootBlock) > USHRT_MAX / 2)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
VerResource.cbRootBlock += cbStringBlocks;
// Call this VS_VERSION_INFO
RESOURCEHEADER verHeader = { 0x00000000, 0x0000003C, 0xFFFF, (WORD)(size_t)RT_VERSION, 0xFFFF, 0x0001,
0x00000000, 0x0030, 0x0000, 0x00000000, 0x00000000 };
verHeader.DataSize = VerResource.cbRootBlock;
// Write the header
Write( &verHeader, sizeof(RESOURCEHEADER) );
// Write the version resource
Write( &VerResource, sizeof(VerResource) );
// Write each string block.
for (i = 0; i < MAX_KEY; i++) {
if (szValues[i] == NULL || wcslen(szValues[i]) == 0)
continue;
WriteVerString( szKeys[i], szValues[i] );
}
#undef MAX_KEY
return;
}
/*
* SizeofVerString
* Determines the size of a version string to the given stream.
* RETURNS: size of block in bytes.
*/
WORD Win32Res::SizeofVerString(LPCWSTR lpszKey, LPCWSTR lpszValue)
{
STANDARD_VM_CONTRACT;
size_t cbKey, cbValue;
cbKey = (wcslen(lpszKey) + 1) * 2; // Make room for the NULL
cbValue = (wcslen(lpszValue) + 1) * 2;
if (cbValue == 2)
cbValue = 4; // Empty strings need a space and NULL terminator (for Win9x)
if (cbKey + cbValue >= 0xFFF0)
COMPlusThrow(kArgumentException, W("Argument_VerStringTooLong"));
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:6305) // "Potential mismatch between sizeof and countof quantities"
#endif
return (WORD)(PadKeyLen(cbKey) + // key, 0 padded to DWORD boundary
PadValLen(cbValue) + // value, 0 padded to dword boundary
HDRSIZE); // block header.
#ifdef _PREFAST_
#pragma warning(pop)
#endif
}
/*----------------------------------------------------------------------------
* WriteVerString
* Writes a version string to the given file.
*/
VOID Win32Res::WriteVerString( LPCWSTR lpszKey, LPCWSTR lpszValue)
{
STANDARD_VM_CONTRACT;
size_t cbKey, cbValue, cbBlock;
bool bNeedsSpace = false;
cbKey = (wcslen(lpszKey) + 1) * 2; // includes terminating NUL
cbValue = wcslen(lpszValue);
if (cbValue > 0)
cbValue++; // make room for NULL
else {
bNeedsSpace = true;
cbValue = 2; // Make room for space and NULL (for Win9x)
}
cbBlock = SizeofVerString(lpszKey, lpszValue);
NewArrayHolder<BYTE> pbBlock = new BYTE[(DWORD)cbBlock + HDRSIZE];
ZeroMemory(pbBlock, (DWORD)cbBlock + HDRSIZE);
_ASSERTE(cbValue < USHRT_MAX && cbKey < USHRT_MAX && cbBlock < USHRT_MAX);
// Copy header, key and value to block.
*(WORD *)((BYTE *)pbBlock) = (WORD)cbBlock;
*(WORD *)(pbBlock + sizeof(WORD)) = (WORD)cbValue;
*(WORD *)(pbBlock + 2 * sizeof(WORD)) = 1; // 1 = text value
// size = (cbBlock + HDRSIZE - HDRSIZE) / sizeof(WCHAR)
wcscpy_s((WCHAR*)(pbBlock + HDRSIZE), (cbBlock / sizeof(WCHAR)), lpszKey);
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:6305) // "Potential mismatch between sizeof and countof quantities"
#endif
if (bNeedsSpace)
*((WCHAR*)(pbBlock + (HDRSIZE + PadKeyLen(cbKey)))) = W(' ');
else
{
wcscpy_s((WCHAR*)(pbBlock + (HDRSIZE + PadKeyLen(cbKey))),
//size = ((cbBlock + HDRSIZE) - (HDRSIZE + PadKeyLen(cbKey))) / sizeof(WCHAR)
(cbBlock - PadKeyLen(cbKey))/sizeof(WCHAR),
lpszValue);
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
// Write block
Write( pbBlock, cbBlock);
return;
}
VOID Win32Res::Write(LPCVOID pData, size_t len)
{
STANDARD_VM_CONTRACT;
if (m_pCur + len > m_pEnd) {
// Grow
size_t newSize = (m_pEnd - m_pData);
// double the size unless we need more than that
if (len > newSize)
newSize += len;
else
newSize *= 2;
LPBYTE pNew = new BYTE[newSize];
memcpy(pNew, m_pData, m_pCur - m_pData);
delete [] m_pData;
// Relocate the pointers
m_pCur = pNew + (m_pCur - m_pData);
m_pData = pNew;
m_pEnd = pNew + newSize;
}
// Copy it in
memcpy(m_pCur, pData, len);
m_pCur += len;
return;
}
| 19,222 | 6,946 |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/promise-utils.h"
#include "src/factory.h"
#include "src/isolate.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
JSPromise* PromiseUtils::GetPromise(Handle<Context> context) {
return JSPromise::cast(context->get(kPromiseSlot));
}
Object* PromiseUtils::GetDebugEvent(Handle<Context> context) {
return context->get(kDebugEventSlot);
}
bool PromiseUtils::HasAlreadyVisited(Handle<Context> context) {
return Smi::cast(context->get(kAlreadyVisitedSlot))->value() != 0;
}
void PromiseUtils::SetAlreadyVisited(Handle<Context> context) {
context->set(kAlreadyVisitedSlot, Smi::FromInt(1));
}
} // namespace internal
} // namespace v8
| 844 | 291 |
// Copyright 2019 Luma Pictures
//
// 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.
//
// Modifications Copyright 2019 Autodesk, 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 "render_param.h"
#include "render_delegate.h"
#include <ai.h>
PXR_NAMESPACE_OPEN_SCOPE
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
HdArnoldRenderParam::HdArnoldRenderParam(HdArnoldRenderDelegate* delegate) : _delegate(delegate)
#else
HdArnoldRenderParam::HdArnoldRenderParam()
#endif
{
_needsRestart.store(false, std::memory_order::memory_order_release);
_aborted.store(false, std::memory_order::memory_order_release);
}
HdArnoldRenderParam::Status HdArnoldRenderParam::Render()
{
const auto aborted = _aborted.load(std::memory_order_acquire);
// Checking early if the render was aborted earlier.
if (aborted) {
return Status::Aborted;
}
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
const auto status = AiRenderGetStatus(_delegate->GetRenderSession());
#else
const auto status = AiRenderGetStatus();
#endif
if (status == AI_RENDER_STATUS_FINISHED) {
// If render restart is true, it means the Render Delegate received an update after rendering has finished
// and AiRenderInterrupt does not change the status anymore.
// For the atomic operations we are using a release-acquire model.
const auto needsRestart = _needsRestart.exchange(false, std::memory_order_acq_rel);
if (needsRestart) {
_paused.store(false, std::memory_order_release);
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderRestart(_delegate->GetRenderSession());
#else
AiRenderRestart();
#endif
return Status::Converging;
}
return Status::Converged;
}
// Resetting the value.
_needsRestart.store(false, std::memory_order_release);
if (status == AI_RENDER_STATUS_PAUSED) {
const auto needsRestart = _needsRestart.exchange(false, std::memory_order_acq_rel);
if (needsRestart) {
_paused.store(false, std::memory_order_release);
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderRestart(_delegate->GetRenderSession());
#else
AiRenderRestart();
#endif
} else if (!_paused.load(std::memory_order_acquire)) {
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderResume(_delegate->GetRenderSession());
#else
AiRenderResume();
#endif
}
return Status::Converging;
}
if (status == AI_RENDER_STATUS_RESTARTING) {
_paused.store(false, std::memory_order_release);
return Status::Converging;
}
if (status == AI_RENDER_STATUS_FAILED) {
_aborted.store(true, std::memory_order_release);
_paused.store(false, std::memory_order_release);
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
const auto errorCode = AiRenderEnd(_delegate->GetRenderSession());
#else
const auto errorCode = AiRenderEnd();
#endif
if (errorCode == AI_ABORT) {
TF_WARN("[arnold-usd] Render was aborted.");
} else if (errorCode == AI_ERROR_NO_CAMERA) {
TF_WARN("[arnold-usd] Camera not defined.");
} else if (errorCode == AI_ERROR_BAD_CAMERA) {
TF_WARN("[arnold-usd] Bad camera data.");
} else if (errorCode == AI_ERROR_VALIDATION) {
TF_WARN("[arnold-usd] Usage not validated.");
} else if (errorCode == AI_ERROR_RENDER_REGION) {
TF_WARN("[arnold-usd] Invalid render region.");
} else if (errorCode == AI_INTERRUPT) {
TF_WARN("[arnold-usd] Render interrupted by user.");
} else if (errorCode == AI_ERROR_NO_OUTPUTS) {
TF_WARN("[arnold-usd] No rendering outputs.");
} else if (errorCode == AI_ERROR_UNAVAILABLE_DEVICE) {
TF_WARN("[arnold-usd] Cannot create GPU context.");
} else if (errorCode == AI_ERROR) {
TF_WARN("[arnold-usd] Generic error.");
}
return Status::Aborted;
}
_paused.store(false, std::memory_order_release);
if (status != AI_RENDER_STATUS_RENDERING) {
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderBegin(_delegate->GetRenderSession());
#else
AiRenderBegin();
#endif
}
return Status::Converging;
}
void HdArnoldRenderParam::Interrupt(bool needsRestart, bool clearStatus)
{
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
const auto status = AiRenderGetStatus(_delegate->GetRenderSession());
#else
const auto status = AiRenderGetStatus();
#endif
if (status != AI_RENDER_STATUS_NOT_STARTED) {
#ifdef ARNOLD_MULTIPLE_RENDER_SESSIONS
AiRenderInterrupt(_delegate->GetRenderSession(), AI_BLOCKING);
#else
AiRenderInterrupt(AI_BLOCKING);
#endif
}
if (needsRestart) {
_needsRestart.store(true, std::memory_order_release);
}
if (clearStatus) {
_aborted.store(false, std::memory_order_release);
}
}
void HdArnoldRenderParam::Pause()
{
Interrupt(false, false);
_paused.store(true, std::memory_order_release);
}
void HdArnoldRenderParam::Resume() { _paused.store(false, std::memory_order_release); }
void HdArnoldRenderParam::Restart()
{
_paused.store(false, std::memory_order_release);
_needsRestart.store(true, std::memory_order_release);
}
bool HdArnoldRenderParam::UpdateShutter(const GfVec2f& shutter)
{
if (!GfIsClose(_shutter[0], shutter[0], AI_EPSILON) || !GfIsClose(_shutter[1], shutter[1], AI_EPSILON)) {
_shutter = shutter;
return true;
}
return false;
}
bool HdArnoldRenderParam::UpdateFPS(const float FPS)
{
if (!GfIsClose(_fps, FPS, AI_EPSILON)) {
_fps = FPS;
return true;
}
return false;
}
PXR_NAMESPACE_CLOSE_SCOPE
| 6,728 | 2,278 |
#include "Transition.h"
#include "GComponent.h"
#include "utils/ToolSet.h"
NS_FGUI_BEGIN
USING_NS_CC;
using namespace std;
const int FRAME_RATE = 24;
const int OPTION_IGNORE_DISPLAY_CONTROLLER = 1;
const int OPTION_AUTO_STOP_DISABLED = 2;
const int OPTION_AUTO_STOP_AT_END = 4;
class TransitionValue
{
public:
float f1;//x, scalex, pivotx,alpha,shakeAmplitude,rotation
float f2;//y, scaley, pivoty, shakePeriod
float f3;
float f4;
int i;//frame
Color4B c;//color
bool b;//playing
string s;//sound,transName
bool b1;
bool b2;
TransitionValue();
TransitionValue(TransitionValue& source);
TransitionValue& operator= (const TransitionValue& other);
};
TransitionValue::TransitionValue() :
f1(0), f2(0), f3(0), f4(0), i(0), b(false), b1(false), b2(false)
{
}
TransitionValue::TransitionValue(TransitionValue& other)
{
*this = other;
}
TransitionValue& TransitionValue::operator= (const TransitionValue& other)
{
f1 = other.f1;
f2 = other.f2;
f3 = other.f3;
f4 = other.f4;
i = other.i;
c = other.c;
b = other.b;
s = other.s;
b1 = other.b1;
b2 = other.b2;
return *this;
}
class TransitionItem
{
public:
float time;
string targetId;
TransitionActionType type;
float duration;
TransitionValue value;
TransitionValue startValue;
TransitionValue endValue;
tweenfunc::TweenType easeType;
int repeat;
bool yoyo;
bool tween;
string label;
string label2;
//hooks
Transition::TransitionHook hook;
Transition::TransitionHook hook2;
//running properties
bool completed;
GObject* target;
bool filterCreated;
uint32_t displayLockToken;
TransitionItem();
};
TransitionItem::TransitionItem() :
time(0),
type(TransitionActionType::XY),
duration(0),
easeType(tweenfunc::TweenType::Quad_EaseOut),
repeat(0),
yoyo(false),
tween(false),
hook(nullptr),
hook2(nullptr),
completed(false),
target(nullptr),
filterCreated(false),
displayLockToken(0)
{
}
Transition::Transition(GComponent* owner, int index) :
autoPlayRepeat(1),
autoPlayDelay(0),
_owner(owner),
_totalTimes(0),
_totalTasks(0),
_playing(false),
_ownerBaseX(0),
_ownerBaseY(0),
_onComplete(nullptr),
_options(0),
_reversed(false),
_maxTime(0),
_autoPlay(false),
_actionTag(ActionTag::TRANSITION_ACTION + index)
{
}
Transition::~Transition()
{
for (auto &item : _items)
delete item;
}
void Transition::setAutoPlay(bool value)
{
if (_autoPlay != value)
{
_autoPlay = value;
if (_autoPlay)
{
if (_owner->onStage())
play(autoPlayRepeat, autoPlayDelay, nullptr);
}
else
{
if (!_owner->onStage())
stop(false, true);
}
}
}
void Transition::play(PlayCompleteCallback callback)
{
play(1, 0, callback);
}
void Transition::play(int times, float delay, PlayCompleteCallback callback)
{
play(times, delay, callback, false);
}
void Transition::playReverse(PlayCompleteCallback callback)
{
playReverse(1, 0, callback);
}
void Transition::playReverse(int times, float delay, PlayCompleteCallback callback)
{
play(times, delay, callback, true);
}
void Transition::changeRepeat(int value)
{
_totalTimes = value;
}
void Transition::play(int times, float delay, PlayCompleteCallback onComplete, bool reverse)
{
stop(true, true);
_totalTimes = times;
_reversed = reverse;
internalPlay(delay);
_playing = _totalTasks > 0;
if (_playing)
{
_onComplete = onComplete;
if ((_options & OPTION_IGNORE_DISPLAY_CONTROLLER) != 0)
{
for (auto &item : _items)
{
if (item->target != nullptr && item->target != _owner)
item->displayLockToken = item->target->addDisplayLock();
}
}
}
else if (onComplete != nullptr)
onComplete();
}
void Transition::stop()
{
stop(true, false);
}
void Transition::stop(bool setToComplete, bool processCallback)
{
if (_playing)
{
_playing = false;
_totalTasks = 0;
_totalTimes = 0;
PlayCompleteCallback func = _onComplete;
_onComplete = nullptr;
_owner->displayObject()->stopAllActionsByTag(_actionTag);
int cnt = (int)_items.size();
if (_reversed)
{
for (int i = cnt - 1; i >= 0; i--)
{
TransitionItem* item = _items[i];
if (item->target == nullptr)
continue;
stopItem(item, setToComplete);
}
}
else
{
for (int i = 0; i < cnt; i++)
{
TransitionItem *item = _items[i];
if (item->target == nullptr)
continue;
stopItem(item, setToComplete);
}
}
if (processCallback && func != nullptr)
func();
}
}
void Transition::stopItem(TransitionItem * item, bool setToComplete)
{
if (item->displayLockToken != 0)
{
item->target->releaseDisplayLock(item->displayLockToken);
item->displayLockToken = 0;
}
//if (item->type == TransitionActionType::ColorFilter && item->filterCreated)
// item->target->setFilter(nullptr);
if (item->completed)
return;
if (item->type == TransitionActionType::Transition)
{
Transition* trans = item->target->as<GComponent>()->getTransition(item->value.s);
if (trans != nullptr)
trans->stop(setToComplete, false);
}
else if (item->type == TransitionActionType::Shake)
{
Director::getInstance()->getScheduler()->unschedule("-", item);
item->target->_gearLocked = true;
item->target->setPosition(item->target->getX() - item->startValue.f1, item->target->getY() - item->startValue.f2);
item->target->_gearLocked = false;
}
else
{
if (setToComplete)
{
if (item->tween)
{
if (!item->yoyo || item->repeat % 2 == 0)
applyValue(item, _reversed ? item->startValue : item->endValue);
else
applyValue(item, _reversed ? item->endValue : item->startValue);
}
else if (item->type != TransitionActionType::Sound)
applyValue(item, item->value);
}
}
}
void Transition::setValue(const std::string & label, const ValueVector& values)
{
for (auto &item : _items)
{
if (item->label == label)
{
if (item->tween)
setValue(item, item->startValue, values);
else
setValue(item, item->value, values);
}
else if (item->label2 == label)
{
setValue(item, item->endValue, values);
}
}
}
void Transition::setValue(TransitionItem* item, TransitionValue& value, const ValueVector& values)
{
switch (item->type)
{
case TransitionActionType::XY:
case TransitionActionType::Size:
case TransitionActionType::Pivot:
case TransitionActionType::Scale:
case TransitionActionType::Skew:
value.b1 = true;
value.b2 = true;
value.f1 = values[0].asFloat();
value.f2 = values[1].asFloat();
break;
case TransitionActionType::Alpha:
value.f1 = values[0].asFloat();
break;
case TransitionActionType::Rotation:
value.f1 = values[0].asFloat();
break;
case TransitionActionType::Color:
{
uint32_t v = values[0].asUnsignedInt();
value.c = Color4B((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF, (v >> 24) & 0xFF);
break;
}
case TransitionActionType::Animation:
value.i = values[0].asInt();
if (values.size() > 1)
value.b = values[1].asBool();
break;
case TransitionActionType::Visible:
value.b = values[0].asBool();
break;
case TransitionActionType::Sound:
value.s = values[0].asString();
if (values.size() > 1)
value.f1 = values[1].asFloat();
break;
case TransitionActionType::Transition:
value.s = values[0].asString();
if (values.size() > 1)
value.i = values[1].asInt();
break;
case TransitionActionType::Shake:
value.f1 = values[0].asFloat();
if (values.size() > 1)
value.f2 = values[1].asFloat();
break;
case TransitionActionType::ColorFilter:
value.f1 = values[1].asFloat();
value.f2 = values[2].asFloat();
value.f3 = values[3].asFloat();
value.f4 = values[4].asFloat();
break;
default:
break;
}
}
void Transition::setHook(const std::string & label, TransitionHook callback)
{
for (auto &item : _items)
{
if (item->label == label)
{
item->hook = callback;
break;
}
else if (item->label2 == label)
{
item->hook2 = callback;
break;
}
}
}
void Transition::clearHooks()
{
for (auto &item : _items)
{
item->hook = nullptr;
item->hook2 = nullptr;
}
}
void Transition::setTarget(const std::string & label, GObject * newTarget)
{
for (auto &item : _items)
{
if (item->label == label)
item->targetId = newTarget->id;
}
}
void Transition::setDuration(const std::string & label, float value)
{
for (auto &item : _items)
{
if (item->tween && item->label == label)
item->duration = value;
}
}
void Transition::updateFromRelations(const std::string & targetId, float dx, float dy)
{
int cnt = (int)_items.size();
if (cnt == 0)
return;
for (int i = 0; i < cnt; i++)
{
TransitionItem* item = _items[i];
if (item->type == TransitionActionType::XY && item->targetId == targetId)
{
if (item->tween)
{
item->startValue.f1 += dx;
item->startValue.f2 += dy;
item->endValue.f1 += dx;
item->endValue.f2 += dy;
}
else
{
item->value.f1 += dx;
item->value.f2 += dy;
}
}
}
}
void Transition::OnOwnerRemovedFromStage()
{
if ((_options & OPTION_AUTO_STOP_DISABLED) == 0)
stop((_options & OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false);
}
void Transition::internalPlay(float delay)
{
_ownerBaseX = _owner->getX();
_ownerBaseY = _owner->getY();
_totalTasks = 0;
for (auto &item : _items)
{
if (!item->targetId.empty())
item->target = _owner->getChildById(item->targetId);
else
item->target = _owner;
if (item->target == nullptr)
continue;
if (item->tween)
{
float startTime = delay;
if (_reversed)
startTime += (_maxTime - item->time - item->duration);
else
startTime += item->time;
if (startTime > 0 && (item->type == TransitionActionType::XY || item->type == TransitionActionType::Size))
{
_totalTasks++;
item->completed = false;
ActionInterval* action = Sequence::createWithTwoActions(DelayTime::create(startTime), CallFunc::create([item, this]
{
_totalTasks--;
startTween(item, 0);
}));
action->setTag(ActionTag::TRANSITION_ACTION);
_owner->displayObject()->runAction(action);
}
else
startTween(item, startTime);
}
else
{
float startTime = delay;
if (_reversed)
startTime += (_maxTime - item->time);
else
startTime += item->time;
if (startTime == 0)
{
applyValue(item, item->value);
if (item->hook)
item->hook();
}
else
{
item->completed = false;
_totalTasks++;
ActionInterval* action = Sequence::createWithTwoActions(DelayTime::create(startTime), CallFunc::create([item, this]
{
item->completed = true;
_totalTasks--;
applyValue(item, item->value);
if (item->hook)
item->hook();
checkAllComplete();
}));
action->setTag(ActionTag::TRANSITION_ACTION);
_owner->displayObject()->runAction(action);
}
}
}
}
void Transition::startTween(TransitionItem * item, float delay)
{
if (_reversed)
startTween(item, delay, item->endValue, item->startValue);
else
startTween(item, delay, item->startValue, item->endValue);
}
void Transition::startTween(TransitionItem * item, float delay, TransitionValue& startValue, TransitionValue& endValue)
{
ActionInterval* mainAction = nullptr;
switch (item->type)
{
case TransitionActionType::XY:
case TransitionActionType::Size:
{
if (item->type == TransitionActionType::XY)
{
if (item->target == _owner)
{
if (!startValue.b1)
startValue.f1 = 0;
if (!startValue.b2)
startValue.f2 = 0;
}
else
{
if (!startValue.b1)
startValue.f1 = item->target->getX();
if (!startValue.b2)
startValue.f2 = item->target->getY();
}
}
else
{
if (!startValue.b1)
startValue.f1 = item->target->getWidth();
if (!startValue.b2)
startValue.f2 = item->target->getHeight();
}
item->value.f1 = startValue.f1;
item->value.f2 = startValue.f2;
if (!endValue.b1)
endValue.f1 = item->value.f1;
if (!endValue.b2)
endValue.f2 = item->value.f2;
item->value.b1 = startValue.b1 || endValue.b1;
item->value.b2 = startValue.b2 || endValue.b2;
mainAction = ActionVec2::create(item->duration,
Vec2(startValue.f1, startValue.f2),
Vec2(endValue.f1, endValue.f2),
[this, item](const Vec2& value)
{
item->value.f1 = value.x;
item->value.f2 = value.y;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::Scale:
case TransitionActionType::Skew:
{
item->value.f1 = startValue.f1;
item->value.f2 = startValue.f2;
mainAction = ActionVec2::create(item->duration,
Vec2(startValue.f1, startValue.f2),
Vec2(endValue.f1, endValue.f2),
[this, item](const Vec2& value)
{
item->value.f1 = value.x;
item->value.f2 = value.y;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::Alpha:
case TransitionActionType::Rotation:
{
item->value.f1 = startValue.f1;
mainAction = ActionFloat::create(item->duration,
startValue.f1,
endValue.f1,
[this, item](float value)
{
item->value.f1 = value;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::Color:
{
item->value.c = startValue.c;
mainAction = ActionVec4::create(item->duration,
Vec4(item->value.c.r, item->value.c.g, item->value.c.b, item->value.c.a),
Vec4(endValue.c.r, endValue.c.g, endValue.c.b, endValue.c.a),
[this, item](const Vec4& value)
{
item->value.c.r = value.x;
item->value.c.g = value.y;
item->value.c.b = value.z;
item->value.c.a = value.w;
applyValue(item, item->value);
});
break;
}
case TransitionActionType::ColorFilter:
{
item->value.f1 = startValue.f1;
item->value.f2 = startValue.f2;
item->value.f3 = startValue.f3;
item->value.f4 = startValue.f4;
mainAction = ActionVec4::create(item->duration,
Vec4(startValue.f1, startValue.f2, startValue.f3, startValue.f4),
Vec4(endValue.f1, endValue.f2, endValue.f3, endValue.f4),
[this, item](const Vec4& value)
{
item->value.f1 = value.x;
item->value.f2 = value.y;
item->value.f3 = value.z;
item->value.f4 = value.w;
applyValue(item, item->value);
});
break;
}
default:
break;
}
mainAction = createEaseAction(item->easeType, mainAction);
if (item->repeat != 0)
mainAction = RepeatYoyo::create(mainAction, item->repeat == -1 ? INT_MAX : (item->repeat + 1), item->yoyo);
FiniteTimeAction* completeAction = CallFunc::create([this, item]() { tweenComplete(item); });
if (delay > 0)
{
FiniteTimeAction* delayAction = DelayTime::create(delay);
if (item->hook)
mainAction = Sequence::create({ delayAction, CallFunc::create(item->hook), mainAction, completeAction });
else
mainAction = Sequence::create({ delayAction, mainAction, completeAction });
}
else
{
applyValue(item, item->value);
if (item->hook)
item->hook();
mainAction = Sequence::createWithTwoActions(mainAction, completeAction);
}
mainAction->setTag(ActionTag::TRANSITION_ACTION);
_owner->displayObject()->runAction(mainAction);
_totalTasks++;
item->completed = false;
}
void Transition::tweenComplete(TransitionItem * item)
{
item->completed = true;
_totalTasks--;
if (item->hook2)
item->hook2();
checkAllComplete();
}
void Transition::checkAllComplete()
{
if (_playing && _totalTasks == 0)
{
if (_totalTimes < 0)
{
internalPlay(0);
}
else
{
_totalTimes--;
if (_totalTimes > 0)
internalPlay(0);
else
{
_playing = false;
for (auto &item : _items)
{
if (item->target != nullptr)
{
if (item->displayLockToken != 0)
{
item->target->releaseDisplayLock(item->displayLockToken);
item->displayLockToken = 0;
}
/*if (item->filterCreated)
{
item->filterCreated = false;
item->target->setFilter(nullptr);
}*/
}
}
if (_onComplete)
{
PlayCompleteCallback func = _onComplete;
_onComplete = nullptr;
func();
}
}
}
}
}
void Transition::applyValue(TransitionItem * item, TransitionValue & value)
{
item->target->_gearLocked = true;
switch (item->type)
{
case TransitionActionType::XY:
if (item->target == _owner)
{
float f1, f2;
if (!value.b1)
f1 = item->target->getX();
else
f1 = value.f1 + _ownerBaseX;
if (!value.b2)
f2 = item->target->getY();
else
f2 = value.f2 + _ownerBaseY;
item->target->setPosition(f1, f2);
}
else
{
if (!value.b1)
value.f1 = item->target->getX();
if (!value.b2)
value.f2 = item->target->getY();
item->target->setPosition(value.f1, value.f2);
}
break;
case TransitionActionType::Size:
if (!value.b1)
value.f1 = item->target->getWidth();
if (!value.b2)
value.f2 = item->target->getHeight();
item->target->setSize(value.f1, value.f2);
break;
case TransitionActionType::Pivot:
item->target->setPivot(value.f1, value.f2);
break;
case TransitionActionType::Alpha:
item->target->setAlpha(value.f1);
break;
case TransitionActionType::Rotation:
item->target->setRotation(value.f1);
break;
case TransitionActionType::Scale:
item->target->setScale(value.f1, value.f2);
break;
case TransitionActionType::Skew:
item->target->setSkewX(value.f1);
item->target->setSkewY(value.f2);
break;
case TransitionActionType::Color:
{
IColorGear* cg = dynamic_cast<IColorGear*>(item->target);
if (cg)
cg->cg_setColor(value.c);
break;
}
case TransitionActionType::Animation:
{
IAnimationGear* ag = dynamic_cast<IAnimationGear*>(item->target);
if (ag)
{
if (!value.b1)
value.i = ag->getCurrentFrame();
ag->setCurrentFrame(value.i);
ag->setPlaying(value.b);
}
break;
}
case TransitionActionType::Visible:
item->target->setVisible(value.b);
break;
case TransitionActionType::Transition:
{
Transition* trans = item->target->as<GComponent>()->getTransition(value.s);
if (trans != nullptr)
{
if (value.i == 0)
trans->stop(false, true);
else if (trans->isPlaying())
trans->_totalTimes = value.i;
else
{
item->completed = false;
_totalTasks++;
if (_reversed)
trans->playReverse(value.i, 0, [this, item]() { playTransComplete(item); });
else
trans->play(value.i, 0, [this, item]() { playTransComplete(item); });
}
}
break;
}
case TransitionActionType::Sound:
{
UIRoot->playSound(value.s, value.f1);
break;
}
case TransitionActionType::Shake:
item->startValue.f1 = 0; //offsetX
item->startValue.f2 = 0; //offsetY
item->startValue.f3 = item->value.f2;//shakePeriod
Director::getInstance()->getScheduler()->schedule(CC_CALLBACK_1(Transition::shakeItem, this, item), item, 0, false, "-");
_totalTasks++;
item->completed = false;
break;
case TransitionActionType::ColorFilter:
break;
default:
break;
}
item->target->_gearLocked = false;
}
void Transition::playTransComplete(TransitionItem* item)
{
_totalTasks--;
item->completed = true;
checkAllComplete();
}
void Transition::shakeItem(float dt, TransitionItem * item)
{
float r = ceil(item->value.f1 * item->startValue.f3 / item->value.f2);
float x1 = (1 - rand_0_1() * 2)*r;
float y1 = (1 - rand_0_1() * 2)*r;
x1 = x1 > 0 ? ceil(x1) : floor(x1);
y1 = y1 > 0 ? ceil(y1) : floor(y1);
item->target->_gearLocked = true;
item->target->setPosition(item->target->getX() - item->startValue.f1 + x1, item->target->getY() - item->startValue.f2 + y1);
item->target->_gearLocked = false;
item->startValue.f1 = x1;
item->startValue.f2 = y1;
item->startValue.f3 -= dt;
if (item->startValue.f3 <= 0)
{
item->target->_gearLocked = true;
item->target->setPosition(item->target->getX() - item->startValue.f1, item->target->getY() - item->startValue.f2);
item->target->_gearLocked = false;
item->completed = true;
_totalTasks--;
Director::getInstance()->getScheduler()->unschedule("-", item);
checkAllComplete();
}
}
void Transition::decodeValue(TransitionActionType type, const char* pValue, TransitionValue & value)
{
string str;
if (pValue)
str = pValue;
switch (type)
{
case TransitionActionType::XY:
case TransitionActionType::Size:
case TransitionActionType::Pivot:
case TransitionActionType::Skew:
{
string s1, s2;
ToolSet::splitString(str, ',', s1, s2);
if (s1 == "-")
{
value.b1 = false;
}
else
{
value.f1 = atof(s1.c_str());
value.b1 = true;
}
if (s2 == "-")
{
value.b2 = false;
}
else
{
value.f2 = atof(s2.c_str());
value.b2 = true;
}
break;
}
case TransitionActionType::Alpha:
value.f1 = atof(str.c_str());
break;
case TransitionActionType::Rotation:
value.f1 = atof(str.c_str());
break;
case TransitionActionType::Scale:
{
Vec2 v2;
ToolSet::splitString(str, ',', v2);
value.f1 = v2.x;
value.f2 = v2.y;
break;
}
case TransitionActionType::Color:
value.c = ToolSet::convertFromHtmlColor(str.c_str());
break;
case TransitionActionType::Animation:
{
string s1, s2;
ToolSet::splitString(str, ',', s1, s2);
if (s1 == "-")
{
value.b1 = false;
}
else
{
value.i = atoi(s1.c_str());
value.b1 = true;
}
value.b = s2 == "p";
break;
}
case TransitionActionType::Visible:
value.b = str == "true";
break;
case TransitionActionType::Sound:
{
string s;
ToolSet::splitString(str, ',', value.s, s);
if (!s.empty())
{
int intv = atoi(s.c_str());
if (intv == 100 || intv == 0)
value.f1 = 1;
else
value.f1 = (float)intv / 100;
}
else
value.f1 = 1;
break;
}
case TransitionActionType::Transition:
{
string s;
ToolSet::splitString(str, ',', value.s, s);
if (!s.empty())
value.i = atoi(s.c_str());
else
value.i = 1;
break;
}
case TransitionActionType::Shake:
{
Vec2 v2;
ToolSet::splitString(str, ',', v2);
value.f1 = v2.x;
value.f2 = v2.y;
break;
}
case TransitionActionType::ColorFilter:
{
Vec4 v4;
ToolSet::splitString(str, ',', v4);
value.f1 = v4.x;
value.f2 = v4.y;
value.f3 = v4.z;
value.f4 = v4.w;
break;
}
default:
break;
}
}
void Transition::setup(TXMLElement * xml)
{
const char* p;
name = xml->Attribute("name");
p = xml->Attribute("options");
if (p)
_options = atoi(p);
_autoPlay = xml->BoolAttribute("autoPlay");
if (_autoPlay)
{
p = xml->Attribute("autoPlayRepeat");
if (p)
autoPlayRepeat = atoi(p);
autoPlayDelay = xml->FloatAttribute("autoPlayDelay");
}
TXMLElement* cxml = xml->FirstChildElement("item");
while (cxml)
{
TransitionItem* item = new TransitionItem();
_items.push_back(item);
item->time = (float)cxml->IntAttribute("time") / (float)FRAME_RATE;
p = cxml->Attribute("target");
if (p)
item->targetId = p;
p = cxml->Attribute("type");
if (p)
item->type = ToolSet::parseTransitionActionType(p);
item->tween = cxml->BoolAttribute("tween");
p = cxml->Attribute("label");
if (p)
item->label = p;
if (item->tween)
{
item->duration = (float)cxml->IntAttribute("duration") / FRAME_RATE;
if (item->time + item->duration > _maxTime)
_maxTime = item->time + item->duration;
p = cxml->Attribute("ease");
if (p)
item->easeType = ToolSet::parseEaseType(p);
item->repeat = cxml->IntAttribute("repeat");
item->yoyo = cxml->BoolAttribute("yoyo");
p = cxml->Attribute("label2");
if (p)
item->label2 = p;
p = cxml->Attribute("endValue");
if (p)
{
decodeValue(item->type, cxml->Attribute("startValue"), item->startValue);
decodeValue(item->type, p, item->endValue);
}
else
{
item->tween = false;
decodeValue(item->type, cxml->Attribute("startValue"), item->value);
}
}
else
{
if (item->time > _maxTime)
_maxTime = item->time;
decodeValue(item->type, cxml->Attribute("value"), item->value);
}
cxml = cxml->NextSiblingElement("item");
}
}
NS_FGUI_END
| 30,398 | 9,488 |
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getsol(string s, string t, int n, int m, vector<vector<int>> &v){
if(n==0)
return m;
if(m==0)
return n;
if(v[n][m] > -1)
return v[n][m];
if(s[n-1] == t[m-1])
return getsol(s, t, n-1, m-1, v);
v[n][m] = 1 + min(getsol(s, t, n, m-1, v), min(getsol(s, t, n-1, m, v), getsol(s, t, n-1, m-1, v)));
return v[n][m];
}
int editDistance(string s, string t) {
int n = s.size();
int m = t.size();
vector<vector<int>> v(n+1, vector<int>(m+1, -1));
int sol = getsol(s, t, n, m, v);
return sol;
}
};
int main() {
int T;
cin >> T;
while (T--) {
string s, t;
cin >> s >> t;
Solution ob;
int ans = ob.editDistance(s, t);
cout << ans << "\n";
}
return 0;
}
| 941 | 384 |
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
//! \author Luke Kersting
//! \brief The electron screened Rutherford elastic scattering distribution definition
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.hpp"
#include "MonteCarlo_KinematicHelpers.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_SearchAlgorithms.hpp"
#include "Utility_3DCartesianVectorHelpers.hpp"
#include "Utility_PhysicalConstants.hpp"
namespace MonteCarlo{
// Constructor
ScreenedRutherfordElasticElectronScatteringDistribution::ScreenedRutherfordElasticElectronScatteringDistribution(
const int atomic_number,
const bool seltzer_modification_on )
{
d_elastic_traits.reset( new ElasticTraits( atomic_number,
seltzer_modification_on ) );
}
// Evaluate the distribution at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluate(
const double incoming_energy,
const double scattering_angle_cosine ) const
{
// Make sure the energy and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
return this->evaluatePDF( incoming_energy, scattering_angle_cosine );
}
// Evaluate the distribution at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluate(
const double incoming_energy,
const double scattering_angle_cosine,
const double eta ) const
{
// Make sure the energy, eta and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
testPrecondition( eta > 0.0 );
return this->evaluatePDF( incoming_energy, scattering_angle_cosine, eta );
}
// Evaluate the PDF at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluatePDF(
const double incoming_energy,
const double scattering_angle_cosine ) const
{
// Make sure the energy, eta and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy );
return this->evaluatePDF( incoming_energy, scattering_angle_cosine, eta );
}
// Evaluate the PDF at the given energy and scattering angle cosine
/*! \details The returned value is not normalized to the elastic cutoff
* distribution. The correct normalized value can be calculated by multiplying
* the the returned value by the pdf of the cutoff distribution at mu peak.
* When the scattering angle cosine is very close to one, precision will be lost.
*/
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluatePDF(
const double incoming_energy,
const double scattering_angle_cosine,
const double eta ) const
{
// Make sure the energy, eta and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
testPrecondition( eta > 0.0 );
double delta_mu = 1.0L - scattering_angle_cosine;
return ( ElasticTraits::delta_mu_peak + eta )*( ElasticTraits::delta_mu_peak + eta )/(
( delta_mu + eta )*( delta_mu + eta ) );
}
// Evaluate the CDF
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluateCDF(
const double incoming_energy,
const double scattering_angle_cosine ) const
{
// Make sure the energy and angle are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy );
return this->evaluateCDF( incoming_energy, scattering_angle_cosine, eta );
}
// Evaluate the CDF
double ScreenedRutherfordElasticElectronScatteringDistribution::evaluateCDF(
const double incoming_energy,
const double scattering_angle_cosine,
const double eta ) const
{
// Make sure the energy, eta and angle cosine are valid
testPrecondition( incoming_energy > 0.0 );
testPrecondition( scattering_angle_cosine >= ElasticTraits::mu_peak );
testPrecondition( scattering_angle_cosine <= 1.0 );
testPrecondition( eta > 0.0 );
double delta_mu = 1.0L - scattering_angle_cosine;
return ( ElasticTraits::delta_mu_peak + eta )/( delta_mu + eta )*
( delta_mu/ElasticTraits::delta_mu_peak );
}
// Sample an outgoing energy and direction from the distribution
void ScreenedRutherfordElasticElectronScatteringDistribution::sample(
const double incoming_energy,
double& outgoing_energy,
double& scattering_angle_cosine ) const
{
// The outgoing energy is always equal to the incoming energy
outgoing_energy = incoming_energy;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( incoming_energy,
scattering_angle_cosine,
trial_dummy );
}
// Sample an outgoing energy and direction and record the number of trials
void ScreenedRutherfordElasticElectronScatteringDistribution::sampleAndRecordTrials(
const double incoming_energy,
double& outgoing_energy,
double& scattering_angle_cosine,
Counter& trials ) const
{
// The outgoing energy is always equal to the incoming energy
outgoing_energy = incoming_energy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( incoming_energy,
scattering_angle_cosine,
trials );
}
// Randomly scatter the electron
void ScreenedRutherfordElasticElectronScatteringDistribution::scatterElectron(
ElectronState& electron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const
{
double scattering_angle_cosine;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( electron.getEnergy(),
scattering_angle_cosine,
trial_dummy );
shell_of_interaction =Data::UNKNOWN_SUBSHELL;
// Set the new direction
electron.rotateDirection( scattering_angle_cosine,
this->sampleAzimuthalAngle() );
}
// Randomly scatter the positron
void ScreenedRutherfordElasticElectronScatteringDistribution::scatterPositron(
PositronState& positron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const
{
double scattering_angle_cosine;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( positron.getEnergy(),
scattering_angle_cosine,
trial_dummy );
shell_of_interaction =Data::UNKNOWN_SUBSHELL;
// Set the new direction
positron.rotateDirection( scattering_angle_cosine,
this->sampleAzimuthalAngle() );
}
// Randomly scatter the adjoint electron
void ScreenedRutherfordElasticElectronScatteringDistribution::scatterAdjointElectron(
AdjointElectronState& adjoint_electron,
ParticleBank& bank,
Data::SubshellType& shell_of_interaction ) const
{
double scattering_angle_cosine;
Counter trial_dummy;
// Sample an outgoing direction
this->sampleAndRecordTrialsImpl( adjoint_electron.getEnergy(),
scattering_angle_cosine,
trial_dummy );
shell_of_interaction = Data::UNKNOWN_SUBSHELL;
// Set the new direction
adjoint_electron.rotateDirection( scattering_angle_cosine,
this->sampleAzimuthalAngle() );
}
// Sample an outgoing direction from the distribution
/* \details The CDF is inverted to create the sampling routine.
* mu = ( eta mu_p + ( 1 + eta )( 1 - mu_p )CDF )/
* ( eta + ( 1 - mu_p )CDF )
*/
void ScreenedRutherfordElasticElectronScatteringDistribution::sampleAndRecordTrialsImpl(
const double incoming_energy,
double& scattering_angle_cosine,
Counter& trials ) const
{
// Make sure the incoming energy is valid
testPrecondition( incoming_energy > 0.0 );
// Increment the number of trials
++trials;
double random_number =
Utility::RandomNumberGenerator::getRandomNumber<double>();
double eta = d_elastic_traits->evaluateMoliereScreeningConstant( incoming_energy );
scattering_angle_cosine =
( ElasticTraits::mu_peak * eta +
( 1.0L + eta ) * ElasticTraits::delta_mu_peak * random_number )/
( eta + ElasticTraits::delta_mu_peak * random_number );
// Make sure the scattering angle cosine is valid
testPostcondition( scattering_angle_cosine >= ElasticTraits::mu_peak - 1e-15 );
testPostcondition( scattering_angle_cosine <= 1.0+1e-15 );
// There will sometimes be roundoff error in which case the scattering angle
// cosine should never be greater than 1
scattering_angle_cosine = std::min( scattering_angle_cosine, 1.0 );
}
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// end MonteCarlo_ScreenedRutherfordElasticElectronScatteringDistribution.cpp
//---------------------------------------------------------------------------//
| 11,248 | 3,204 |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* pre = new ListNode(0);
pre->next = head;
ListNode* cur = pre;
int L = 0;
while (cur){
L += 1;
cur = cur->next;
}
cur = pre;
int i = 0;
while (i < L-n-1){
cur = cur->next;
i += 1;
}
cur->next = cur->next->next;
return pre->next;
}
};
| 631 | 215 |
#include<iostream>
int BoxVolume(int lenght, int width, int heght) {
return lenght * width * heght;
}
int BoxVolume(int lenght, int width) {
return lenght * width;
}
int BoxVolume(int lenght) {
return lenght;
}
int main(void) {
std::cout << "[3, 3, 3] : " << BoxVolume(3, 3, 3) << std::endl;
std::cout << "[5, 5, D] : " << BoxVolume(5, 5) << std::endl;
std::cout << "[7, D, D] : " << BoxVolume(7) << std::endl;
return 0;
} | 431 | 186 |
#include "ifc3_parser.h"
#include "constants.h"
#include "eigen.h"
#include "mpiHelper.h"
#include <fstream>// it may be used
#include <iostream>
#include <set>
#ifdef HDF5_AVAIL
#include <highfive/H5Easy.hpp>
#endif
// decide which ifc3 parser to use
Interaction3Ph IFC3Parser::parse(Context &context, Crystal &crystal) {
// check if this is a phonopy file is set in input
if (context.getPhFC3FileName().find("hdf5") != std::string::npos) {
if(context.getPhonopyDispFileName().empty()) {
Error("You need both fc3.hdf5 and phonopy_disp.yaml "
"files to run phono3py." );
} else {
if (mpi->mpiHead()) {
std::cout << "Using anharmonic force constants from phono3py."
<< std::endl;
}
}
return parseFromPhono3py(context, crystal);
} else {
if (mpi->mpiHead()) {
std::cout << "Using anharmonic force constants from ShengBTE."
<< std::endl;
}
return parseFromShengBTE(context, crystal);
}
}
/* this function is used by phono3py parser, and
* constructs a list of vectors which are in the first WS
* superCell of the phonon superCell */
Eigen::MatrixXd IFC3Parser::wsInit(Crystal &crystal,
Eigen::Vector3i qCoarseGrid) {
const int nx = 2;
int index = 0;
const int nrwsx = 200;
Eigen::MatrixXd directUnitCell = crystal.getDirectUnitCell();
Eigen::MatrixXd unitCell(3, 3);
unitCell.col(0) = directUnitCell.col(0) * qCoarseGrid(0);
unitCell.col(1) = directUnitCell.col(1) * qCoarseGrid(1);
unitCell.col(2) = directUnitCell.col(2) * qCoarseGrid(2);
Eigen::MatrixXd tmpResult(3, nrwsx);
for (int ir = -nx; ir <= nx; ir++) {
for (int jr = -nx; jr <= nx; jr++) {
for (int kr = -nx; kr <= nx; kr++) {
for (int i : {0, 1, 2}) {
tmpResult(i, index) =
unitCell(i, 0) * ir + unitCell(i, 1) * jr + unitCell(i, 2) * kr;
}
if (tmpResult.col(index).squaredNorm() > 1.0e-6) {
index += 1;
}
if (index > nrwsx) {
Error("WSInit > nrwsx");
}
}
}
}
int nrws = index;
Eigen::MatrixXd rws(3, nrws);
for (int i = 0; i < nrws; i++) {
rws.col(i) = tmpResult.col(i);
}
return rws;
}
/* given the list of all vectors in the WS superCell (rws),
* determine the weight of a particular vector, r */
double wsWeight(const Eigen::VectorXd &r, const Eigen::MatrixXd &rws) {
int nreq = 1;
for (int ir = 0; ir < rws.cols(); ir++) {
double rrt = r.dot(rws.col(ir));
double ck = rrt - rws.col(ir).squaredNorm() / 2.;
if (ck > 1.0e-6) {
return 0.;
}
if (abs(ck) < 1.0e-6) {
nreq += 1;
}
}
double x = 1. / (double) nreq;
return x;
}
/* find the index of a particular vector in cellPositions */
int findIndexRow(Eigen::MatrixXd &cellPositions, Eigen::Vector3d &position) {
int ir2 = -1;
for (int i = 0; i < cellPositions.cols(); i++) {
if ((position - cellPositions.col(i)).norm() < 1.e-12) {
ir2 = i;
return ir2;
}
}
if (ir2 == -1) {
Error("index not found");
}
return ir2;
}
std::tuple<Eigen::MatrixXd, Eigen::Tensor<double, 3>, Eigen::MatrixXd, Eigen::Tensor<double, 3>>
reorderDynamicalMatrix(
Crystal &crystal, const Eigen::Vector3i &qCoarseGrid, const Eigen::MatrixXd &rws,
Eigen::Tensor<double, 5> &mat3R, Eigen::MatrixXd &cellPositions,
const std::vector<
std::vector<std::vector<std::vector<std::vector<std::vector<double>>>>>>
&ifc3Tensor,
const std::vector<int> &cellMap) {
int numAtoms = crystal.getNumAtoms();
Eigen::MatrixXd atomicPositions = crystal.getAtomicPositions();
int nr1Big = qCoarseGrid(0) * 2;
int nr2Big = qCoarseGrid(1) * 2;
int nr3Big = qCoarseGrid(2) * 2;
Eigen::MatrixXd directUnitCell = crystal.getDirectUnitCell();
// Count the number of bravais vectors we need to loop over
int numBravaisVectors = 0;
// Record how many BV with non-zero weight
// belong to each atom, so that we can index iR3
// properly later in the code
Eigen::VectorXi startBVForAtom(numAtoms);
int numBVThisAtom = 0;
std::set<std::vector<double>> setBravaisVectors;
for (int na = 0; na < numAtoms; na++) {
startBVForAtom(na) = numBVThisAtom;
for (int nb = 0; nb < numAtoms; nb++) {
// loop over all possible indices for the first vector
for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) {
for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) {
for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) {
// calculate the R2 vector for atom nb
Eigen::Vector3d r2;
std::vector<double> R2(3);
for (int i : {0, 1, 2}) {
R2[i] = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2);
r2(i) = R2[i] - atomicPositions(na, i) + atomicPositions(nb, i);
}
double weightR2 = wsWeight(r2, rws);
// count this vector if it contributes
if (weightR2 > 0) {
numBravaisVectors += 1;
numBVThisAtom += 1;
setBravaisVectors.insert(R2);
}
}
}
}
}
}
int numR = setBravaisVectors.size();
std::vector<Eigen::Vector3d> listBravaisVectors;
for (auto x : setBravaisVectors) {
Eigen::Vector3d R2;
for (int i : {0, 1, 2}) {
R2(i) = x[i];
}
listBravaisVectors.push_back(R2);
}
Eigen::MatrixXd bravaisVectors(3, numR);
Eigen::Tensor<double, 3> weights(numR, numAtoms, numAtoms);
bravaisVectors.setZero();
weights.setConstant(0.);
for (int na = 0; na < numAtoms; na++) {
for (int nb = 0; nb < numAtoms; nb++) {
// loop over all possible indices for the first vector
for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) {
for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) {
for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) {
// calculate the R2 vector for atom nb
Eigen::Vector3d r2, R2;
for (int i : {0, 1, 2}) {
R2(i) = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2);
r2(i) = R2(i) - atomicPositions(na, i) + atomicPositions(nb, i);
}
double weightR2 = wsWeight(r2, rws);
// count this vector if it contributes
if (weightR2 > 0) {
int ir;
{
auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), R2);
if (it == listBravaisVectors.end()) Error("phono3py parser index not found");
ir = it - listBravaisVectors.begin();
}
for (int i : {0, 1, 2}) {
bravaisVectors(i, ir) = R2(i);
}
weights(ir, na, nb) = weightR2;
}
}
}
}
}
}
//---------
// next, we reorder the dynamical matrix along the bravais lattice vectors
// similarly to what was done in the harmonic class.
mat3R.resize(3 * numAtoms, 3 * numAtoms, 3 * numAtoms, numR, numR);
mat3R.setZero();
double conversion = pow(distanceBohrToAng, 3) / energyRyToEv;
// Note: it may be possible to make these loops faster.
// It is likely possible to avoid using findIndexRow,
// and there could be a faster order of loops.
// loop over all possible indices for the first vector
for (int nr3 = -nr3Big; nr3 < nr3Big; nr3++) {
for (int nr2 = -nr2Big; nr2 < nr2Big; nr2++) {
for (int nr1 = -nr1Big; nr1 < nr1Big; nr1++) {
Eigen::Vector3d r2;
for (int i : {0, 1, 2}) {
r2(i) = nr1 * directUnitCell(i, 0) + nr2 * directUnitCell(i, 1) + nr3 * directUnitCell(i, 2);
}
int iR2;
{
auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), r2);
if (it == listBravaisVectors.end()) continue;
iR2 = it - listBravaisVectors.begin();
}
// calculate the positive quadrant equivalents
int m1 = mod((nr1 + 1), qCoarseGrid(0));
if (m1 <= 0) {
m1 += qCoarseGrid(0);
}
int m2 = mod((nr2 + 1), qCoarseGrid(1));
if (m2 <= 0) {
m2 += qCoarseGrid(1);
}
int m3 = mod((nr3 + 1), qCoarseGrid(2));
if (m3 <= 0) {
m3 += qCoarseGrid(2);
}
m1 += -1;
m2 += -1;
m3 += -1;
// build the unit cell equivalent vectors to look up
Eigen::Vector3d rp2;
for (int i : {0, 1, 2}) {
rp2(i) = m1 * directUnitCell(i, 0) + m2 * directUnitCell(i, 1) + m3 * directUnitCell(i, 2);
}
// look up the index of the original atom
auto ir2 = findIndexRow(cellPositions, rp2);
// loop over all possible indices for the R3 vector
for (int mr3 = -nr3Big; mr3 < nr3Big; mr3++) {
for (int mr2 = -nr2Big; mr2 < nr2Big; mr2++) {
for (int mr1 = -nr1Big; mr1 < nr1Big; mr1++) {
// calculate the R3 vector for atom nc
Eigen::Vector3d r3;
for (int i : {0, 1, 2}) {
r3(i) = mr1 * directUnitCell(i, 0) + mr2 * directUnitCell(i, 1) + mr3 * directUnitCell(i, 2);
}
int iR3;
{
auto it = std::find(listBravaisVectors.begin(), listBravaisVectors.end(), r3);
if (it == listBravaisVectors.end()) continue;
iR3 = it - listBravaisVectors.begin();
}
// calculate the positive quadrant equivalents
int p1 = mod((mr1 + 1), qCoarseGrid(0));
if (p1 <= 0) {
p1 += qCoarseGrid(0);
}
int p2 = mod((mr2 + 1), qCoarseGrid(1));
if (p2 <= 0) {
p2 += qCoarseGrid(1);
}
int p3 = mod((mr3 + 1), qCoarseGrid(2));
if (p3 <= 0) {
p3 += qCoarseGrid(2);
}
p1 += -1;
p2 += -1;
p3 += -1;
// build the unit cell equivalent vectors to look up
Eigen::Vector3d rp3;
for (int i : {0, 1, 2}) {
rp3(i) = p1 * directUnitCell(i, 0) + p2 * directUnitCell(i, 1) + p3 * directUnitCell(i, 2);
}
// look up the index of the original atom
auto ir3 = findIndexRow(cellPositions, rp3);
// loop over the atoms involved in the first vector
for (int na = 0; na < numAtoms; na++) {
for (int nb = 0; nb < numAtoms; nb++) {
// calculate the R2 vector for atom nb
Eigen::Vector3d ra2;
for (int i : {0, 1, 2}) {
ra2(i) = r2(i) - atomicPositions(na, i) + atomicPositions(nb, i);
}
// skip vectors which do not contribute
double weightR2 = wsWeight(ra2, rws);
if (weightR2 == 0) continue;
// loop over atoms involved in R3 vector
for (int nc = 0; nc < numAtoms; nc++) {
// calculate the R3 vector for atom nc
Eigen::Vector3d ra3;
for (int i : {0, 1, 2}) {
ra3(i) = r3(i) - atomicPositions(na, i) + atomicPositions(nc, i);
}
// continue only if this vector matters
double weightR3 = wsWeight(ra3, rws);
if (weightR3 == 0) continue;
// index back to superCell positions
int sat2 = cellMap[nb] + ir2;
int sat3 = cellMap[nc] + ir3;
// loop over the cartesian directions
for (int i : {0, 1, 2}) {
for (int j : {0, 1, 2}) {
for (int k : {0, 1, 2}) {
// compress the cartesian indices and unit cell atom
// indices for the first three indices of FC3
auto ind1 = compress2Indices(na, i, numAtoms, 3);
auto ind2 = compress2Indices(nb, j, numAtoms, 3);
auto ind3 = compress2Indices(nc, k, numAtoms, 3);
if ( mat3R(ind1, ind2, ind3, iR3, iR2) != 0 ) {
// this doesn't happen, so I am picking each element only once
std::cout << "already visited\n";
std::cout << ind1 << " " << ind2 << " " << ind3 << " "
<< iR3 << " " << iR2 << "\n";
}
mat3R(ind1, ind2, ind3, iR3, iR2) +=
ifc3Tensor[cellMap[na]][sat2][sat3][i][j][k] * conversion;
// ifc3Tensor[cellMap[na]][sat2][sat3][i][j][k] * conversion;
}// close cartesian loops
}
}
}// r3 loops
}
}
}// close nc loop
} // close R2 loops
}
}
}// close nb loop
} // close na loop
return std::make_tuple(bravaisVectors, weights, bravaisVectors, weights);
}
Interaction3Ph IFC3Parser::parseFromPhono3py(Context &context,
Crystal &crystal) {
#ifndef HDF5_AVAIL
Error(
"Phono3py HDF5 output cannot be read if Phoebe is not built with HDF5.");
// return void;
#else
// Notes about p3py's fc3.hdf5 file:
// 3rd order fcs are listed as (num_atom, num_atom, num_atom, 3, 3, 3)
// stored in eV/Angstrom3
// Look here for additional details
// https://phonopy.github.io/phono3py/output-files.html#fc3-hdf5
// the information we need outside the ifcs3 is in a file called
// disp_fc3.yaml, which contains the atomic positions of the
// superCell and the displacements of the atoms
// The mapping between the superCell and unit cell atoms is
// set up so that the first nAtoms*dimSup of the superCell are unit cell
// atom #1, and the second nAtoms*dimSup are atom #2, and so on.
// First, get num atoms from the crystal
int numAtoms = crystal.getNumAtoms();
// Open disp_fc3 file, read superCell positions, nSupAtoms
// ==========================================================
auto fileName = context.getPhonopyDispFileName();
std::ifstream infile(fileName);
std::string line;
if (fileName.empty()) {
Error("Phono3py required file phonopyDispFileName "
"(phono3py_disp.yaml) not specified in input file.");
}
if (not infile.is_open()) {
Error("Phono3py required file phonopyDispFileName "
"phono3py_disp.yaml) file not found at "
+ fileName);
}
if (mpi->mpiHead())
std::cout << "Reading in " + fileName + "." << std::endl;
// read in the dimension information.
Eigen::Vector3i qCoarseGrid;
while (infile) {
std::getline(infile, line);
if (line.find("dim:") != std::string::npos) {
std::vector<std::string> tok = tokenize(line);
//std::istringstream iss(temp);
//iss >> qCoarseGrid(0) >> qCoarseGrid(1) >> qCoarseGrid(2);
qCoarseGrid(0) = std::stoi(tok[1]);
qCoarseGrid(1) = std::stoi(tok[2]);
qCoarseGrid(2) = std::stoi(tok[3]);
break;
}
}
// First, we open the phonopyDispFileName to check the distance units.
// Phono3py uses Bohr for QE calculations and Angstrom for VASP
// so, here we decide which is the correct unit,
// by parsing the phono3py_disp.yaml file
double distanceConversion = 1. / distanceBohrToAng;
while (infile) {
std::getline(infile, line);
if (line.find("length") != std::string::npos) {
if (line.find("au") != std::string::npos) {
distanceConversion = 1.; // distances already in Bohr
}
break;
}
}
// read the rest of the file to look for superCell positions
std::vector<std::vector<double>> supPositionsVec;
Eigen::MatrixXd lattice(3, 3);
int ilatt = 3;
bool readSupercell = false;
while (infile) {
getline(infile, line);
// we dont want to read the positions after phonon_supercell_matrix,
// so we break here
if(line.find("phonon_supercell_matrix") != std::string::npos) {
break;
}
// read all the lines after we see the flag for the supercell
// no matter what, the ifc3 info will always come after "supercell:"
// and supercell comes before phonon_supercell in the output file
if (line.find("supercell:") != std::string::npos) {
readSupercell = true;
}
// if this is a cell position, save it
if (line.find("coordinates: ") != std::string::npos && readSupercell) {
std::vector<double> position = {0.,0.,0.};
std::vector<std::string> tok = tokenize(line);
position[0] = std::stod(tok[2]);
position[1] = std::stod(tok[3]);
position[2] = std::stod(tok[4]);
supPositionsVec.push_back(position);
}
if (ilatt < 3 && readSupercell) { // count down lattice lines
// convert from angstrom to bohr
std::vector<std::string> tok = tokenize(line);
lattice(ilatt, 0) = std::stod(tok[2]);
lattice(ilatt, 1) = std::stod(tok[3]);
lattice(ilatt, 2) = std::stod(tok[4]);
ilatt++;
}
if (line.find("lattice:") != std::string::npos && readSupercell) {
ilatt = 0;
}
}
infile.close();
infile.clear();
// number of atoms in the supercell for later use
int numSupAtoms = supPositionsVec.size();
int nr = numSupAtoms / numAtoms;
// check that this matches the ifc2 atoms
int numAtomsCheck = numSupAtoms/
(qCoarseGrid[0]*qCoarseGrid[1]*qCoarseGrid[2]);
if (numAtomsCheck != numAtoms) {
Error("IFC3s seem to come from a cell with a different number\n"
"of atoms than the IFC2s. Check your inputs."
"FC2 atoms: " + std::to_string(numAtoms) +
" FC3 atoms: " + std::to_string(numAtomsCheck));
}
// convert std::vectors to Eigen formats required by the
// next part of phoebe
Eigen::MatrixXd supPositions(numSupAtoms, 3);
for ( int n = 0; n < numSupAtoms; n++) {
for (int i : {0, 1, 2}) {
supPositions(n,i) = supPositionsVec[n][i];
}
}
// convert distances to Bohr
lattice *= distanceConversion;
// convert positions to cartesian, in bohr
for (int i = 0; i < numSupAtoms; i++) {
Eigen::Vector3d temp(supPositions(i, 0), supPositions(i, 1),
supPositions(i, 2));
Eigen::Vector3d temp2 = lattice.transpose() * temp;
supPositions(i, 0) = temp2(0);
supPositions(i, 1) = temp2(1);
supPositions(i, 2) = temp2(2);
}
// Open the hdf5 file containing the IFC3s
// ===================================================
fileName = context.getPhFC3FileName();
if (fileName.empty()) {
Error("Phono3py phFC3FileName (fc3.hdf5) file not "
"specified in input file.");
}
if (mpi->mpiHead())
std::cout << "Reading in " + fileName + "." << std::endl;
// user info about memory
// note, this is for a temporary array --
// later we reduce to (numAtoms*3)^3 * numRVecs
{
double rx;
double x = pow(numSupAtoms * 3, 3) / pow(1024., 3) * sizeof(rx);
if (mpi->mpiHead()) {
std::cout << "Allocating " << x
<< " (GB) (per MPI process) for the 3-ph coupling matrix."
<< std::endl;
}
}
// set up buffer to read entire matrix
// have to use this monstrosity because the
// phono3py data is shaped as a 6 dimensional array,
// and eigen tensor is not supported by highFive
std::vector<
std::vector<std::vector<std::vector<std::vector<std::vector<double>>>>>>
ifc3Tensor;
std::vector<int> cellMap;
try {
HighFive::File file(fileName, HighFive::File::ReadOnly);
// Set up hdf5 datasets
HighFive::DataSet difc3 = file.getDataSet("/fc3");
HighFive::DataSet dcellMap = file.getDataSet("/p2s_map");
// read in the ifc3 data
difc3.read(ifc3Tensor);
dcellMap.read(cellMap);
} catch (std::exception &error) {
if(mpi->mpiHead()) std::cout << error.what() << std::endl;
Error("Issue reading fc3.hdf5 file. Make sure it exists at " + fileName +
"\n and is not open by some other persisting processes.");
}
// Determine the list of possible R2, R3 vectors
// the distances from the origin unit cell to another
// unit cell in the positive quadrant superCell
Eigen::MatrixXd cellPositions(3, nr);
cellPositions.setZero();
// get all possible ws cell vectors
Eigen::MatrixXd rws = wsInit(crystal, qCoarseGrid);
// find all possible vectors R2, R3, which are
// position of atomPosSuperCell - atomPosUnitCell = R
for (int is = 0; is < nr; is++) {
cellPositions(0, is) = supPositions(is, 0) - supPositions(0, 0);
cellPositions(1, is) = supPositions(is, 1) - supPositions(0, 1);
cellPositions(2, is) = supPositions(is, 2) - supPositions(0, 2);
}
// reshape to FC3 format
Eigen::Tensor<double, 5> FC3;
auto tup = reorderDynamicalMatrix(crystal, qCoarseGrid, rws, FC3,
cellPositions, ifc3Tensor, cellMap);
auto bravaisVectors2 = std::get<0>(tup);
auto weights2 = std::get<1>(tup);
auto bravaisVectors3 = std::get<2>(tup);
auto weights3 = std::get<3>(tup);
if (mpi->mpiHead()) {
std::cout << "Successfully parsed anharmonic "
"phono3py files.\n"
<< std::endl;
}
// Create interaction3Ph object
Interaction3Ph interaction3Ph(crystal, FC3, bravaisVectors2, bravaisVectors3,
weights2, weights3);
return interaction3Ph;
#endif
}
Interaction3Ph IFC3Parser::parseFromShengBTE(Context &context,
Crystal &crystal) {
auto fileName = context.getPhFC3FileName();
// Open IFC3 file
std::ifstream infile(fileName);
std::string line;
if (not infile.is_open()) {
Error("FC3 file not found");
}
if (mpi->mpiHead())
std::cout << "Reading in " + fileName + "." << std::endl;
// Number of triplets
std::getline(infile, line);
int numTriplets = std::stoi(line);
// user info about memory
{
double rx;
double x = 27 * numTriplets / pow(1024., 3) * sizeof(rx);
if (mpi->mpiHead()) {
std::cout << "Allocating " << x
<< " (GB) (per MPI process) for the 3-ph coupling matrix.\n"
<< std::endl;
}
}
// Allocate quantities to be read
Eigen::Tensor<double, 4> ifc3Tensor(3, 3, 3, numTriplets);
ifc3Tensor.setZero();
Eigen::Tensor<double, 3> cellPositions(numTriplets, 2, 3);
cellPositions.setZero();
Eigen::Tensor<int, 2> displacedAtoms(numTriplets, 3);
displacedAtoms.setZero();
for (int i = 0; i < numTriplets; i++) {// loop over all triplets
// empty line
std::getline(infile, line);
// line with a counter
std::getline(infile, line);
// Read position of 2nd cell
std::getline(infile, line);
std::istringstream iss(line);
std::string item;
int j = 0;
while (iss >> item) {
cellPositions(i, 0, j) = std::stod(item) / distanceBohrToAng;
j++;
}
// Read position of 3rd cell
std::getline(infile, line);
std::istringstream iss2(line);
j = 0;
while (iss2 >> item) {
cellPositions(i, 1, j) = std::stod(item) / distanceBohrToAng;
j++;
}
// Read triplet atom indices
std::getline(infile, line);
std::istringstream iss3(line);
j = 0;
int i0;
while (iss3 >> i0) {
displacedAtoms(i, j) = i0 - 1;
j++;
}
// Read the 3x3x3 force constants tensor
int i1, i2, i3;
double d4;
double conversion = pow(distanceBohrToAng, 3) / energyRyToEv;
for (int a : {0, 1, 2}) {
for (int b : {0, 1, 2}) {
for (int c : {0, 1, 2}) {
std::getline(infile, line);
std::istringstream iss4(line);
while (iss4 >> i1 >> i2 >> i3 >> d4) {
ifc3Tensor(c, b, a, i) = d4 * conversion;
}
}
}
}
}
// Close IFC3 file
infile.close();
// TODO Round cellPositions to the nearest lattice vectors
// start processing ifc3s into FC3 matrix
int numAtoms = crystal.getNumAtoms();
int numBands = numAtoms * 3;
int nr2 = 0;
int nr3 = 0;
std::vector<Eigen::Vector3d> tmpCellPositions2, tmpCellPositions3;
for (int it = 0; it < numTriplets; it++) {
// load the position of the 2 atom in the current triplet
Eigen::Vector3d position2, position3;
for (int ic : {0, 1, 2}) {
position2(ic) = cellPositions(it, 0, ic);
position3(ic) = cellPositions(it, 1, ic);
}
// now check if this element is in the list.
bool found2 = false;
if (std::find(tmpCellPositions2.begin(), tmpCellPositions2.end(),
position2)
!= tmpCellPositions2.end()) {
found2 = true;
}
bool found3 = false;
if (std::find(tmpCellPositions3.begin(), tmpCellPositions3.end(),
position3)
!= tmpCellPositions3.end()) {
found3 = true;
}
if (!found2) {
tmpCellPositions2.push_back(position2);
nr2++;
}
if (!found3) {
tmpCellPositions3.push_back(position3);
nr3++;
}
}
Eigen::MatrixXd cellPositions2(3, nr2);
Eigen::MatrixXd cellPositions3(3, nr3);
cellPositions2.setZero();
cellPositions3.setZero();
for (int i = 0; i < nr2; i++) {
cellPositions2.col(i) = tmpCellPositions2[i];
}
for (int i = 0; i < nr3; i++) {
cellPositions3.col(i) = tmpCellPositions3[i];
}
Eigen::Tensor<double, 5> FC3(numBands, numBands, numBands, nr2, nr3);
FC3.setZero();
for (int it = 0; it < numTriplets; it++) {// sum over all triplets
int ia1 = displacedAtoms(it, 0);
int ia2 = displacedAtoms(it, 1);
int ia3 = displacedAtoms(it, 2);
Eigen::Vector3d position2, position3;
for (int ic : {0, 1, 2}) {
position2(ic) = cellPositions(it, 0, ic);
position3(ic) = cellPositions(it, 1, ic);
}
int ir2 = findIndexRow(cellPositions2, position2);
int ir3 = findIndexRow(cellPositions3, position3);
for (int ic1 : {0, 1, 2}) {
for (int ic2 : {0, 1, 2}) {
for (int ic3 : {0, 1, 2}) {
auto ind1 = compress2Indices(ia1, ic1, numAtoms, 3);
auto ind2 = compress2Indices(ia2, ic2, numAtoms, 3);
auto ind3 = compress2Indices(ia3, ic3, numAtoms, 3);
FC3(ind1, ind2, ind3, ir3, ir2) = ifc3Tensor(ic3, ic2, ic1, it);
}
}
}
}
Eigen::Tensor<double, 3> weights(nr2, numAtoms, numAtoms);
weights.setConstant(1.);
Interaction3Ph interaction3Ph(crystal, FC3, cellPositions2,
cellPositions3, weights, weights);
if (mpi->mpiHead()) {
std::cout << "Successfully parsed anharmonic "
"ShengBTE files.\n"
<< std::endl;
}
return interaction3Ph;
}
| 27,001 | 9,673 |
/******************************************************************************\
* *
* ____ _ _ _ *
* | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ *
* | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| *
* | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | *
* |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| *
* *
* *
* *
* Copyright (C) 2011 - 2014 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* Distributed under the Boost Software License, Version 1.0. See *
* accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt *
\******************************************************************************/
#ifndef BOOST_ACTOR_RESPONSE_PROMISE_HPP
#define BOOST_ACTOR_RESPONSE_PROMISE_HPP
#include "boost/actor/actor.hpp"
#include "boost/actor/message.hpp"
#include "boost/actor/actor_addr.hpp"
#include "boost/actor/message_id.hpp"
namespace boost {
namespace actor {
/**
* @brief A response promise can be used to deliver a uniquely identifiable
* response message from the server (i.e. receiver of the request)
* to the client (i.e. the sender of the request).
*/
class response_promise {
public:
response_promise() = default;
response_promise(response_promise&&) = default;
response_promise(const response_promise&) = default;
response_promise& operator=(response_promise&&) = default;
response_promise& operator=(const response_promise&) = default;
response_promise(const actor_addr& from,
const actor_addr& to,
const message_id& response_id);
/**
* @brief Queries whether this promise is still valid, i.e., no response
* was yet delivered to the client.
*/
inline explicit operator bool() const {
// handle is valid if it has a receiver
return static_cast<bool>(m_to);
}
/**
* @brief Sends @p response_message and invalidates this handle afterwards.
*/
void deliver(message response_message);
private:
actor_addr m_from;
actor_addr m_to;
message_id m_id;
};
} // namespace actor
} // namespace boost
#endif // BOOST_ACTOR_RESPONSE_PROMISE_HPP
| 2,806 | 788 |
// 33. Tabular printing of a list of processes
// Suppose you have a snapshot of the list of all processes in a system. The
// information for each process includes name, identifier, status (which can be
// either running or suspended), account name (under which the process runs),
// memory size in bytes, and platform (which can be either 32-bit or 64-bit). Your
// task is to writer a function that takes such a list of processes and prints them
// to the console alphabetically, in tabular format. All columns must be left-
// aligned, except for the memory column which must be right-aligned. The value
// of the memory size must be displayed in KB. The following is an example of the
// output of this function:
// chrome.exe 1044 Running marius.bancila 25180 32-bit
// chrome.exe 10100 Running marius.bancila 227756 32-bit
// cmd.exe 512 Running SYSTEM 48 64-bit
// explorer.exe 7108 Running marius.bancila 29529 64-bit
// skype.exe 22456 Syspended marius.bancila 656 64-bit
// 33. ํ๋ก ์ ๋ฆฌ๋ ํ๋ก์ธ์ค๋ค์ ๋ชฉ๋ก์ ์ถ๋ ฅ
// ๋น์ ์ด ์ด๋ค ์์คํ
์ ๋ชจ๋ ํ๋ก์ธ์ค๋ค์ ๋ชฉ๋ก์ ์ค๋
์ท์ผ๋ก ๊ฐ์ง๊ณ ์๋ค๊ณ ๊ฐ์ ํ์. ๊ฐ ํ๋ก์ธ
// ์ค์ ์ ๋ณด๋ ์ด๋ฆ, ์๋ณ์, ์ํ(running ๋๋ suspended ๋ ๊ฐ์ง ์ํ์ผ ์ ์๋ค), ๊ณ์ ์ด๋ฆ
// (ํ๋ก์ธ์ค๊ฐ ๋์์ค์ธ ๊ณ์ ), ๋ฉ๋ชจ๋ฆฌ ํฌ๊ธฐ(byte), ๊ทธ๋ฆฌ๊ณ ํ๋ซํผ(32-bit ๋๋ 64-bit ์ผ ์ ์
// ๋ค)์ ํฌํจํ๋ค. ๋น์ ์ ์๋ฌด๋ ํ๋ก์ธ์ค์ ๋ชฉ๋ก์ ๊ฐ์ ธ์์, ์ฝ์์ ์ํ๋ฒณ ํ์ ํ์์ผ๋ก ๋ชฉ๋ก
// ์ ์ถ๋ ฅํ๋ ํจ์๋ฅผ ์์ฑํ๋ ๊ฒ์ด๋ค. ๋ชจ๋ ์ปฌ๋ผ์ ๋ฐ๋์ left-aligned ์ฌ์ผ ํ๋ฉฐ, ๋ฉ๋ชจ๋ฆฌ ์ปฌ๋ผ
// ๋ง ์์ธ์ ์ผ๋ก right-aligned ์ด๋ค. ๋ฉ๋ชจ๋ฆฌ ํฌ๊ธฐ ๊ฐ์ ๋ฐ๋์ KB๋ก ๋ณด์ฌ์ ธ์ผ ํ๋ค. ์๋์ ๋ณด์ฌ
// ์ง๋ ๊ฒ์, ์ด ํ๋ง์์ ์ถ๋ ฅ ์์ ์ด๋ค:
// chrome.exe 1044 Running marius.bancila 25180 32-bit
// chrome.exe 10100 Running marius.bancila 227756 32-bit
// cmd.exe 512 Running SYSTEM 48 64-bit
// explorer.exe 7108 Running marius.bancila 29529 64-bit
// skype.exe 22456 Syspended marius.bancila 656 64-bit
#include "gsl/gsl"
// create `main` function for catch
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
// Redirect CMake's #define to C++ constexpr string
constexpr auto TestName = PROJECT_NAME_STRING;
TEST_CASE("tokenize", "[Joining strings]") {
} | 1,927 | 1,082 |
#include "ui_object.h"
#include "../shader_manager.h"
#include "../shaders/ui/ui_object_shader.h"
#include "../../util/mesh_factory.h"
#include <algorithm>
namespace hyperion {
namespace ui {
UIObject::UIObject(const std::string &name)
: Node(name)
{
GetMaterial().depth_test = false;
GetMaterial().depth_write = false;
GetMaterial().alpha_blended = true;
SetRenderable(MeshFactory::CreateQuad());
GetRenderable()->SetShader(ShaderManager::GetInstance()->GetShader<UIObjectShader>(ShaderProperties()));
GetSpatial().SetBucket(Spatial::Bucket::RB_SCREEN);
}
void UIObject::UpdateTransform()
{
Node::UpdateTransform();
}
bool UIObject::IsMouseOver(double x, double y) const
{
if (x < GetGlobalTranslation().x) {
return false;
}
if (x > GetGlobalTranslation().x + GetGlobalScale().x) {
return false;
}
if (y < GetGlobalTranslation().y) {
return false;
}
if (y > GetGlobalTranslation().y + GetGlobalScale().y) {
return false;
}
return true;
}
} // namespace ui
} // namespace hyperion
| 1,090 | 365 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* representation of a dummy attribute targeted by <animateMotion> element */
#include "SVGMotionSMILAttr.h"
#include "SVGMotionSMILType.h"
#include "nsISMILAnimationElement.h"
#include "nsSMILValue.h"
#include "nsAttrValue.h"
#include "nsGkAtoms.h"
#include "nsDebug.h"
#include "nsCRT.h"
#include "nsSVGLength2.h"
#include "nsSMILParserUtils.h"
namespace mozilla {
nsresult
SVGMotionSMILAttr::ValueFromString(const nsAString& aStr,
const nsISMILAnimationElement* aSrcElement,
nsSMILValue& aValue,
bool& aPreventCachingOfSandwich) const
{
NS_NOTREACHED("Shouldn't using nsISMILAttr::ValueFromString for parsing "
"animateMotion's SMIL values.");
return NS_ERROR_FAILURE;
}
nsSMILValue
SVGMotionSMILAttr::GetBaseValue() const
{
return nsSMILValue(&SVGMotionSMILType::sSingleton);
}
void
SVGMotionSMILAttr::ClearAnimValue()
{
mSVGElement->SetAnimateMotionTransform(nullptr);
}
nsresult
SVGMotionSMILAttr::SetAnimValue(const nsSMILValue& aValue)
{
gfxMatrix matrix = SVGMotionSMILType::CreateMatrix(aValue);
mSVGElement->SetAnimateMotionTransform(&matrix);
return NS_OK;
}
const nsIContent*
SVGMotionSMILAttr::GetTargetNode() const
{
return mSVGElement;
}
} // namespace mozilla
| 1,608 | 554 |